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
dahlstrom-g/intellij-community
plugins/kotlin/performance-tests/performance-test-utils/test/org/jetbrains/kotlin/idea/performance/tests/utils/projectRoutines.kt
2
6097
// 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.performance.tests.utils import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.startup.impl.StartupManagerImpl import com.intellij.lang.LanguageAnnotators import com.intellij.lang.LanguageExtensionPoint import com.intellij.lang.annotation.Annotator import com.intellij.openapi.Disposable import com.intellij.openapi.application.impl.NonBlockingReadActionImpl import com.intellij.openapi.editor.Document import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.impl.PsiDocumentManagerBase import com.intellij.psi.search.FilenameIndex import com.intellij.psi.search.GlobalSearchScope import com.intellij.testFramework.ExtensionTestUtil import com.intellij.testFramework.TestApplicationManager import com.intellij.testFramework.runInEdtAndWait import com.intellij.util.ui.UIUtil import junit.framework.TestCase import org.jetbrains.kotlin.idea.core.util.toPsiFile import java.nio.file.Paths fun commitAllDocuments() { val fileDocumentManager = FileDocumentManager.getInstance() runInEdtAndWait { fileDocumentManager.saveAllDocuments() } ProjectManagerEx.getInstanceEx().openProjects.forEach { project -> val psiDocumentManagerBase = PsiDocumentManager.getInstance(project) as PsiDocumentManagerBase runInEdtAndWait { psiDocumentManagerBase.clearUncommittedDocuments() psiDocumentManagerBase.commitAllDocuments() } } } fun commitDocument(project: Project, document: Document) { val psiDocumentManagerBase = PsiDocumentManager.getInstance(project) as PsiDocumentManagerBase runInEdtAndWait { psiDocumentManagerBase.commitDocument(document) } } fun saveDocument(document: Document) { val fileDocumentManager = FileDocumentManager.getInstance() runInEdtAndWait { fileDocumentManager.saveDocument(document) } } fun dispatchAllInvocationEvents() { runInEdtAndWait { UIUtil.dispatchAllInvocationEvents() NonBlockingReadActionImpl.waitForAsyncTaskCompletion() } } fun loadProjectWithName(path: String, name: String): Project? = ProjectManagerEx.getInstanceEx().openProject(Paths.get(path), OpenProjectTask(projectName = name)) fun TestApplicationManager.closeProject(project: Project) { val name = project.name val startupManagerImpl = StartupManager.getInstance(project) as StartupManagerImpl val daemonCodeAnalyzerSettings = DaemonCodeAnalyzerSettings.getInstance() val daemonCodeAnalyzerImpl = DaemonCodeAnalyzer.getInstance(project) as DaemonCodeAnalyzerImpl setDataProvider(null) daemonCodeAnalyzerSettings.isImportHintEnabled = true // return default value to avoid unnecessary save startupManagerImpl.checkCleared() daemonCodeAnalyzerImpl.cleanupAfterTest() logMessage { "project '$name' is about to be closed" } dispatchAllInvocationEvents() ProjectManagerEx.getInstanceEx().forceCloseProject(project) logMessage { "project '$name' successfully closed" } } fun replaceWithCustomHighlighter(parentDisposable: Disposable, fromImplementationClass: String, toImplementationClass: String) { val pointName = ExtensionPointName.create<LanguageExtensionPoint<Annotator>>(LanguageAnnotators.EP_NAME.name) val extensionPoint = pointName.getPoint(null) val point = LanguageExtensionPoint<Annotator>() point.language = "kotlin" point.implementationClass = toImplementationClass val extensions = extensionPoint.extensions val filteredExtensions = extensions.filter { it.language != "kotlin" || it.implementationClass != fromImplementationClass } .toList() // custom highlighter is already registered if filteredExtensions has the same size as extensions if (filteredExtensions.size < extensions.size) { ExtensionTestUtil.maskExtensions(pointName, filteredExtensions + listOf(point), parentDisposable) } } fun projectFileByName(project: Project, name: String): PsiFile { fun baseName(name: String): String { val index = name.lastIndexOf("/") return if (index > 0) name.substring(index + 1) else name } val fileManager = VirtualFileManager.getInstance() val url = "${project.guessProjectDir()}/$name" fileManager.refreshAndFindFileByUrl(url)?.let { return it.toPsiFile(project)!! } val baseFileName = baseName(name) val projectBaseName = baseName(project.name) val virtualFiles = FilenameIndex.getVirtualFilesByName( project, baseFileName, true, GlobalSearchScope.projectScope(project) ) .filter { it.canonicalPath?.contains("/$projectBaseName/$name") ?: false }.toList() TestCase.assertEquals( "expected the only file with name '$name'\n, it were: [${virtualFiles.map { it.canonicalPath }.joinToString("\n")}]", 1, virtualFiles.size ) return virtualFiles.iterator().next().toPsiFile(project)!! } fun Project.relativePath(file: VirtualFile): String { val basePath = guessProjectDir() ?: error("don't use it for a default project $this") return FileUtil.getRelativePath(basePath.toNioPath().toFile(), file.toNioPath().toFile()) ?: error("$file is not located within a project $this") }
apache-2.0
b1f73983e9b6f6619389db485ffbe9c2
39.926174
158
0.774151
5.055556
false
true
false
false
dahlstrom-g/intellij-community
tools/intellij.ide.starter/src/com/intellij/ide/starter/exec/ExecOutputRedirect.kt
4
2299
package com.intellij.ide.starter.exec import com.intellij.ide.starter.exec.ExecOutputRedirect.* import com.intellij.ide.starter.utils.logOutput import java.io.File import java.io.PrintWriter import kotlin.io.path.createDirectories /** * Specifies how a child process' stdout or stderr must be redirected in the current process: * - [NoRedirect] * - [ToFile] * - [ToStdOut] */ sealed class ExecOutputRedirect { open fun open() = Unit open fun close() = Unit open fun redirectLine(line: String) = Unit abstract fun read(): String abstract override fun toString(): String protected fun reportOnStdoutIfNecessary(line: String) { // Propagate the IDE debugger attach service message. if (line.contains("Listening for transport dt_socket")) { println(line) } } object NoRedirect : ExecOutputRedirect() { override fun redirectLine(line: String) { reportOnStdoutIfNecessary(line) } override fun read() = "" override fun toString() = "ignored" } data class ToFile(val outputFile: File) : ExecOutputRedirect() { private lateinit var writer: PrintWriter override fun open() { outputFile.apply { toPath().parent.createDirectories() createNewFile() } writer = outputFile.printWriter() } override fun close() { writer.close() } override fun redirectLine(line: String) { reportOnStdoutIfNecessary(line) writer.println(line) } override fun read(): String { if (!outputFile.exists()) { logOutput("File $outputFile doesn't exist") return "" } return outputFile.readText() } override fun toString() = "file $outputFile" } data class ToStdOut(val prefix: String) : ExecOutputRedirect() { override fun redirectLine(line: String) { reportOnStdoutIfNecessary(line) logOutput(" $prefix $line") } override fun read() = "" override fun toString() = "stdout" } class ToString : ExecOutputRedirect() { private val stringBuilder = StringBuilder() override fun redirectLine(line: String) { reportOnStdoutIfNecessary(line) stringBuilder.appendLine(line) } override fun read() = stringBuilder.toString() override fun toString() = "string" } }
apache-2.0
c82fb58bba835ed961689af80e20e276
21.772277
93
0.668117
4.438224
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/CreateAllServicesAndExtensionsAction.kt
3
9649
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("TestOnlyProblems", "ReplaceGetOrSet") package com.intellij.ide.plugins import com.intellij.diagnostic.PluginException import com.intellij.ide.AppLifecycleListener import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.plugins.cl.PluginClassLoader import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.extensions.impl.ExtensionPointImpl import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.runModalTask import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.psi.stubs.StubElementTypeHolderEP import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.util.getErrorsAsString import io.github.classgraph.AnnotationEnumValue import io.github.classgraph.ClassGraph import io.github.classgraph.ClassInfo import kotlin.properties.Delegates.notNull @Suppress("HardCodedStringLiteral") private class CreateAllServicesAndExtensionsAction : AnAction("Create All Services And Extensions"), DumbAware { override fun actionPerformed(e: AnActionEvent) { val errors = mutableListOf<Throwable>() runModalTask("Creating All Services And Extensions", cancellable = true) { indicator -> val taskExecutor: (task: () -> Unit) -> Unit = { task -> try { task() } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { errors.add(e) } } // check first checkExtensionPoint(StubElementTypeHolderEP.EP_NAME.point as ExtensionPointImpl<*>, taskExecutor) checkContainer(ApplicationManager.getApplication() as ComponentManagerImpl, indicator, taskExecutor) ProjectUtil.getOpenProjects().firstOrNull()?.let { checkContainer(it as ComponentManagerImpl, indicator, taskExecutor) } indicator.text2 = "Checking light services..." checkLightServices(taskExecutor, errors) } if (errors.isNotEmpty()) { logger<ComponentManagerImpl>().error(getErrorsAsString(errors)) } // some errors are not thrown but logged val message = (if (errors.isEmpty()) "No errors" else "${errors.size} errors were logged") + ". Check also that no logged errors." Notification("Error Report", "", message, NotificationType.INFORMATION).notify(null) } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } } private class CreateAllServicesAndExtensionsActivity : AppLifecycleListener { init { if (!ApplicationManager.getApplication().isInternal || !java.lang.Boolean.getBoolean("ide.plugins.create.all.services.and.extensions")) { throw ExtensionNotApplicableException.create() } } override fun appStarted() = ApplicationManager.getApplication().invokeLater { performAction() } } fun performAction() { val actionManager = ActionManager.getInstance() actionManager.tryToExecute( actionManager.getAction(ACTION_ID), null, null, ActionPlaces.UNKNOWN, true, ) } // external usage in [src/com/jetbrains/performancePlugin/commands/chain/generalCommandChain.kt] const val ACTION_ID = "CreateAllServicesAndExtensions" @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") private val badServices = java.util.Set.of( "com.intellij.usageView.impl.UsageViewContentManagerImpl", "com.jetbrains.python.scientific.figures.PyPlotToolWindow", "com.intellij.analysis.pwa.analyser.PwaServiceImpl", "com.intellij.analysis.pwa.view.toolwindow.PwaProblemsViewImpl", ) @Suppress("HardCodedStringLiteral") private fun checkContainer(container: ComponentManagerImpl, indicator: ProgressIndicator, taskExecutor: (task: () -> Unit) -> Unit) { indicator.text2 = "Checking ${container.activityNamePrefix()}services..." ComponentManagerImpl.createAllServices(container, badServices) indicator.text2 = "Checking ${container.activityNamePrefix()}extensions..." container.extensionArea.processExtensionPoints { extensionPoint -> // requires a read action if (extensionPoint.name == "com.intellij.favoritesListProvider" || extensionPoint.name == "org.jetbrains.kotlin.defaultErrorMessages") { return@processExtensionPoints } checkExtensionPoint(extensionPoint, taskExecutor) } } private fun checkExtensionPoint(extensionPoint: ExtensionPointImpl<*>, taskExecutor: (task: () -> Unit) -> Unit) { var extensionClass: Class<out Any> by notNull() taskExecutor { extensionClass = extensionPoint.extensionClass } extensionPoint.checkImplementations { extension -> taskExecutor { val extensionInstance: Any try { extensionInstance = (extension.createInstance(extensionPoint.componentManager) ?: return@taskExecutor) } catch (e: Exception) { throw PluginException("Failed to instantiate extension (extension=$extension, pointName=${extensionPoint.name})", e, extension.pluginDescriptor.pluginId) } if (!extensionClass.isInstance(extensionInstance)) { throw PluginException("$extension does not implement $extensionClass", extension.pluginDescriptor.pluginId) } } } } private fun checkLightServices(taskExecutor: (task: () -> Unit) -> Unit, errors: MutableList<Throwable>) { for (plugin in PluginManagerCore.getPluginSet().enabledPlugins) { // we don't check classloader for sub descriptors because url set is the same val classLoader = plugin.pluginClassLoader as? PluginClassLoader ?: continue ClassGraph() .enableAnnotationInfo() .ignoreParentClassLoaders() .overrideClassLoaders(classLoader) .scan() .use { scanResult -> val lightServices = scanResult.getClassesWithAnnotation(Service::class.java.name) for (lightService in lightServices) { if (lightService.name == "org.jetbrains.plugins.grails.runner.GrailsConsole" || lightService.name == "com.jetbrains.rdserver.editors.MultiUserCaretSynchronizerProjectService" || lightService.name == "com.intellij.javascript.web.webTypes.nodejs.WebTypesNpmLoader") { // wants EDT/read action in constructor continue } try { checkLightServiceOfModule(lightService = lightService, plugin = plugin, errors = errors, taskExecutor = taskExecutor) } catch (e: PluginException) { errors.add(e) } catch (e: Throwable) { errors.add(PluginException("Error on checking light services", e, plugin.pluginId)) } } } } } private fun checkLightServiceOfModule(lightService: ClassInfo, plugin: IdeaPluginDescriptorImpl, errors: MutableList<Throwable>, taskExecutor: (task: () -> Unit) -> Unit) { // not clear - from what classloader light service will be loaded in reality val lightServiceClass = loadLightServiceClass(lightService, plugin) ?: return val isProjectLevel: Boolean val isAppLevel: Boolean val annotationParameterValue = lightService.getAnnotationInfo(Service::class.java.name).parameterValues.find { it.name == "value" } if (annotationParameterValue == null) { isAppLevel = lightServiceClass.declaredConstructors.any { it.parameterCount == 0 } isProjectLevel = lightServiceClass.declaredConstructors.any { it.parameterCount == 1 && it.parameterTypes.get(0) == Project::class.java } } else { val list = annotationParameterValue.value as Array<*> isAppLevel = list.any { v -> (v as AnnotationEnumValue).valueName == Service.Level.APP.name } isProjectLevel = list.any { v -> (v as AnnotationEnumValue).valueName == Service.Level.PROJECT.name } } fun taskExecutorWithErrorHandling(task: () -> Unit) { taskExecutor { try { task() } catch (e: Throwable) { errors.add(PluginException("Cannot create $lightServiceClass", e, plugin.pluginId)) } } } if (isAppLevel) { taskExecutorWithErrorHandling { ApplicationManager.getApplication().getService(lightServiceClass) } } if (isProjectLevel) { taskExecutorWithErrorHandling { ProjectUtil.getOpenProjects().firstOrNull()?.getService(lightServiceClass) } } } private fun loadLightServiceClass(lightService: ClassInfo, plugin: IdeaPluginDescriptorImpl): Class<*>? { for (item in plugin.content.modules) { val descriptor = item.requireDescriptor() if (lightService.name.startsWith(descriptor.packagePrefix!!)) { // module is not loaded - dependency is not provided val classLoader = descriptor.pluginClassLoader as? PluginClassLoader ?: return null return classLoader.loadClass(lightService.name, true) } } // ok, or no plugin dependencies at all, or all are disabled, resolve from main try { return (plugin.pluginClassLoader as PluginClassLoader).loadClass(lightService.name, true) } catch (e: Exception) { throw PluginException("Cannot load $lightService", e, plugin.pluginId) } }
apache-2.0
1739162c27f9a8050fa3f06bc2a68c46
38.871901
134
0.721733
4.90544
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/actmain/ActMainAccount.kt
1
2547
package jp.juggler.subwaytooter.actmain import jp.juggler.subwaytooter.ActMain import jp.juggler.subwaytooter.column.fireShowColumnHeader import jp.juggler.subwaytooter.pref.PrefL import jp.juggler.subwaytooter.table.SavedAccount // デフォルトの投稿先アカウントを探す。アカウント選択が必要な状況ならnull val ActMain.currentPostTarget: SavedAccount? get() = phoneTab( { env -> val c = env.pagerAdapter.getColumn(env.pager.currentItem) return when { c == null || c.accessInfo.isPseudo -> null else -> c.accessInfo } }, { env -> val dbId = PrefL.lpTabletTootDefaultAccount() if (dbId != -1L) { val a = SavedAccount.loadAccount(this@currentPostTarget, dbId) if (a != null && !a.isPseudo) return a } val accounts = ArrayList<SavedAccount>() for (c in env.visibleColumns) { try { val a = c.accessInfo // 画面内に疑似アカウントがあれば常にアカウント選択が必要 if (a.isPseudo) { accounts.clear() break } // 既出でなければ追加する if (accounts.none { it == a }) accounts.add(a) } catch (ignored: Throwable) { } } return when (accounts.size) { // 候補が1つだけならアカウント選択は不要 1 -> accounts.first() // 候補が2つ以上ならアカウント選択は必要 else -> null } }) fun ActMain.reloadAccountSetting( newAccounts: ArrayList<SavedAccount> = SavedAccount.loadAccountList( this ), ) { for (column in appState.columnList) { val a = column.accessInfo if (!a.isNA) a.reloadSetting(this, newAccounts.find { it.acct == a.acct }) column.fireShowColumnHeader() } } fun ActMain.reloadAccountSetting(account: SavedAccount) { val newData = SavedAccount.loadAccount(this, account.db_id) ?: return for (column in appState.columnList) { val a = column.accessInfo if (a.acct != newData.acct) continue if (!a.isNA) a.reloadSetting(this, newData) column.fireShowColumnHeader() } }
apache-2.0
362fedb44c830f648fafe4bb14ca9649
31.328571
82
0.532362
4.18851
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/base/db/migrations/Migration5.kt
1
2440
/* * 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.base.db.migrations import androidx.sqlite.db.SupportSQLiteDatabase import androidx.room.migration.Migration object Migration5 : Migration(4, 5) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("DROP TABLE IF EXISTS ARROW") database.execSQL( "CREATE TABLE IF NOT EXISTS ARROW (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT," + "length TEXT," + "material TEXT," + "spine TEXT," + "weight TEXT," + "tip_wight TEXT," + "vanes TEXT," + "nock TEXT," + "comment TEXT," + "thumbnail BLOB," + "image TEXT)" ) database.execSQL("ALTER TABLE ROUND ADD COLUMN arrow INTEGER REFERENCES ARROW ON DELETE SET NULL") database.execSQL("ALTER TABLE ROUND ADD COLUMN comment TEXT DEFAULT ''") database.execSQL("ALTER TABLE SHOOT ADD COLUMN comment TEXT DEFAULT ''") database.execSQL("UPDATE ROUND SET target=0 WHERE target=1 OR target=2 OR target=3") database.execSQL("UPDATE ROUND SET target=2 WHERE target=5 OR target=6 OR target=7") database.execSQL("UPDATE ROUND SET target=3 WHERE target=4") database.execSQL("UPDATE ROUND SET target=4 WHERE target=8") database.execSQL("UPDATE ROUND SET target=5 WHERE target=9") database.execSQL("UPDATE ROUND SET target=6 WHERE target=10") database.execSQL( "UPDATE SHOOT SET points=2 WHERE _id IN (SELECT s._id " + "FROM ROUND r, PASSE p, SHOOT s LEFT JOIN BOW b ON b._id=r.bow " + "WHERE r._id=p.round AND s.passe=p._id " + "AND (r.bow=-2 OR b.type=1) AND s.points=1 AND r.target=3)" ) } }
gpl-2.0
eda1e8e15ad0c674fccf1e1cd3776338
43.363636
106
0.606557
4.436364
false
false
false
false
phylame/qaf
qaf-ixin/src/test/kotlin/Test.kt
1
658
import qaf.ixin.addAlignedComponents import qaf.ixin.x import java.awt.Component import javax.swing.* fun main(args: Array<String>) { val frame = JFrame() addAlignedComponents(frame.contentPane as JPanel, SwingConstants.TOP, BoxLayout.PAGE_AXIS, 5, JLabel("Haha").apply { alignmentX = Component.CENTER_ALIGNMENT }, JButton("Ok").apply { alignmentX = Component.CENTER_ALIGNMENT }, JCheckBox("Yes").apply { alignmentX = Component.CENTER_ALIGNMENT }, Box.createVerticalGlue()) frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE frame.size = 800 x 600 frame.isVisible = true }
apache-2.0
448e311cac16c89ae16a3f0a3560c35d
33.631579
97
0.677812
4.245161
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/features/distance/DistanceItemDecorator.kt
1
1825
/* * 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.distance import android.content.Context import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView import de.dreier.mytargets.R class DistanceItemDecorator(context: Context, private val gridSize: Int) : RecyclerView.ItemDecoration() { private val spaceHorizontal: Int = context.resources .getDimension(R.dimen.card_padding_horizontal).toInt() private val spaceVertical: Int = context.resources .getDimension(R.dimen.card_padding_vertical).toInt() override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { val position = parent.getChildAdapterPosition(view) if (position % gridSize == 0) { outRect.left = spaceHorizontal } else { outRect.left = spaceHorizontal / 4 } if ((position + 1) % gridSize == 0) { outRect.right = spaceHorizontal } else { outRect.right = spaceHorizontal / 4 } outRect.bottom = spaceVertical // Add top margin only for the first item to avoid double space between items if (position < gridSize) { outRect.top = spaceVertical } } }
gpl-2.0
3588d012a6964258fdb6f2d051c79a6a
31.589286
85
0.676712
4.608586
false
false
false
false
mctoyama/PixelServer
src/main/kotlin/org/pixelndice/table/pixelserver/connection/main/State02WaitingAuthRequest.kt
1
2617
package org.pixelndice.table.pixelserver.connection.main import org.apache.logging.log4j.LogManager import org.hibernate.Session import org.pixelndice.table.pixelprotocol.Protobuf import org.pixelndice.table.pixelserver.Bus import org.pixelndice.table.pixelserver.sessionFactory import org.pixelndice.table.pixelserverhibernate.Account private val logger = LogManager.getLogger(State02WaitingAuthRequest::class.java) class State02WaitingAuthRequest : State { override fun process(ctx: Context) { val p = ctx.channel.packet val resp = Protobuf.Packet.newBuilder() if (p != null) { if (p.payloadCase == Protobuf.Packet.PayloadCase.AUTHREQUEST) { logger.debug("Received authrequest") val authRequest = p.authRequest val email = authRequest.email val password = authRequest.password var account: Account? = null var session: Session? = null try { session = sessionFactory.openSession() account = Account.login(session, email, password) }catch (e: Exception){ Bus.post(Bus.Fatal(e.toString())) }finally { session?.close() } if( account == null ){ logger.trace("Login fail: $email") val authError = Protobuf.AuthError.newBuilder() authError.reason = "Login fail" resp.setAuthError(authError) ctx.state = StateStop() }else{ logger.trace("Login ok for: $email") ctx.account = account val tkResp = Protobuf.AuthResponse.newBuilder() val me = Protobuf.Account.newBuilder() me.id = ctx.account.id!! me.email = email me.name = ctx.account.name tkResp.setMe(me) resp.setAuthResponse(tkResp) ctx.state = State03JoinOrHostGame() } ctx.channel.packet = resp.build() } else { logger.error("Expecting auth request. Instead Received: $p") val rend = Protobuf.EndWithError.newBuilder() rend.reason = "key.errorexpectingauthrequest" resp.setEndWithError(rend) ctx.channel.packet = resp.build() ctx.state = StateStop() } } } }
bsd-2-clause
19f8721f9e8610de97577a4c0adc7d93
26.840426
80
0.538403
5.161736
false
false
false
false
substratum/template
app/src/main/kotlin/substratum/theme/template/AdvancedConstants.kt
1
2087
package substratum.theme.template object AdvancedConstants { // Custom message on theme launch, see theme_strings.xml for changing the dialog content // Set SHOW_DIALOG_REPEATEDLY to true if you want the dialog to be showed on every theme launch const val SHOW_LAUNCH_DIALOG = false const val SHOW_DIALOG_REPEATEDLY = false // Blacklisted APKs to prevent theme launching, these include simple regex formatting, without // full regex formatting (e.g. com.android. will block everything that starts with com.android.) val BLACKLISTED_APPLICATIONS = arrayOf( "cc.madkite.freedom", "zone.jasi2169.uretpatcher", "uret.jasi2169.patcher", "p.jasi2169.al3", "com.dimonvideo.luckypatcher", "com.chelpus.lackypatch", "com.forpda.lp", "com.android.vending.billing.InAppBillingService", "com.android.vending.billing.InAppBillingSorvice", "com.android.vendinc", "com.appcake", "ac.market.store", "org.sbtools.gamehack", "com.zune.gamekiller", "com.aag.killer", "com.killerapp.gamekiller", "cn.lm.sq", "net.schwarzis.game_cih", "org.creeplays.hack", "com.baseappfull.fwd", "com.zmapp", "com.dv.marketmod.installer", "org.mobilism.android", "com.blackmartalpha", "org.blackmart.market", "com.happymod.apk" ) // List of all organization theming systems officially supported by the team val ORGANIZATION_THEME_SYSTEMS = arrayOf( "projekt.substratum", "projekt.substratum.debug", "projekt.substratum.lite", "projekt.themer" ) // List of other theme systems that are officially unsupported by the team, but fully supported // by their corresponding organizations val OTHER_THEME_SYSTEMS = arrayOf( "com.slimroms.thememanager", "com.slimroms.omsbackend" ) }
apache-2.0
7dad1ec068e2a0ec4a5cdbfbe1e43460
36.945455
100
0.610446
3.975238
false
false
false
false
paplorinc/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/navigation/PsiElementNavigationTarget.kt
1
1295
// 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.codeInsight.navigation import com.intellij.ide.util.EditSourceUtil import com.intellij.navigation.NavigationTarget import com.intellij.navigation.TargetPresentation import com.intellij.pom.Navigatable import com.intellij.psi.PsiElement import org.jetbrains.annotations.ApiStatus.Experimental @Experimental class PsiElementNavigationTarget(private val myElement: PsiElement) : NavigationTarget { private val myNavigatable by lazy { if (myElement is Navigatable) myElement else EditSourceUtil.getDescriptor(myElement) } private val myPresentation by lazy { PsiElementTargetPresentation(myElement) } override fun isValid(): Boolean = myElement.isValid override fun getNavigatable(): Navigatable? = myNavigatable override fun getTargetPresentation(): TargetPresentation = myPresentation override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as PsiElementNavigationTarget if (myElement != other.myElement) return false return true } override fun hashCode(): Int { return myElement.hashCode() } }
apache-2.0
8fce13dd87952a0e8d4445136333b974
29.833333
140
0.778378
4.942748
false
false
false
false
google/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/providers/LineBookmarkProvider.kt
5
11394
// 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.ide.bookmark.providers import com.intellij.ide.bookmark.* import com.intellij.ide.bookmark.ui.tree.FileNode import com.intellij.ide.bookmark.ui.tree.LineNode import com.intellij.ide.projectView.ProjectViewNode import com.intellij.ide.projectView.impl.DirectoryUrl import com.intellij.ide.projectView.impl.PsiFileUrl import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.event.BulkAwareDocumentListener.Simple import com.intellij.openapi.editor.event.EditorMouseEvent import com.intellij.openapi.editor.event.EditorMouseEventArea import com.intellij.openapi.editor.event.EditorMouseListener import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.AsyncFileListener import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.psi.PsiCompiledElement import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.impl.smartPointers.SmartPointerEx import com.intellij.psi.util.PsiUtilCore import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.tree.project.ProjectFileNode import com.intellij.util.Alarm.ThreadToUse.POOLED_THREAD import com.intellij.util.SingleAlarm import com.intellij.util.ui.tree.TreeUtil import java.awt.event.MouseEvent import javax.swing.SwingUtilities import javax.swing.tree.TreePath class LineBookmarkProvider(private val project: Project) : BookmarkProvider, EditorMouseListener, Simple, AsyncFileListener { override fun getWeight() = Int.MIN_VALUE override fun getProject() = project override fun compare(bookmark1: Bookmark, bookmark2: Bookmark): Int { val fileBookmark1 = bookmark1 as? FileBookmark val fileBookmark2 = bookmark2 as? FileBookmark if (fileBookmark1 == null && fileBookmark2 == null) return 0 if (fileBookmark1 == null) return -1 if (fileBookmark2 == null) return 1 val file1 = fileBookmark1.file val file2 = fileBookmark2.file if (file1 == file2) { val lineBookmark1 = bookmark1 as? LineBookmark val lineBookmark2 = bookmark2 as? LineBookmark if (lineBookmark1 == null && lineBookmark2 == null) return 0 if (lineBookmark1 == null) return -1 if (lineBookmark2 == null) return 1 return lineBookmark1.line.compareTo(lineBookmark2.line) } if (file1.isDirectory && !file2.isDirectory) return -1 if (!file1.isDirectory && file2.isDirectory) return 1 return StringUtil.naturalCompare(file1.presentableName, file2.presentableName) } override fun prepareGroup(nodes: List<AbstractTreeNode<*>>): List<AbstractTreeNode<*>> { nodes.forEach { (it as? FileNode)?.ungroup() } // clean all file groups if needed val node = nodes.firstNotNullOfOrNull { it as? LineNode } ?: return nodes.filter(::isNodeVisible) // nothing to group if (node.bookmarksView?.groupLineBookmarks?.isSelected != true) return nodes.filter(::isNodeVisible) // grouping disabled val map = mutableMapOf<VirtualFile, FileNode?>() nodes.forEach { when (it) { is LineNode -> map.putIfAbsent(it.virtualFile, null) is FileNode -> map[it.virtualFile] = it } } // create fake file nodes to group corresponding line nodes map.mapNotNull { if (it.value == null) it.key else null }.forEach { map[it] = FileNode(project, FileBookmarkImpl(this, it)).apply { bookmarkGroup = node.bookmarkGroup parent = node.parent } } return nodes.mapNotNull { when { !isNodeVisible(it) -> null it is LineNode -> map[it.virtualFile]!!.grouped(it) it is FileNode -> it.grouped() else -> it } } } override fun createBookmark(map: Map<String, String>) = map["url"]?.let { createBookmark(it, StringUtil.parseInt(map["line"], -1)) } override fun createBookmark(context: Any?) = when (context) { // below // migrate old bookmarks and favorites is com.intellij.ide.bookmarks.Bookmark -> createBookmark(context.file, context.line) is DirectoryUrl -> createBookmark(context.url) is PsiFileUrl -> createBookmark(context.url) // above // migrate old bookmarks and favorites is PsiElement -> createBookmark(context) is VirtualFile -> createBookmark(context, -1) is ProjectFileNode -> createBookmark(context.virtualFile) is TreePath -> createBookmark(context) else -> null } fun createBookmark(file: VirtualFile, line: Int = -1): FileBookmark? = when { !file.isValid || file is LightVirtualFile -> null line >= 0 -> LineBookmarkImpl(this, file, line) else -> FileBookmarkImpl(this, file) } fun createBookmark(editor: Editor, line: Int? = null): FileBookmark? { if (editor.isOneLineMode) return null val file = FileDocumentManager.getInstance().getFile(editor.document) ?: return null return createBookmark(file, line ?: editor.caretModel.logicalPosition.line) } private fun createBookmark(url: String, line: Int = -1) = createValidBookmark(url, line) ?: createInvalidBookmark(url, line) private fun createValidBookmark(url: String, line: Int = -1) = VFM.findFileByUrl(url)?.let { createBookmark(it, line) } private fun createInvalidBookmark(url: String, line: Int = -1) = InvalidBookmark(this, url, line) private fun createBookmark(element: PsiElement): FileBookmark? { if (element is PsiFileSystemItem) return element.virtualFile?.let { createBookmark(it) } if (element is PsiCompiledElement) return null val file = PsiUtilCore.getVirtualFile(element) ?: return null if (file is LightVirtualFile) return null val document = FileDocumentManager.getInstance().getDocument(file) ?: return null return when (val offset = element.textOffset) { in 0..document.textLength -> createBookmark(file, document.getLineNumber(offset)) else -> null } } private fun createBookmark(path: TreePath): FileBookmark? { val file = path.asVirtualFile ?: return null val parent = path.parentPath?.asVirtualFile ?: return null // see com.intellij.ide.projectView.impl.ClassesTreeStructureProvider return if (!parent.isDirectory || file.parent != parent) null else createBookmark(file) } private val TreePath.asVirtualFile: VirtualFile? get() { val node = TreeUtil.getLastUserObject(ProjectViewNode::class.java, this) ?: return null node.virtualFile?.let { return it } // Workaround for KTIJ-21708 return when (val nodeValue = node.equalityObject) { is SmartPointerEx<*> -> nodeValue.virtualFile else -> null } } private val MouseEvent.isUnexpected // see MouseEvent.isUnexpected in ToggleBookmarkAction get() = !SwingUtilities.isLeftMouseButton(this) || isPopupTrigger || if (SystemInfo.isMac) !isMetaDown else !isControlDown private val EditorMouseEvent.isUnexpected get() = isConsumed || area != EditorMouseEventArea.LINE_MARKERS_AREA || mouseEvent.isUnexpected override fun mouseClicked(event: EditorMouseEvent) { if (event.isUnexpected) return event.editor.project?.let { if (it != project) return } val manager = BookmarksManager.getInstance(project) ?: return val bookmark = createBookmark(event.editor, event.logicalPosition.line) ?: return manager.getType(bookmark)?.let { manager.remove(bookmark) } ?: manager.add(bookmark, BookmarkType.DEFAULT) event.consume() } override fun afterDocumentChange(document: Document) { val file = FileDocumentManager.getInstance().getFile(document) ?: return if (file is LightVirtualFile) return val manager = BookmarksManager.getInstance(project) ?: return val map = sortedMapOf<LineBookmarkImpl, Int>(compareBy { it.line }) val set = mutableSetOf<Int>() for (bookmark in manager.bookmarks) { if (bookmark is LineBookmarkImpl && bookmark.file == file) { val rangeMarker = (manager as? BookmarksManagerImpl)?.findLineHighlighter(bookmark) ?: bookmark.descriptor.rangeMarker val line = rangeMarker?.let { if (it.isValid) it.document.getLineNumber(it.startOffset) else null } ?: -1 when (bookmark.line) { line -> set.add(line) else -> map[bookmark] = line } } } if (map.isEmpty()) return val bookmarks = mutableMapOf<Bookmark, Bookmark?>() map.forEach { (bookmark, line) -> bookmarks[bookmark] = when { line < 0 || set.contains(line) -> null else -> { set.add(line) createBookmark(file, line) } } } manager.update(bookmarks) } override fun prepareChange(events: List<VFileEvent>): AsyncFileListener.ChangeApplier? { val update = events.any { it is VFileCreateEvent || it is VFileDeleteEvent } if (update) validateAlarm.cancelAndRequest() return null } private val validateAlarm = SingleAlarm(::validateAndUpdate, 100, project, POOLED_THREAD) private fun validateAndUpdate() { val manager = BookmarksManager.getInstance(project) ?: return val bookmarks = mutableMapOf<Bookmark, Bookmark?>() manager.bookmarks.forEach { validate(it)?.run { bookmarks[it] = this } } manager.update(bookmarks) } private fun validate(bookmark: Bookmark) = when (bookmark) { is InvalidBookmark -> createValidBookmark(bookmark.url, bookmark.line) is FileBookmarkImpl -> bookmark.file.run { if (isValid) null else createBookmark(url) } is LineBookmarkImpl -> bookmark.file.run { if (isValid) null else createBookmark(url, bookmark.line) } else -> null } private fun isNodeVisible(node: AbstractTreeNode<*>) = (node.value as? InvalidBookmark)?.run { line < 0 } ?: true private val VFM get() = VirtualFileManager.getInstance() init { if (!project.isDefault) { val multicaster = EditorFactory.getInstance().eventMulticaster multicaster.addDocumentListener(this, project) multicaster.addEditorMouseListener(this, project) VFM.addAsyncFileListener(this, project) } } companion object { @JvmStatic fun find(project: Project): LineBookmarkProvider? = when { project.isDisposed -> null else -> BookmarkProvider.EP.findExtension(LineBookmarkProvider::class.java, project) } fun readLineText(bookmark: LineBookmark?) = bookmark?.let { readLineText(it.file, it.line) } fun readLineText(file: VirtualFile, line: Int): String? { val document = FileDocumentManager.getInstance().getDocument(file) ?: return null if (line < 0 || document.lineCount <= line) return null val start = document.getLineStartOffset(line) if (start < 0) return null val end = document.getLineEndOffset(line) if (end < start) return null return document.getText(TextRange.create(start, end)) } } }
apache-2.0
61b0f041546eb9c292c96642b52d3004
43.162791
134
0.725382
4.304496
false
false
false
false
dinosaurwithakatana/injection-helper
processor/src/main/java/io/dwak/injectionhelper/InjectionHelperProcessor.kt
1
4289
package io.dwak.injectionhelper import javax.annotation.processing.AbstractProcessor import javax.annotation.processing.Filer import javax.annotation.processing.Messager import javax.annotation.processing.ProcessingEnvironment import javax.annotation.processing.RoundEnvironment import javax.inject.Inject import javax.lang.model.SourceVersion import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.TypeElement import javax.lang.model.util.Elements import javax.tools.Diagnostic class InjectionHelperProcessor: AbstractProcessor() { private lateinit var env: ProcessingEnvironment private val filer: Filer by lazy { env.filer } private val messager: Messager by lazy { env.messager } private val elementUtils: Elements by lazy { env.elementUtils } override fun init(p0: ProcessingEnvironment) { super.init(p0) env = p0 } override fun getSupportedSourceVersion() = SourceVersion.latestSupported() override fun getSupportedAnnotationTypes() = mutableSetOf(Inject::class.java.canonicalName) override fun process(annotations: MutableSet<out TypeElement>, roundEnv: RoundEnvironment): Boolean { if (annotations.isNotEmpty()) { val injectionHelperTargetClassMap = hashMapOf<TypeElement, InjectionHelperBindingClass>() val erasedTargetNames =mutableSetOf<String>() annotations.map { roundEnv.getElementsAnnotatedWith(it) } .flatMap { it.filter { it.hasAnnotationWithName(Inject::class.java.simpleName) } } .filter { it.kind == ElementKind.FIELD } .forEach { try { val enclosingTypeElement = it.enclosingElement as TypeElement val injectionHelper = getOrCreateInjectionHelper(injectionHelperTargetClassMap, enclosingTypeElement, erasedTargetNames) injectionHelper.createAndAddBinding(it) } catch (e: Exception) { } } injectionHelperTargetClassMap.values .forEach { try { it.writeToFiler(filer) } catch (e: Exception) { messager.printMessage(Diagnostic.Kind.ERROR, e.message) } } } return true } private fun getOrCreateInjectionHelper(targetClassMap: MutableMap<TypeElement, InjectionHelperBindingClass>, enclosingElement: TypeElement, erasedTargetNames: MutableSet<String>) : InjectionHelperBindingClass { var injectionHelper = targetClassMap[enclosingElement] if (injectionHelper == null) { val targetCLass = enclosingElement.qualifiedName.toString() val classPackage = enclosingElement.packageName(elementUtils) val className = enclosingElement.className(classPackage) + InjectionHelperBindingClass.SUFFIX injectionHelper = InjectionHelperBindingClass(classPackage, className, targetCLass, processingEnv) targetClassMap.put(enclosingElement, injectionHelper) erasedTargetNames.add(enclosingElement.toString()) } return injectionHelper } @Suppress("unused") private fun error(element: Element, message: String, vararg args: Any) = messager.printMessage(Diagnostic.Kind.ERROR, String.format(message, args), element) @Suppress("unused") private fun note(note: String) = messager.printMessage(Diagnostic.Kind.NOTE, note) @Suppress("unused") private fun warning(note: String) = messager.printMessage(Diagnostic.Kind.WARNING, note) } /** * Returns {@code true} if the an annotation is found on the given element with the given class * name (not fully qualified). */ fun Element.hasAnnotationWithName(simpleName: String): Boolean { annotationMirrors.forEach { val annotationElement = it.annotationType.asElement() val annotationName = annotationElement.simpleName.toString() if (simpleName.equals(annotationName)) { return true } } return false } fun TypeElement.packageName(elementUtils: Elements) = elementUtils.getPackageOf(this).qualifiedName.toString() fun TypeElement.className(packageName: String): String { val packageLen = packageName.length + 1 return this.qualifiedName.toString().substring(packageLen).replace('.', '$') }
apache-2.0
55532fd43104502ed1a0b01b37375a72
37.294643
111
0.723945
4.969873
false
false
false
false
JetBrains/intellij-community
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/ParentAndChildWithNulls.kt
1
2827
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import kotlin.jvm.JvmName import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic import org.jetbrains.deft.annotations.Child import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity interface ParentWithNulls : WorkspaceEntity { val parentData: String @Child val child: ChildWithNulls? //region generated code @GeneratedCodeApiVersion(1) interface Builder : ParentWithNulls, WorkspaceEntity.Builder<ParentWithNulls>, ObjBuilder<ParentWithNulls> { override var entitySource: EntitySource override var parentData: String override var child: ChildWithNulls? } companion object : Type<ParentWithNulls, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(parentData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ParentWithNulls { val builder = builder() builder.parentData = parentData builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ParentWithNulls, modification: ParentWithNulls.Builder.() -> Unit) = modifyEntity( ParentWithNulls.Builder::class.java, entity, modification) //endregion interface ChildWithNulls : WorkspaceEntity { val childData: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : ChildWithNulls, WorkspaceEntity.Builder<ChildWithNulls>, ObjBuilder<ChildWithNulls> { override var entitySource: EntitySource override var childData: String } companion object : Type<ChildWithNulls, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(childData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ChildWithNulls { val builder = builder() builder.childData = childData builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ChildWithNulls, modification: ChildWithNulls.Builder.() -> Unit) = modifyEntity( ChildWithNulls.Builder::class.java, entity, modification) var ChildWithNulls.Builder.parentEntity: ParentWithNulls? by WorkspaceEntity.extension() //endregion val ChildWithNulls.parentEntity: ParentWithNulls? by WorkspaceEntity.extension()
apache-2.0
1133ffa707b1004d30348d8e94a3f6d1
31.125
128
0.766183
5.021314
false
false
false
false
stupacki/MultiFunctions
multi-functions/src/main/kotlin/io/multifunctions/models/Penta.kt
1
1289
package io.multifunctions.models import java.io.Serializable /** * Represents a generic penta of fife values. * * There is no meaning attached to values in this class, it can be used for any purpose. * Penta exhibits value semantics, i.e. two pentas are equal if all components are equal. * * @param A type of the first value. * @param B type of the second value. * @param C type of the second value. * @param D type of the second value. * @param E type of the second value. * @property first First value. * @property second Second value. * @property third Third value. * @property fourth Fourth value. * @property fifth Fifth value. * @constructor Creates a new instance of Penta. */ public data class Penta<out A, out B, out C, out D, out E>( val first: A, val second: B, val third: C, val fourth: D, val fifth: E ) : Serializable { /** * Returns string representation of the [Penta] including its [first], [second], [third], [fourth] and [fifth] values. */ override fun toString(): String = "Penta(first=$first, second=$second, third=$third, fourth=$fourth, fifth=$fifth)" } /** * Converts this penta into a list. */ public fun <T> Penta<T, T, T, T, T>.toList(): List<T> = listOf(first, second, third, fourth, fifth)
apache-2.0
1dce726c63ed1fb6de884cb1a75323f6
30.439024
122
0.672614
3.531507
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/ui/compose/feed/ExplainPermissionDialog.kt
1
1356
package com.nononsenseapps.feeder.ui.compose.feed import androidx.annotation.StringRes import androidx.compose.foundation.layout.padding import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.nononsenseapps.feeder.R @Composable fun ExplainPermissionDialog( @StringRes explanation: Int, onDismiss: () -> Unit, onOk: () -> Unit ) { AlertDialog( onDismissRequest = onDismiss, confirmButton = { Button(onClick = onOk) { Text(text = stringResource(id = android.R.string.ok)) } }, text = { Text( text = stringResource(id = explanation), style = MaterialTheme.typography.bodyLarge, modifier = Modifier .padding(vertical = 8.dp) ) } ) } @Composable @Preview private fun preview() = ExplainPermissionDialog( explanation = R.string.explanation_permission_notifications, onDismiss = {}, onOk = {} )
gpl-3.0
bdd9602a3605424c5c4c4d07abcc117c
27.851064
69
0.666667
4.581081
false
false
false
false
raybritton/json-query
lib/src/main/kotlin/com/raybritton/jsonquery/parsing/query/QueryExecutor.kt
1
3604
package com.raybritton.jsonquery.parsing.query import com.raybritton.jsonquery.RuntimeException import com.raybritton.jsonquery.ext.sort import com.raybritton.jsonquery.models.* import com.raybritton.jsonquery.models.Target import com.raybritton.jsonquery.tools.* /** * This class runs all the queries in order (deepest first) so the parent queries has the values needed */ internal class QueryExecutor { fun execute(json: Any, query: Query): Any { var targetJson = json var updatedQuery = query if (query.target is Target.TargetQuery) { targetJson = execute(json, query.target.query) updatedQuery = query.copy(target = Target.TargetField(".")) } return process(targetJson, updatedQuery) } private fun process(json: Any, query: Query): Any { val target = (query.target as Target.TargetField).value var updatedQuery = query //NAVIGATE var targetJson = json.navigateToTarget(target) targetJson = checkOffset(targetJson, query) if (updatedQuery.where != null) { (updatedQuery.where?.value as? Value.ValueQuery)?.let { val value = execute(targetJson, it.value) updatedQuery = updatedQuery.copy( where = updatedQuery.where!!.copy( value = Value.ValueString(value.toString()) )) } } //FILTER var workingJson: Any? = if (updatedQuery.where != null) targetJson.where(updatedQuery.where!!, updatedQuery.flags.isCaseSensitive, query.select?.offset) else targetJson if (workingJson == null) throw RuntimeException("Where returned null") workingJson = checkLimit(workingJson, query) //MATH (updatedQuery.select?.projection as? SelectProjection.Math)?.let { return workingJson!!.math(it.expr, it.field, updatedQuery.flags.isByElement) } //OUTPUT if (updatedQuery.flags.isDistinct) { if (workingJson is JsonArray) { workingJson = workingJson.distinct() } } if (updatedQuery.select?.orderBy != null) { workingJson = workingJson.sort(updatedQuery) } workingJson = workingJson?.filterToProjection(updatedQuery) workingJson.rewrite(updatedQuery) return workingJson!! } private fun checkLimit(json: Any, query: Query): Any { val limit = when (query.method) { Query.Method.SELECT -> query.select!!.limit Query.Method.DESCRIBE -> query.describe!!.limit else -> null } if (limit != null) { if (json is JsonArray) { return json.subList(0, Math.min(limit, json.size)) } else { throw RuntimeException("Tried to LIMIT on ${json::class.java}", RuntimeException.ExtraInfo.LIMIT_OBJECT) } } return json } private fun checkOffset(json: Any, query: Query): Any { val offset = when (query.method) { Query.Method.SELECT -> query.select!!.offset Query.Method.DESCRIBE -> query.describe!!.offset else -> null } if (offset != null) { if (json is JsonArray) { return json.subList(0, Math.min(offset, json.size - offset)) } else { throw RuntimeException("Tried to OFFSET on ${json::class.java}", RuntimeException.ExtraInfo.OFFSET_OBJECT) } } return json } }
apache-2.0
e8915bc9a5612ab5f7878fb2cea7afa8
32.073394
176
0.596837
4.579416
false
false
false
false
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/model/PortNumbers.kt
1
590
package no.skatteetaten.aurora.boober.model object PortNumbers { const val HTTP_PORT = 80 const val HTTPS_PORT = 443 const val INTERNAL_HTTP_PORT = 8080 const val INTERNAL_ADMIN_PORT = 8081 const val EXTRA_APPLICATION_PORT = 8082 const val TOXIPROXY_HTTP_PORT = 8090 const val CLINGER_PROXY_SERVER_PORT = 8100 const val CLINGER_MANAGEMENT_SERVER_PORT = 8101 const val TOXIPROXY_ADMIN_PORT = 8474 const val JOLOKIA_HTTP_PORT = 8778 const val NODE_PORT = 9090 const val DEFAULT_POSTGRES_PORT = 5432 const val DEFAULT_ORACLE_PORT = 1521 }
apache-2.0
3da28f99841ee7fd5a4716928579e66f
31.777778
51
0.713559
3.554217
false
false
false
false
neo4j-graphql/neo4j-graphql
src/main/kotlin/org/neo4j/graphql/GraphQLProcedure.kt
1
8695
package org.neo4j.graphql import graphql.ExecutionInput import graphql.schema.idl.SchemaPrinter import org.neo4j.graphdb.GraphDatabaseService import org.neo4j.graphdb.Node import org.neo4j.graphdb.Relationship import org.neo4j.graphql.procedure.VirtualNode import org.neo4j.graphql.procedure.VirtualRelationship import org.neo4j.logging.Log import org.neo4j.procedure.* import java.util.* import java.util.stream.Stream /** * @author mh * @since 29.10.16 */ class GraphQLProcedure { @Context @JvmField var db: GraphDatabaseService? = null @Context @JvmField var log: Log? = null class GraphQLResult(@JvmField val result: Map<String, Any>) class GraphResult(@JvmField val nodes: List<Node>,@JvmField val rels: List<Relationship>) @Procedure("graphql.execute", mode = Mode.WRITE) fun execute(@Name("query") query : String , @Name("variables",defaultValue = "{}") variables : Map<String,Any>, @Name(value = "operation",defaultValue = "") operation: String?) : Stream<GraphQLResult> { return doExecute(variables, query, operation) } @Procedure("graphql.query", mode = Mode.READ) fun query(@Name("query") query : String , @Name("variables",defaultValue = "{}") variables : Map<String,Any>, @Name(value = "operation",defaultValue = "") operation: String?) : Stream<GraphQLResult> { return doExecute(variables, query, operation) } @Procedure("graphql.reset", mode = Mode.READ) fun reset() { return GraphSchema.reset() } private fun doExecute(variables: Map<String, Any>, query: String, operation: String?): Stream<GraphQLResult> { val ctx = GraphQLContext(db!!, log!!, variables) val execution = ExecutionInput.Builder() .query(query).variables(variables).context(ctx).root(ctx) // todo proper mutation root if (!operation.isNullOrBlank()) execution.operationName(operation) val result = GraphSchema.getGraphQL(db!!).execute(execution.build()) if (result.errors.isEmpty()) { return Stream.of(GraphQLResult(result.getData())) } if (ctx.backLog.isNotEmpty()) { // todo report metadata } val errors = result.errors.joinToString("\n") throw RuntimeException("Error executing GraphQL Query:\n $errors") } data class StringResult(@JvmField val value: String?) @Procedure("graphql.idl", mode = Mode.WRITE) fun idl(@Name("idl") idl: String?) : Stream<StringResult> { if (idl==null) { GraphSchemaScanner.deleteIdl(db!!) return Stream.of(StringResult("Removed stored GraphQL Schema")) } else { val storeIdl = GraphSchemaScanner.storeIdl(db!!, idl) return Stream.of(StringResult(storeIdl.toString())) } } @UserFunction( "graphql.getIdl") fun getIdl() : String { val schema = GraphQLSchemaBuilder.buildSchema(db!!) return SchemaPrinter().print(schema) } @Procedure("graphql.schema") fun schema() : Stream<GraphResult> { GraphSchemaScanner.databaseSchema(db!!) val metaDatas = GraphSchemaScanner.allMetaDatas() val nodes = metaDatas.associate { val props = it.properties.values.associate { " "+it.fieldName to it.type.toString() } + ("name" to it.type) it.type to VirtualNode(listOf(it.type) + it.labels, props) } val rels = metaDatas.flatMap { n -> val node = nodes[n.type]!! n.relationships.values.map { rel -> VirtualRelationship(node, rel.fieldName, mapOf("type" to rel.type, "multi" to rel.multi), nodes[rel.label]!!) } } return Stream.of(GraphResult(nodes.values.toList(),rels)) } @UserFunction("graphql.runSingle") fun runSingle(@Name("query") query: String, @Name("variables",defaultValue = "{}") variables : Map<String,Any>) : Any? { val result = db!!.execute(query, variables) val firstColumn = result.columns()[0] return result.columnAs<Any>(firstColumn).next() } @UserFunction("graphql.runMany") fun runMany(@Name("query") query: String, @Name("variables",defaultValue = "{}") variables : Map<String,Any>) : List<*> { val result = db!!.execute(query, variables) val firstColumn = result.columns()[0] return result.columnAs<Any>(firstColumn).asSequence().toList() } @UserFunction("graphql.labels") fun labels(@Name("entity") entity: Any) : List<String> { return when (entity) { is Node -> entity.labels.map { it.name() } is Relationship -> listOf(entity.type.name()) is Map<*,*> -> entity.get("_labels") as List<String>? ?: emptyList<String>() else -> emptyList() } } data class Row(@JvmField val row:Any?) @Procedure("graphql.run", mode = Mode.WRITE) fun runProc(@Name("query") query: String, @Name("variables",defaultValue = "{}") variables : Map<String,Any>, @Name("expectMultipleValues", defaultValue = "true") expectMultipleValues : Boolean) : Stream<Row> { val result = if (expectMultipleValues) runMany(query, variables) else runSingle(query, variables) return if (result is List<*>) { result.stream().map { Row(it) } } else { Stream.of(Row(result)) } } data class Nodes(@JvmField val node:Node?) @Procedure("graphql.queryForNodes") fun queryForNodes(@Name("query") query: String, @Name("variables",defaultValue = "{}") variables : Map<String,Any>) : Stream<Nodes> { val result = db!!.execute(query, variables) val firstColumn = result.columns()[0] return result.columnAs<Node>(firstColumn).stream().map{ Nodes(it) } } @Procedure("graphql.updateForNodes",mode = Mode.WRITE) fun updateForNodes(@Name("query") query: String, @Name("variables",defaultValue = "{}") variables : Map<String,Any>) : Stream<Nodes> { val result = db!!.execute(query, variables) val firstColumn = result.columns()[0] return result.columnAs<Node>(firstColumn).stream().map{ Nodes(it) } } @UserFunction("graphql.sortColl") fun sortColl(@Name("coll") coll : java.util.List<Map<String,Any>>, @Name("orderFields", defaultValue = "[]") orderFields : java.util.List<String>, @Name("limit", defaultValue = "-1") limit : Long, @Name("skip", defaultValue = "0") skip : Long): List<Map<String,Any>> { val fields = orderFields.map { it: String -> val asc = it[0] == '^'; Pair(if (asc) it.substring(1) else it, asc) } val result = ArrayList(coll) as List<Map<String,Comparable<Any>>> val compare = { o1: Map<String, Comparable<Any>>, o2: Map<String, Comparable<Any>> -> // short-cut the folding fields.fold(0) { a: Int, s: Pair<String, Boolean> -> if (a == 0) { val name = s.first val v1 = o1.get(name) val v2 = o2.get(name) if (v1 == v2) 0 else { val cmp = if (v1 == null) -1 else if (v2 == null) 1 else v1.compareTo(v2) if (s.second) cmp else -cmp } } else a } } Collections.sort(result, compare) return (if (skip > 0 && limit != -1L) result.subList (skip.toInt(), skip.toInt() + limit.toInt()) else if (skip > 0) result.subList (skip.toInt(), result.size) else if (limit != -1L) result.subList (0, limit.toInt()) else result) } @Procedure("graphql.introspect") fun introspect(@Name("url") url:String, @Name("headers",defaultValue = "{}") headers:Map<String,String>) : Stream<GraphResult> { val metaDatas = Introspection().load(url, headers) // todo store as idl ? val nodes = metaDatas.associate { val props = it.properties.values.associate { " "+it.fieldName to it.type.toString() } + ("name" to it.type) it.type to VirtualNode(listOf(it.type) + it.labels, props) } val rels = metaDatas.flatMap { n -> val node = nodes[n.type]!! n.relationships.values.map { rel -> nodes[rel.label]?.let { labelNode -> val (start, end) = if (rel.out) node to labelNode else labelNode to node VirtualRelationship(start, rel.fieldName, mapOf("type" to rel.type, "multi" to rel.multi), end) } }.filterNotNull() } return Stream.of(GraphResult(nodes.values.toList(),rels)) } }
apache-2.0
2a845da5ea095bf38234eb4eca17d0b6
40.602871
214
0.607016
4.01246
false
false
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.kt
1
83591
// 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.openapi.wm.impl import com.intellij.BundleBase import com.intellij.DynamicBundle import com.intellij.diagnostic.LoadingState import com.intellij.diagnostic.runActivity import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.ide.IdeEventQueue import com.intellij.ide.UiActivity import com.intellij.ide.UiActivityMonitor import com.intellij.ide.actions.ActivateToolWindowAction import com.intellij.ide.actions.MaximizeActiveDialogAction import com.intellij.ide.plugins.PluginManagerCore import com.intellij.internal.statistic.collectors.fus.actions.persistence.ToolWindowCollector import com.intellij.notification.impl.NotificationsManagerImpl import com.intellij.openapi.Disposable import com.intellij.openapi.MnemonicHelper import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.actionSystem.ex.AnActionListener import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.application.Application import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.extensions.impl.ExtensionPointImpl import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.fileEditor.impl.EditorsSplitters import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.KeymapManagerListener import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.* import com.intellij.openapi.project.ex.ProjectEx import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.ui.FrameWrapper import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.Splitter import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.* import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.* import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.openapi.wm.ex.ToolWindowManagerEx import com.intellij.openapi.wm.ex.ToolWindowManagerListener import com.intellij.openapi.wm.ex.WindowManagerEx import com.intellij.ui.BalloonImpl import com.intellij.ui.ComponentUtil import com.intellij.ui.GuiUtils import com.intellij.ui.awt.RelativePoint import com.intellij.util.BitUtil import com.intellij.util.EventDispatcher import com.intellij.util.SingleAlarm import com.intellij.util.SystemProperties import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.addIfNotNull import com.intellij.util.ui.* import org.intellij.lang.annotations.JdkConstants import org.jdom.Element import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import java.awt.* import java.awt.event.* import java.beans.PropertyChangeListener import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference import java.util.function.Predicate import java.util.function.Supplier import javax.swing.* import javax.swing.event.HyperlinkEvent import javax.swing.event.HyperlinkListener private val LOG = logger<ToolWindowManagerImpl>() @State( name = "ToolWindowManager", defaultStateAsResource = true, storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)] ) open class ToolWindowManagerImpl(val project: Project) : ToolWindowManagerEx(), PersistentStateComponent<Element?> { private val dispatcher = EventDispatcher.create(ToolWindowManagerListener::class.java) private var layout = DesktopLayout() private val idToEntry: MutableMap<String, ToolWindowEntry> = HashMap() private val activeStack = ActiveStack() private val sideStack = SideStack() private var toolWindowPane: ToolWindowsPane? = null private var frame: ProjectFrameHelper? = null private var layoutToRestoreLater: DesktopLayout? = null private var currentState = KeyState.WAITING private var waiterForSecondPress: SingleAlarm? = null private val recentToolWindows: MutableList<String> = LinkedList<String>() private val pendingSetLayoutTask = AtomicReference<Runnable?>() fun isToolWindowRegistered(id: String) = idToEntry.containsKey(id) init { if (project.isDefault) { waiterForSecondPress = null } else { runActivity("toolwindow factory class preloading") { processDescriptors { bean, pluginDescriptor -> bean.getToolWindowFactory(pluginDescriptor) } } } } companion object { /** * Setting this [client property][JComponent.putClientProperty] allows to specify 'effective' parent for a component which will be used * to find a tool window to which component belongs (if any). This can prevent tool windows in non-default view modes (e.g. 'Undock') * to close when focus is transferred to a component not in tool window hierarchy, but logically belonging to it (e.g. when component * is added to the window's layered pane). * * @see ComponentUtil.putClientProperty */ @JvmField val PARENT_COMPONENT: Key<JComponent> = Key.create("tool.window.parent.component") @JvmStatic @ApiStatus.Internal fun getRegisteredMutableInfoOrLogError(decorator: InternalDecoratorImpl): WindowInfoImpl { val toolWindow = decorator.toolWindow return toolWindow.toolWindowManager.getRegisteredMutableInfoOrLogError(toolWindow.id) } } internal fun getFrame() = frame private fun runPendingLayoutTask() { pendingSetLayoutTask.getAndSet(null)?.run() } @Service private class ToolWindowManagerAppLevelHelper { companion object { private fun handleFocusEvent(event: FocusEvent) { if (event.id == FocusEvent.FOCUS_LOST) { if (event.oppositeComponent == null || event.isTemporary) { return } val project = IdeFocusManager.getGlobalInstance().lastFocusedFrame?.project ?: return if (project.isDisposed || project.isDefault) { return } val toolWindowManager = getInstance(project) as ToolWindowManagerImpl val toolWindowId = toolWindowManager.activeToolWindowId ?: return val activeEntry = toolWindowManager.idToEntry[toolWindowId] ?: return val windowInfo = activeEntry.readOnlyWindowInfo // just removed if (!windowInfo.isVisible) { return } if (!(windowInfo.isAutoHide || windowInfo.type == ToolWindowType.SLIDING)) { return } // let's check that it is a toolwindow who loses the focus if (isInActiveToolWindow(event.source, activeEntry.toolWindow) && !isInActiveToolWindow(event.oppositeComponent, activeEntry.toolWindow)) { // a toolwindow lost focus val focusGoesToPopup = JBPopupFactory.getInstance().getParentBalloonFor(event.oppositeComponent) != null if (!focusGoesToPopup) { val info = toolWindowManager.getRegisteredMutableInfoOrLogError(toolWindowId) toolWindowManager.doDeactivateToolWindow(info, activeEntry) } } } else if (event.id == FocusEvent.FOCUS_GAINED) { val component = event.component ?: return processOpenedProjects { project -> for (composite in FileEditorManagerEx.getInstanceEx(project).splitters.editorComposites) { if (composite.editors.any { SwingUtilities.isDescendingFrom(component, it.component) }) { (getInstance(project) as ToolWindowManagerImpl).activeStack.clear() } } } } } private inline fun process(processor: (manager: ToolWindowManagerImpl) -> Unit) { processOpenedProjects { project -> processor(getInstance(project) as ToolWindowManagerImpl) } } class MyListener : AWTEventListener { override fun eventDispatched(event: AWTEvent?) { if (event is FocusEvent) { handleFocusEvent(event) } else if (event is WindowEvent && event.getID() == WindowEvent.WINDOW_LOST_FOCUS) { process { manager -> val frame = event.getSource() as? JFrame if (frame === manager.frame?.frame) { manager.resetHoldState() } } } } } } init { val awtFocusListener = MyListener() Toolkit.getDefaultToolkit().addAWTEventListener(awtFocusListener, AWTEvent.FOCUS_EVENT_MASK or AWTEvent.WINDOW_FOCUS_EVENT_MASK) val updateHeadersAlarm = SingleAlarm(Runnable { processOpenedProjects { project -> (getInstance(project) as ToolWindowManagerImpl).updateToolWindowHeaders() } }, 50, ApplicationManager.getApplication()) val focusListener = PropertyChangeListener { updateHeadersAlarm.cancelAndRequest() } KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", focusListener) Disposer.register(ApplicationManager.getApplication()) { KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("focusOwner", focusListener) } val connection = ApplicationManager.getApplication().messageBus.connect() connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosingBeforeSave(project: Project) { val manager = (project.serviceIfCreated<ToolWindowManager>() as ToolWindowManagerImpl?) ?: return for (entry in manager.idToEntry.values) { manager.saveFloatingOrWindowedState(entry, manager.layout.getInfo(entry.id) ?: continue) } } override fun projectClosed(project: Project) { (project.serviceIfCreated<ToolWindowManager>() as ToolWindowManagerImpl?)?.projectClosed() } }) connection.subscribe(KeymapManagerListener.TOPIC, object : KeymapManagerListener { override fun activeKeymapChanged(keymap: Keymap?) { process { manager -> manager.idToEntry.values.forEach { it.stripeButton.updatePresentation() } } } }) connection.subscribe(AnActionListener.TOPIC, object : AnActionListener { override fun beforeActionPerformed(action: AnAction, dataContext: DataContext, event: AnActionEvent) { process { manager -> if (manager.currentState != KeyState.HOLD) { manager.resetHoldState() } } } }) IdeEventQueue.getInstance().addDispatcher(IdeEventQueue.EventDispatcher { event -> if (event is KeyEvent) { process { manager -> manager.dispatchKeyEvent(event) } } false }, ApplicationManager.getApplication()) } } private fun updateToolWindowHeaders() { focusManager.doWhenFocusSettlesDown(ExpirableRunnable.forProject(project) { for (entry in idToEntry.values) { if (entry.readOnlyWindowInfo.isVisible) { entry.toolWindow.decoratorComponent?.repaint() } } }) } private fun dispatchKeyEvent(e: KeyEvent): Boolean { if ((e.keyCode != KeyEvent.VK_CONTROL) && ( e.keyCode != KeyEvent.VK_ALT) && (e.keyCode != KeyEvent.VK_SHIFT) && (e.keyCode != KeyEvent.VK_META)) { if (e.modifiers == 0) { resetHoldState() } return false } if (e.id != KeyEvent.KEY_PRESSED && e.id != KeyEvent.KEY_RELEASED) { return false } val parent = UIUtil.findUltimateParent(e.component) if (parent is IdeFrame) { if ((parent as IdeFrame).project !== project) { resetHoldState() return false } } val vks = activateToolWindowVKsMask if (vks == 0) { resetHoldState() return false } val mouseMask = InputEvent.BUTTON1_DOWN_MASK or InputEvent.BUTTON2_DOWN_MASK or InputEvent.BUTTON3_DOWN_MASK if (BitUtil.isSet(vks, keyCodeToInputMask(e.keyCode)) && (e.modifiersEx and mouseMask) == 0) { val pressed = e.id == KeyEvent.KEY_PRESSED val modifiers = e.modifiers if (areAllModifiersPressed(modifiers, vks) || !pressed) { processState(pressed) } else { resetHoldState() } } return false } private fun resetHoldState() { currentState = KeyState.WAITING processHoldState() } private fun processState(pressed: Boolean) { if (pressed) { if (currentState == KeyState.WAITING) { currentState = KeyState.PRESSED } else if (currentState == KeyState.RELEASED) { currentState = KeyState.HOLD processHoldState() } } else { if (currentState == KeyState.PRESSED) { currentState = KeyState.RELEASED waiterForSecondPress?.cancelAndRequest() } else { resetHoldState() } } } private fun processHoldState() { toolWindowPane?.setStripesOverlayed(currentState == KeyState.HOLD) } @ApiStatus.Internal override fun init(frameHelper: ProjectFrameHelper): ToolWindowsPane { toolWindowPane?.let { return it } // manager is used in light tests (light project is never disposed), so, earlyDisposable must be used val disposable = (project as ProjectEx).earlyDisposable waiterForSecondPress = SingleAlarm(task = Runnable { if (currentState != KeyState.HOLD) { resetHoldState() } }, delay = SystemProperties.getIntProperty("actionSystem.keyGestureDblClickTime", 650), parentDisposable = disposable) val connection = project.messageBus.connect(disposable) connection.subscribe(ToolWindowManagerListener.TOPIC, dispatcher.multicaster) connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener { override fun fileClosed(source: FileEditorManager, file: VirtualFile) { focusManager.doWhenFocusSettlesDown(ExpirableRunnable.forProject(project) { if (!FileEditorManager.getInstance(project).hasOpenFiles()) { focusToolWindowByDefault() } }) } }) frame = frameHelper val rootPane = frameHelper.rootPane!! val toolWindowPane = rootPane.toolWindowPane toolWindowPane.initDocumentComponent(project) this.toolWindowPane = toolWindowPane return toolWindowPane } // must be executed in EDT private fun beforeProjectOpenedTask( tasks: List<RegisterToolWindowTask>, app: Application, ) = Runnable { frame!!.rootPane!!.updateToolbar() runPendingLayoutTask() // FacetDependentToolWindowManager - strictly speaking, computeExtraToolWindowBeans should be executed not in EDT, but for now it is not safe because: // 1. read action is required to read facet list (might cause a deadlock) // 2. delay between collection and adding ProjectWideFacetListener (should we introduce a new method in RegisterToolWindowTaskProvider to add listeners?) val list = ArrayList(tasks) + (app.extensionArea as ExtensionsAreaImpl) .getExtensionPoint<RegisterToolWindowTaskProvider>("com.intellij.registerToolWindowTaskProvider") .computeExtraToolWindowBeans() if (toolWindowPane == null) { if (!app.isUnitTestMode) { LOG.error("ProjectFrameAllocator is not used - use ProjectManager.openProject to open project in a correct way") } val toolWindowsPane = init((WindowManager.getInstance() as WindowManagerImpl).allocateFrame(project)) // cannot be executed because added layered pane is not yet validated and size is not known app.invokeLater(Runnable { runPendingLayoutTask() initToolWindows(list, toolWindowsPane) }, project.disposed) } else { initToolWindows(list, toolWindowPane!!) } registerEPListeners() } private fun computeToolWindowBeans(): List<RegisterToolWindowTask> { val list = mutableListOf<RegisterToolWindowTask>() processDescriptors { bean, pluginDescriptor -> val condition = bean.getCondition(pluginDescriptor) if (condition == null || condition.value(project)) { list.addIfNotNull(beanToTask(bean, pluginDescriptor)) } } return list } private fun ExtensionPointImpl<RegisterToolWindowTaskProvider>.computeExtraToolWindowBeans(): List<RegisterToolWindowTask> { val list = mutableListOf<RegisterToolWindowTask>() this.processImplementations(true) { supplier, epPluginDescriptor -> if (epPluginDescriptor.pluginId == PluginManagerCore.CORE_ID) { for (bean in (supplier.get() ?: return@processImplementations).getTasks(project)) { list.addIfNotNull(beanToTask(bean)) } } else { LOG.error("Only bundled plugin can define registerToolWindowTaskProvider: $epPluginDescriptor") } } return list } private fun beanToTask( bean: ToolWindowEP, pluginDescriptor: PluginDescriptor = bean.pluginDescriptor, ): RegisterToolWindowTask? { val factory = bean.getToolWindowFactory(pluginDescriptor) return if (factory != null && factory.isApplicable(project)) beanToTask(bean, pluginDescriptor, factory) else null } private fun beanToTask( bean: ToolWindowEP, pluginDescriptor: PluginDescriptor, factory: ToolWindowFactory, ) = RegisterToolWindowTask( id = bean.id, icon = findIconFromBean(bean, factory, pluginDescriptor), anchor = getToolWindowAnchor(factory, bean), sideTool = bean.secondary || (@Suppress("DEPRECATION") bean.side), canCloseContent = bean.canCloseContents, canWorkInDumbMode = DumbService.isDumbAware(factory), shouldBeAvailable = factory.shouldBeAvailable(project), contentFactory = factory, stripeTitle = getStripeTitleSupplier(bean.id, pluginDescriptor), ) // This method cannot be inlined because of magic Kotlin compilation bug: it 'captured' "list" local value and cause class-loader leak // See IDEA-CR-61904 private fun registerEPListeners() { ToolWindowEP.EP_NAME.addExtensionPointListener(object : ExtensionPointListener<ToolWindowEP> { override fun extensionAdded(extension: ToolWindowEP, pluginDescriptor: PluginDescriptor) { initToolWindow(extension, pluginDescriptor) } override fun extensionRemoved(extension: ToolWindowEP, pluginDescriptor: PluginDescriptor) { doUnregisterToolWindow(extension.id) } }, project) } private fun getToolWindowAnchor(factory: ToolWindowFactory?, bean: ToolWindowEP) = (factory as? ToolWindowFactoryEx)?.anchor ?: ToolWindowAnchor.fromText(bean.anchor ?: ToolWindowAnchor.LEFT.toString()) private fun initToolWindows(list: List<RegisterToolWindowTask>, toolWindowsPane: ToolWindowsPane) { runActivity("toolwindow creating") { val entries = ArrayList<String>(list.size) for (task in list) { try { entries.add(doRegisterToolWindow(task, toolWindowsPane).id) } catch (e: ProcessCanceledException) { throw e } catch (t: Throwable) { LOG.error("Cannot init toolwindow ${task.contentFactory}", t) } } project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowsRegistered(entries, this) toolWindowPane!!.revalidateNotEmptyStripes() } toolWindowsPane.putClientProperty(UIUtil.NOT_IN_HIERARCHY_COMPONENTS, Iterable { idToEntry.values.asSequence().mapNotNull { val component = it.toolWindow.decoratorComponent if (component != null && component.parent == null) component else null }.iterator() }) service<ToolWindowManagerAppLevelHelper>() } override fun initToolWindow(bean: ToolWindowEP) { initToolWindow(bean, bean.pluginDescriptor) } private fun initToolWindow(bean: ToolWindowEP, pluginDescriptor: PluginDescriptor) { val condition = bean.getCondition(pluginDescriptor) if (condition != null && !condition.value(project)) { return } val factory = bean.getToolWindowFactory(bean.pluginDescriptor) ?: return if (!factory.isApplicable(project)) { return } val toolWindowPane = toolWindowPane ?: init((WindowManager.getInstance() as WindowManagerImpl).allocateFrame(project)) val anchor = getToolWindowAnchor(factory, bean) @Suppress("DEPRECATION") val sideTool = bean.secondary || bean.side val entry = doRegisterToolWindow(RegisterToolWindowTask( id = bean.id, icon = findIconFromBean(bean, factory, pluginDescriptor), anchor = anchor, sideTool = sideTool, canCloseContent = bean.canCloseContents, canWorkInDumbMode = DumbService.isDumbAware(factory), shouldBeAvailable = factory.shouldBeAvailable(project), contentFactory = factory, stripeTitle = getStripeTitleSupplier(bean.id, pluginDescriptor) ), toolWindowPane) project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowsRegistered(listOf(entry.id), this) toolWindowPane.getStripeFor(anchor).revalidate() toolWindowPane.validate() toolWindowPane.repaint() } fun projectClosed() { if (frame == null) { return } frame!!.releaseFrame() toolWindowPane!!.putClientProperty(UIUtil.NOT_IN_HIERARCHY_COMPONENTS, null) // hide all tool windows - frame maybe reused for another project for (entry in idToEntry.values) { try { removeDecoratorWithoutUpdatingState(entry, layout.getInfo(entry.id) ?: continue, dirtyMode = true) } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { LOG.error(e) } finally { Disposer.dispose(entry.disposable) } } toolWindowPane!!.reset() frame = null } override fun addToolWindowManagerListener(listener: ToolWindowManagerListener) { dispatcher.addListener(listener) } override fun addToolWindowManagerListener(listener: ToolWindowManagerListener, parentDisposable: Disposable) { project.messageBus.connect(parentDisposable).subscribe(ToolWindowManagerListener.TOPIC, listener) } override fun removeToolWindowManagerListener(listener: ToolWindowManagerListener) { dispatcher.removeListener(listener) } override fun activateEditorComponent() { if (!EditorsSplitters.focusDefaultComponentInSplittersIfPresent(project)) { // see note about requestFocus in focusDefaultComponentInSplittersIfPresent frame?.rootPane?.requestFocus() } } open fun activateToolWindow(id: String, runnable: Runnable?, autoFocusContents: Boolean, source: ToolWindowEventSource? = null) { ApplicationManager.getApplication().assertIsDispatchThread() val activity = UiActivity.Focus("toolWindow:$id") UiActivityMonitor.getInstance().addActivity(project, activity, ModalityState.NON_MODAL) activateToolWindow(idToEntry[id]!!, getRegisteredMutableInfoOrLogError(id), autoFocusContents, source) ApplicationManager.getApplication().invokeLater(Runnable { runnable?.run() UiActivityMonitor.getInstance().removeActivity(project, activity) }, project.disposed) } private fun activateToolWindow(entry: ToolWindowEntry, info: WindowInfoImpl, autoFocusContents: Boolean = true, source: ToolWindowEventSource? = null) { LOG.debug { "activateToolWindow($entry)" } if (source != null) { ToolWindowCollector.getInstance().recordActivation(project, entry.id, info, source) } recentToolWindows.remove(entry.id) recentToolWindows.add(0, entry.id) if (!entry.toolWindow.isAvailable) { // Tool window can be "logically" active but not focused. For example, // when the user switched to another application. So we just need to bring // tool window's window to front. if (autoFocusContents && !entry.toolWindow.hasFocus) { entry.toolWindow.requestFocusInToolWindow() } return } if (!entry.readOnlyWindowInfo.isVisible) { showToolWindowImpl(entry, info, dirtyMode = false, source = source) } if (autoFocusContents && ApplicationManager.getApplication().isActive) { entry.toolWindow.requestFocusInToolWindow() } else { activeStack.push(entry) } fireStateChanged() } fun getRecentToolWindows() = ArrayList(recentToolWindows) internal fun updateToolWindow(toolWindow: ToolWindowImpl, component: Component) { toolWindow.setFocusedComponent(component) if (toolWindow.isAvailable && !toolWindow.isActive) { activateToolWindow(toolWindow.id, null, autoFocusContents = true) } activeStack.push(idToEntry[toolWindow.id] ?: return) } // mutate operation must use info from layout and not from decorator private fun getRegisteredMutableInfoOrLogError(id: String): WindowInfoImpl { val info = layout.getInfo(id) ?: throw IllegalThreadStateException("window with id=\"$id\" is unknown") if (!isToolWindowRegistered(id)) { LOG.error("window with id=\"$id\" isn't registered") } return info } private fun doDeactivateToolWindow(info: WindowInfoImpl, entry: ToolWindowEntry, dirtyMode: Boolean = false, source: ToolWindowEventSource? = null) { LOG.debug { "enter: deactivateToolWindowImpl(${info.id})" } setHiddenState(info, entry, source) updateStateAndRemoveDecorator(info, entry, dirtyMode = dirtyMode) entry.applyWindowInfo(info.copy()) } private fun setHiddenState(info: WindowInfoImpl, entry: ToolWindowEntry, source: ToolWindowEventSource?) { ToolWindowCollector.getInstance().recordHidden(project, info, source) info.isActiveOnStart = false info.isVisible = false activeStack.remove(entry, false) } override val toolWindowIds: Array<String> get() = idToEntry.keys.toTypedArray() override val toolWindowIdSet: Set<String> get() = HashSet(idToEntry.keys) override val activeToolWindowId: String? get() { EDT.assertIsEdt() val frame = frame?.frame ?: return null if (frame.isActive) { val focusOwner = focusManager.getLastFocusedFor(frame) ?: return null var parent: Component? = focusOwner while (parent != null) { if (parent is InternalDecoratorImpl) { return parent.toolWindow.id } parent = parent.parent } } else { // let's check floating and windowed for (entry in idToEntry.values) { if (entry.floatingDecorator?.isActive == true || entry.windowedDecorator?.isActive == true) { return entry.id } } } return null } override val lastActiveToolWindowId: String? get() = getLastActiveToolWindow(condition = null)?.id override fun getLastActiveToolWindow(condition: Predicate<in JComponent>?): ToolWindow? { EDT.assertIsEdt() for (i in 0 until activeStack.persistentSize) { val toolWindow = activeStack.peekPersistent(i).toolWindow if (toolWindow.isAvailable && (condition == null || condition.test(toolWindow.component))) { return toolWindow } } return null } /** * @return floating decorator for the tool window with specified `ID`. */ private fun getFloatingDecorator(id: String) = idToEntry[id]?.floatingDecorator /** * @return windowed decorator for the tool window with specified `ID`. */ private fun getWindowedDecorator(id: String) = idToEntry[id]?.windowedDecorator /** * @return tool button for the window with specified `ID`. */ @TestOnly fun getStripeButton(id: String) = idToEntry[id]!!.stripeButton override fun getIdsOn(anchor: ToolWindowAnchor) = getVisibleToolWindowsOn(anchor).map { it.id }.toList() @ApiStatus.Internal fun getToolWindowsOn(anchor: ToolWindowAnchor, excludedId: String): List<ToolWindowEx> { return getVisibleToolWindowsOn(anchor) .filter { it.id != excludedId } .map { it.toolWindow } .toList() } @ApiStatus.Internal fun getDockedInfoAt(anchor: ToolWindowAnchor?, side: Boolean): WindowInfo? { for (entry in idToEntry.values) { val info = entry.readOnlyWindowInfo if (info.isVisible && info.isDocked && info.anchor == anchor && side == info.isSplit) { return info } } return null } override fun getLocationIcon(id: String, fallbackIcon: Icon): Icon { val info = layout.getInfo(id) ?: return fallbackIcon val type = info.type if (type == ToolWindowType.FLOATING || type == ToolWindowType.WINDOWED) { return AllIcons.Actions.MoveToWindow } val anchor = info.anchor val splitMode = info.isSplit return when (anchor) { ToolWindowAnchor.BOTTOM -> { if (splitMode) AllIcons.Actions.MoveToBottomRight else AllIcons.Actions.MoveToBottomLeft } ToolWindowAnchor.LEFT -> { if (splitMode) AllIcons.Actions.MoveToLeftBottom else AllIcons.Actions.MoveToLeftTop } ToolWindowAnchor.RIGHT -> { if (splitMode) AllIcons.Actions.MoveToRightBottom else AllIcons.Actions.MoveToRightTop } ToolWindowAnchor.TOP -> { if (splitMode) AllIcons.Actions.MoveToTopRight else AllIcons.Actions.MoveToTopLeft } else -> fallbackIcon } } private fun getVisibleToolWindowsOn(anchor: ToolWindowAnchor): Sequence<ToolWindowEntry> { return idToEntry.values .asSequence() .filter { it.readOnlyWindowInfo.anchor == anchor && it.toolWindow.isAvailable } } // cannot be ToolWindowEx because of backward compatibility override fun getToolWindow(id: String?): ToolWindow? { return idToEntry[id ?: return null]?.toolWindow } open fun showToolWindow(id: String) { LOG.debug { "enter: showToolWindow($id)" } EDT.assertIsEdt() val info = layout.getInfo(id) ?: throw IllegalThreadStateException("window with id=\"$id\" is unknown") val entry = idToEntry[id]!! if (entry.readOnlyWindowInfo.isVisible) { LOG.assertTrue(entry.toolWindow.getComponentIfInitialized() != null) return } if (showToolWindowImpl(entry, info, dirtyMode = false)) { checkInvariants("id: $id") fireStateChanged() } } internal fun removeFromSideBar(id: String, source: ToolWindowEventSource?) { val info = getRegisteredMutableInfoOrLogError(id) if (!info.isShowStripeButton) { return } val entry = idToEntry[info.id!!]!! info.isShowStripeButton = false setHiddenState(info, entry, source) updateStateAndRemoveDecorator(info, entry, dirtyMode = false) entry.applyWindowInfo(info.copy()) if (Registry.`is`("ide.new.stripes.ui")) { toolWindowPane?.onStripeButtonRemoved(project, entry.toolWindow) } fireStateChanged() } override fun hideToolWindow(id: String, hideSide: Boolean) { hideToolWindow(id, hideSide, moveFocus = true) } open fun hideToolWindow(id: String, hideSide: Boolean, moveFocus: Boolean, source: ToolWindowEventSource? = null) { EDT.assertIsEdt() val entry = idToEntry[id]!! if (!entry.readOnlyWindowInfo.isVisible) { return } val info = getRegisteredMutableInfoOrLogError(id) val moveFocusAfter = moveFocus && entry.toolWindow.isActive doHide(entry, info, dirtyMode = false, hideSide = hideSide, source = source) fireStateChanged() if (moveFocusAfter) { activateEditorComponent() } } private fun doHide(entry: ToolWindowEntry, info: WindowInfoImpl, dirtyMode: Boolean, hideSide: Boolean = false, source: ToolWindowEventSource? = null) { // hide and deactivate doDeactivateToolWindow(info, entry, dirtyMode = dirtyMode, source = source) if (hideSide && info.type != ToolWindowType.FLOATING && info.type != ToolWindowType.WINDOWED) { for (each in getVisibleToolWindowsOn(info.anchor)) { activeStack.remove(each, false) } if (isStackEnabled) { while (!sideStack.isEmpty(info.anchor)) { sideStack.pop(info.anchor) } } for (otherEntry in idToEntry.values) { val otherInfo = layout.getInfo(otherEntry.id) ?: continue if (otherInfo.isVisible && otherInfo.anchor == info.anchor) { doDeactivateToolWindow(otherInfo, otherEntry, dirtyMode = dirtyMode, source = ToolWindowEventSource.HideSide) } } } else { // first of all we have to find tool window that was located at the same side and was hidden if (isStackEnabled) { var info2: WindowInfoImpl? = null while (!sideStack.isEmpty(info.anchor)) { val storedInfo = sideStack.pop(info.anchor) if (storedInfo.isSplit != info.isSplit) { continue } val currentInfo = getRegisteredMutableInfoOrLogError(storedInfo.id!!) // SideStack contains copies of real WindowInfos. It means that // these stored infos can be invalid. The following loop removes invalid WindowInfos. if (storedInfo.anchor == currentInfo.anchor && storedInfo.type == currentInfo.type && storedInfo.isAutoHide == currentInfo.isAutoHide) { info2 = storedInfo break } } if (info2 != null) { val entry2 = idToEntry[info2.id!!]!! if (!entry2.readOnlyWindowInfo.isVisible) { showToolWindowImpl(entry2, info2, dirtyMode = dirtyMode) } } } activeStack.remove(entry, false) } } /** * @param dirtyMode if `true` then all UI operations are performed in dirty mode. */ private fun showToolWindowImpl(entry: ToolWindowEntry, toBeShownInfo: WindowInfoImpl, dirtyMode: Boolean, source: ToolWindowEventSource? = null): Boolean { if (!entry.toolWindow.isAvailable) { return false } ToolWindowCollector.getInstance().recordShown(project, source, toBeShownInfo) toBeShownInfo.isVisible = true toBeShownInfo.isShowStripeButton = true val snapshotInfo = toBeShownInfo.copy() entry.applyWindowInfo(snapshotInfo) doShowWindow(entry, snapshotInfo, dirtyMode) if (entry.readOnlyWindowInfo.type == ToolWindowType.WINDOWED && entry.toolWindow.getComponentIfInitialized() != null) { UIUtil.toFront(ComponentUtil.getWindow(entry.toolWindow.component)) } return true } private fun doShowWindow(entry: ToolWindowEntry, info: WindowInfo, dirtyMode: Boolean) { if (entry.readOnlyWindowInfo.type == ToolWindowType.FLOATING) { addFloatingDecorator(entry, info) } else if (entry.readOnlyWindowInfo.type == ToolWindowType.WINDOWED) { addWindowedDecorator(entry, info) } else { // docked and sliding windows // If there is tool window on the same side then we have to hide it, i.e. // clear place for tool window to be shown. // // We store WindowInfo of hidden tool window in the SideStack (if the tool window // is docked and not auto-hide one). Therefore it's possible to restore the // hidden tool window when showing tool window will be closed. for (otherEntry in idToEntry.values) { if (entry.id == otherEntry.id) { continue } val otherInfo = otherEntry.readOnlyWindowInfo if (otherInfo.isVisible && otherInfo.type == info.type && otherInfo.anchor == info.anchor && otherInfo.isSplit == info.isSplit) { val otherLayoutInto = layout.getInfo(otherEntry.id)!! // hide and deactivate tool window setHiddenState(otherLayoutInto, otherEntry, ToolWindowEventSource.HideOnShowOther) val otherInfoCopy = otherLayoutInto.copy() otherEntry.applyWindowInfo(otherInfoCopy) otherEntry.toolWindow.decoratorComponent?.let { decorator -> toolWindowPane!!.removeDecorator(otherInfoCopy, decorator, false, this) } // store WindowInfo into the SideStack if (isStackEnabled && otherInfo.isDocked && !otherInfo.isAutoHide) { sideStack.push(otherInfoCopy) } } } toolWindowPane!!.addDecorator(entry.toolWindow.getOrCreateDecoratorComponent(), info, dirtyMode, this) // remove tool window from the SideStack if (isStackEnabled) { sideStack.remove(entry.id) } } entry.toolWindow.scheduleContentInitializationIfNeeded() fireToolWindowShown(entry.toolWindow) } override fun registerToolWindow(task: RegisterToolWindowTask): ToolWindow { val toolWindowPane = toolWindowPane ?: init((WindowManager.getInstance() as WindowManagerImpl).allocateFrame(project)) val entry = doRegisterToolWindow(task, toolWindowPane = toolWindowPane) project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowsRegistered(listOf(entry.id), this) toolWindowPane.getStripeFor(entry.toolWindow.anchor).revalidate() toolWindowPane.validate() toolWindowPane.repaint() fireStateChanged() return entry.toolWindow } private fun doRegisterToolWindow(task: RegisterToolWindowTask, toolWindowPane: ToolWindowsPane): ToolWindowEntry { LOG.debug { "enter: installToolWindow($task)" } ApplicationManager.getApplication().assertIsDispatchThread() if (idToEntry.containsKey(task.id)) { throw IllegalArgumentException("window with id=\"${task.id}\" is already registered") } val info = layout.getOrCreate(task) val disposable = Disposer.newDisposable(task.id) Disposer.register(project, disposable) val contentFactory = task.contentFactory val windowInfoSnapshot = info.copy() if (windowInfoSnapshot.isVisible && (contentFactory == null || !task.shouldBeAvailable)) { // isVisible cannot be true if contentFactory is null, because we cannot show toolwindow without content windowInfoSnapshot.isVisible = false } @Suppress("HardCodedStringLiteral") val stripeTitle = task.stripeTitle?.get() ?: task.id val toolWindow = ToolWindowImpl(this, task.id, task.canCloseContent, task.canWorkInDumbMode, task.component, disposable, windowInfoSnapshot, contentFactory, isAvailable = task.shouldBeAvailable, stripeTitle = stripeTitle) toolWindow.windowInfoDuringInit = windowInfoSnapshot try { contentFactory?.init(toolWindow) } finally { toolWindow.windowInfoDuringInit = null } // contentFactory.init can set icon if (toolWindow.icon == null) { task.icon?.let { toolWindow.doSetIcon(it) } } ActivateToolWindowAction.ensureToolWindowActionRegistered(toolWindow) val button = StripeButton(toolWindowPane, toolWindow) val entry = ToolWindowEntry(button, toolWindow, disposable) idToEntry[task.id] = entry // only after added to idToEntry map button.isSelected = windowInfoSnapshot.isVisible button.updatePresentation() addStripeButton(button, toolWindowPane.getStripeFor((contentFactory as? ToolWindowFactoryEx)?.anchor ?: info.anchor)) if (Registry.`is`("ide.new.stripes.ui")) { toolWindow.largeStripeAnchor = if (toolWindow.largeStripeAnchor == ToolWindowAnchor.NONE) task.anchor else toolWindow.largeStripeAnchor } // If preloaded info is visible or active then we have to show/activate the installed // tool window. This step has sense only for windows which are not in the auto hide // mode. But if tool window was active but its mode doesn't allow to activate it again // (for example, tool window is in auto hide mode) then we just activate editor component. if (contentFactory != null /* not null on init tool window from EP */) { if (windowInfoSnapshot.isVisible) { showToolWindowImpl(entry, info, dirtyMode = false) // do not activate tool window that is the part of project frame - default component should be focused if (windowInfoSnapshot.isActiveOnStart && (windowInfoSnapshot.type == ToolWindowType.WINDOWED || windowInfoSnapshot.type == ToolWindowType.FLOATING) && ApplicationManager.getApplication().isActive) { entry.toolWindow.requestFocusInToolWindow() } } } return entry } @Suppress("OverridingDeprecatedMember") override fun unregisterToolWindow(id: String) { doUnregisterToolWindow(id) fireStateChanged() } internal fun doUnregisterToolWindow(id: String) { LOG.debug { "enter: unregisterToolWindow($id)" } ApplicationManager.getApplication().assertIsDispatchThread() ActivateToolWindowAction.unregister(id) val entry = idToEntry.remove(id) ?: return val toolWindow = entry.toolWindow val info = layout.getInfo(id) if (info != null) { // remove decorator and tool button from the screen - removing will also save current bounds updateStateAndRemoveDecorator(info, entry, false) // save recent appearance of tool window activeStack.remove(entry, true) if (isStackEnabled) { sideStack.remove(id) } removeStripeButton(entry.stripeButton) toolWindowPane!!.validate() toolWindowPane!!.repaint() } if (!project.isDisposed) { project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowUnregistered(id, (toolWindow)) } Disposer.dispose(entry.disposable) } private fun updateStateAndRemoveDecorator(info: WindowInfoImpl, entry: ToolWindowEntry, dirtyMode: Boolean) { saveFloatingOrWindowedState(entry, info) removeDecoratorWithoutUpdatingState(entry, info, dirtyMode) } private fun removeDecoratorWithoutUpdatingState(entry: ToolWindowEntry, info: WindowInfoImpl, dirtyMode: Boolean) { entry.windowedDecorator?.let { entry.windowedDecorator = null Disposer.dispose(it) return } entry.floatingDecorator?.let { entry.floatingDecorator = null it.dispose() return } entry.toolWindow.decoratorComponent?.let { toolWindowPane!!.removeDecorator(info, it, dirtyMode, this) return } } private fun saveFloatingOrWindowedState(entry: ToolWindowEntry, info: WindowInfoImpl) { entry.floatingDecorator?.let { info.floatingBounds = it.bounds info.isActiveOnStart = it.isActive return } entry.windowedDecorator?.let { windowedDecorator -> info.isActiveOnStart = windowedDecorator.isActive val frame = windowedDecorator.getFrame() if (frame.isShowing) { val maximized = (frame as JFrame).extendedState == Frame.MAXIMIZED_BOTH if (maximized) { frame.extendedState = Frame.NORMAL frame.invalidate() frame.revalidate() } val bounds = getRootBounds(frame) info.floatingBounds = bounds info.isMaximized = maximized } return } } override fun getLayout(): DesktopLayout { ApplicationManager.getApplication().assertIsDispatchThread() return layout } override fun setLayoutToRestoreLater(layout: DesktopLayout?) { layoutToRestoreLater = layout } override fun getLayoutToRestoreLater() = layoutToRestoreLater override fun setLayout(newLayout: DesktopLayout) { ApplicationManager.getApplication().assertIsDispatchThread() if (idToEntry.isEmpty()) { layout = newLayout return } data class LayoutData(val old: WindowInfoImpl, val new: WindowInfoImpl, val entry: ToolWindowEntry) val list = mutableListOf<LayoutData>() for (entry in idToEntry.values) { val old = layout.getInfo(entry.id) ?: entry.readOnlyWindowInfo as WindowInfoImpl val new = newLayout.getInfo(entry.id) // just copy if defined in the old layout but not in the new if (new == null) { newLayout.addInfo(entry.id, old.copy()) } else if (old != new) { list.add(LayoutData(old = old, new = new, entry = entry)) } } this.layout = newLayout if (list.isEmpty()) { return } for (item in list) { item.entry.applyWindowInfo(item.new) if (item.old.isVisible && !item.new.isVisible) { updateStateAndRemoveDecorator(item.new, item.entry, dirtyMode = true) } if (item.old.anchor != item.new.anchor || item.old.order != item.new.order) { setToolWindowAnchorImpl(item.entry, item.old, item.new, item.new.anchor, item.new.order) } var toShowWindow = false if (item.old.isSplit != item.new.isSplit) { val wasVisible = item.old.isVisible // we should hide the window and show it in a 'new place' to automatically hide possible window that is already located in a 'new place' if (wasVisible) { hideToolWindow(item.entry.id, hideSide = false, moveFocus = true) } if (wasVisible) { toShowWindow = true } } if (item.old.type != item.new.type) { val dirtyMode = item.old.type == ToolWindowType.DOCKED || item.old.type == ToolWindowType.SLIDING updateStateAndRemoveDecorator(item.old, item.entry, dirtyMode) if (item.new.isVisible) { toShowWindow = true } } else if (!item.old.isVisible && item.new.isVisible) { toShowWindow = true } if (toShowWindow) { doShowWindow(item.entry, item.new, dirtyMode = true) } } val toolWindowPane = toolWindowPane!! toolWindowPane.revalidateNotEmptyStripes() toolWindowPane.validate() toolWindowPane.repaint() activateEditorComponent() val frame = frame!! val rootPane = frame.rootPane ?: return rootPane.revalidate() rootPane.repaint() fireStateChanged() checkInvariants("") } override fun invokeLater(runnable: Runnable) { ApplicationManager.getApplication().invokeLater(runnable, project.disposed) } override val focusManager: IdeFocusManager get() = IdeFocusManager.getInstance(project)!! override fun canShowNotification(toolWindowId: String): Boolean { return toolWindowPane?.getStripeFor(idToEntry[toolWindowId]?.readOnlyWindowInfo?.anchor ?: return false)?.getButtonFor(toolWindowId) != null } override fun notifyByBalloon(toolWindowId: String, type: MessageType, @NlsContexts.NotificationContent htmlBody: String) { notifyByBalloon(toolWindowId, type, htmlBody, null, null) } override fun notifyByBalloon(options: ToolWindowBalloonShowOptions) { if (Registry.`is`("ide.new.stripes.ui")) { notifySquareButtonByBalloon(options) return } val entry = idToEntry[options.toolWindowId]!! val existing = entry.balloon if (existing != null) { Disposer.dispose(existing) } val stripe = toolWindowPane!!.getStripeFor(entry.readOnlyWindowInfo.anchor) if (!entry.toolWindow.isAvailable) { entry.toolWindow.isPlaceholderMode = true stripe.updatePresentation() stripe.revalidate() stripe.repaint() } val anchor = entry.readOnlyWindowInfo.anchor val position = Ref.create(Balloon.Position.below) when { ToolWindowAnchor.TOP == anchor -> position.set(Balloon.Position.below) ToolWindowAnchor.BOTTOM == anchor -> position.set(Balloon.Position.above) ToolWindowAnchor.LEFT == anchor -> position.set(Balloon.Position.atRight) ToolWindowAnchor.RIGHT == anchor -> position.set(Balloon.Position.atLeft) } val balloon = createBalloon(options, entry) val button = stripe.getButtonFor(options.toolWindowId) LOG.assertTrue(button != null, ("Button was not found, popup won't be shown. $options")) if (button == null) { return } val show = Runnable { val tracker: PositionTracker<Balloon> if (entry.toolWindow.isVisible && (entry.toolWindow.type == ToolWindowType.WINDOWED || entry.toolWindow.type == ToolWindowType.FLOATING)) { tracker = createPositionTracker(entry.toolWindow.component, ToolWindowAnchor.BOTTOM) } else if (!button.isShowing) { tracker = createPositionTracker(toolWindowPane!!, anchor) } else { tracker = object : PositionTracker<Balloon>(button) { override fun recalculateLocation(`object`: Balloon): RelativePoint? { val otherEntry = idToEntry[options.toolWindowId] ?: return null val stripeButton = otherEntry.stripeButton if (otherEntry.readOnlyWindowInfo.anchor != anchor) { `object`.hide() return null } return RelativePoint(stripeButton, Point(stripeButton.bounds.width / 2, stripeButton.height / 2 - 2)) } } } if (!balloon.isDisposed) { balloon.show(tracker, position.get()) } } if (button.isValid) { show.run() } else { SwingUtilities.invokeLater(show) } } fun notifySquareButtonByBalloon(options: ToolWindowBalloonShowOptions) { val entry = idToEntry[options.toolWindowId]!! val existing = entry.balloon if (existing != null) { Disposer.dispose(existing) } val anchor = entry.readOnlyWindowInfo.largeStripeAnchor val position = Ref.create(Balloon.Position.atLeft) when (anchor) { ToolWindowAnchor.TOP -> position.set(Balloon.Position.atRight) ToolWindowAnchor.RIGHT -> position.set(Balloon.Position.atRight) ToolWindowAnchor.BOTTOM -> position.set(Balloon.Position.atLeft) ToolWindowAnchor.LEFT -> position.set(Balloon.Position.atLeft) } val balloon = createBalloon(options, entry) var button = toolWindowPane!!.getSquareStripeFor(entry.readOnlyWindowInfo.largeStripeAnchor)?.getButtonFor(options.toolWindowId) as ActionButton? if (button == null || !button.isShowing) { button = (toolWindowPane!!.getSquareStripeFor(ToolWindowAnchor.LEFT) as? ToolwindowLeftToolbar)?.moreButton!! position.set(Balloon.Position.atLeft) } val show = Runnable { val tracker: PositionTracker<Balloon> if (entry.toolWindow.isVisible && (entry.toolWindow.type == ToolWindowType.WINDOWED || entry.toolWindow.type == ToolWindowType.FLOATING)) { tracker = createPositionTracker(entry.toolWindow.component, ToolWindowAnchor.BOTTOM) } else { tracker = object : PositionTracker<Balloon>(button) { override fun recalculateLocation(`object`: Balloon): RelativePoint? { val otherEntry = idToEntry[options.toolWindowId] ?: return null if (otherEntry.readOnlyWindowInfo.largeStripeAnchor != anchor) { `object`.hide() return null } return RelativePoint(button, Point(if (position.get() == Balloon.Position.atRight) 0 else button.bounds.width, button.height / 2)) } } } if (!balloon.isDisposed) { balloon.show(tracker, position.get()) } } if (button.isValid) { show.run() } else { SwingUtilities.invokeLater(show) } } private fun createPositionTracker(component: Component, anchor: ToolWindowAnchor): PositionTracker<Balloon> { return object : PositionTracker<Balloon>(component) { override fun recalculateLocation(`object`: Balloon): RelativePoint { val bounds = component.bounds val target = StartupUiUtil.getCenterPoint(bounds, Dimension(1, 1)) when { ToolWindowAnchor.TOP == anchor -> target.y = 0 ToolWindowAnchor.BOTTOM == anchor -> target.y = bounds.height - 3 ToolWindowAnchor.LEFT == anchor -> target.x = 0 ToolWindowAnchor.RIGHT == anchor -> target.x = bounds.width } return RelativePoint(component, target) } } } private fun createBalloon(options: ToolWindowBalloonShowOptions, entry: ToolWindowEntry): Balloon { val listenerWrapper = BalloonHyperlinkListener(options.listener) @Suppress("HardCodedStringLiteral") val content = options.htmlBody.replace("\n", "<br>") val balloonBuilder = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(content, options.icon, options.type.titleForeground, options.type.popupBackground, listenerWrapper) .setBorderColor(options.type.borderColor) .setHideOnClickOutside(false) .setHideOnFrameResize(false) options.balloonCustomizer?.accept(balloonBuilder) val balloon = balloonBuilder.createBalloon() if (balloon is BalloonImpl) { NotificationsManagerImpl.frameActivateBalloonListener(balloon, Runnable { AppExecutorUtil.getAppScheduledExecutorService().schedule({ balloon.setHideOnClickOutside(true) }, 100, TimeUnit.MILLISECONDS) }) } listenerWrapper.balloon = balloon entry.balloon = balloon Disposer.register(balloon, Disposable { entry.toolWindow.isPlaceholderMode = false entry.balloon = null }) Disposer.register(entry.disposable, balloon) return balloon } override fun getToolWindowBalloon(id: String) = idToEntry[id]?.balloon override val isEditorComponentActive: Boolean get() { ApplicationManager.getApplication().assertIsDispatchThread() return ComponentUtil.getParentOfType(EditorsSplitters::class.java, focusManager.focusOwner) != null } fun setToolWindowAnchor(id: String, anchor: ToolWindowAnchor) { ApplicationManager.getApplication().assertIsDispatchThread() setToolWindowAnchor(id, anchor, -1) } // used by Rider @Suppress("MemberVisibilityCanBePrivate") fun setToolWindowAnchor(id: String, anchor: ToolWindowAnchor, order: Int) { val entry = idToEntry[id]!! val info = entry.readOnlyWindowInfo if (anchor == info.anchor && (order == info.order || order == -1)) { return } ApplicationManager.getApplication().assertIsDispatchThread() setToolWindowAnchorImpl(entry, info, getRegisteredMutableInfoOrLogError(id), anchor, order) toolWindowPane!!.validateAndRepaint() fireStateChanged() } fun setLargeStripeAnchor(id: String, anchor: ToolWindowAnchor) { val entry = idToEntry[id]!! val info = entry.readOnlyWindowInfo ApplicationManager.getApplication().assertIsDispatchThread() setToolWindowLargeAnchorImpl(entry, info, getRegisteredMutableInfoOrLogError(id), anchor) toolWindowPane!!.validateAndRepaint() fireStateChanged() } fun setVisibleOnLargeStripe(id: String, visible: Boolean) { val info = getRegisteredMutableInfoOrLogError(id) info.isVisibleOnLargeStripe = visible idToEntry[info.id]!!.applyWindowInfo(info.copy()) fireStateChanged() } private fun setToolWindowAnchorImpl(entry: ToolWindowEntry, currentInfo: WindowInfo, layoutInfo: WindowInfoImpl, anchor: ToolWindowAnchor, order: Int) { // if tool window isn't visible or only order number is changed then just remove/add stripe button val toolWindowPane = toolWindowPane!! if (!currentInfo.isVisible || anchor == currentInfo.anchor || currentInfo.type == ToolWindowType.FLOATING || currentInfo.type == ToolWindowType.WINDOWED) { doSetAnchor(entry, layoutInfo, anchor, order) } else { val wasFocused = entry.toolWindow.isActive // for docked and sliding windows we have to move buttons and window's decorators layoutInfo.isVisible = false toolWindowPane.removeDecorator(currentInfo, entry.toolWindow.decoratorComponent, /* dirtyMode = */ true, this) doSetAnchor(entry, layoutInfo, anchor, order) showToolWindowImpl(entry, layoutInfo, false) if (wasFocused) { entry.toolWindow.requestFocusInToolWindow() } } } private fun doSetAnchor(entry: ToolWindowEntry, layoutInfo: WindowInfoImpl, anchor: ToolWindowAnchor, order: Int) { val toolWindowPane = toolWindowPane!! removeStripeButton(entry.stripeButton) layout.setAnchor(layoutInfo, anchor, order) // update infos for all window. Actually we have to update only infos affected by setAnchor method for (otherEntry in idToEntry.values) { val otherInfo = layout.getInfo(otherEntry.id)?.copy() ?: continue otherEntry.applyWindowInfo(otherInfo) } val stripe = toolWindowPane.getStripeFor(anchor) addStripeButton(entry.stripeButton, stripe) stripe.revalidate() } private fun setToolWindowLargeAnchorImpl(entry: ToolWindowEntry, currentInfo: WindowInfo, layoutInfo: WindowInfoImpl, anchor: ToolWindowAnchor) { val toolWindowPane = toolWindowPane!! if (!currentInfo.isVisible || anchor == currentInfo.largeStripeAnchor || currentInfo.type == ToolWindowType.FLOATING || currentInfo.type == ToolWindowType.WINDOWED) { doSetLargeAnchor(entry, layoutInfo, anchor) } else { val wasFocused = entry.toolWindow.isActive // for docked and sliding windows we have to move buttons and window's decorators layoutInfo.isVisible = false toolWindowPane.removeDecorator(currentInfo, entry.toolWindow.decoratorComponent, true, this) doSetLargeAnchor(entry, layoutInfo, anchor) showToolWindowImpl(entry, layoutInfo, false) if (wasFocused) { entry.toolWindow.requestFocusInToolWindow() } } } private fun doSetLargeAnchor(entry: ToolWindowEntry, layoutInfo: WindowInfoImpl, anchor: ToolWindowAnchor) { toolWindowPane!!.onStripeButtonAdded(project, entry.toolWindow, anchor, layoutInfo) layout.setAnchor(layoutInfo, anchor, -1) // update infos for all window. Actually we have to update only infos affected by setAnchor method for (otherEntry in idToEntry.values) { val otherInfo = layout.getInfo(otherEntry.id)?.copy() ?: continue otherEntry.applyWindowInfo(otherInfo) } } fun setOrderOnLargeStripe(id: String, order: Int) { val info = getRegisteredMutableInfoOrLogError(id) info.orderOnLargeStripe = order idToEntry[info.id]!!.applyWindowInfo(info.copy()) fireStateChanged() } internal fun setSideTool(id: String, isSplit: Boolean) { val entry = idToEntry[id] if (entry == null) { LOG.error("Cannot set side tool: toolwindow $id is not registered") return } if (entry.readOnlyWindowInfo.isSplit != isSplit) { setSideTool(entry, getRegisteredMutableInfoOrLogError(id), isSplit) fireStateChanged() } } private fun setSideTool(entry: ToolWindowEntry, info: WindowInfoImpl, isSplit: Boolean) { if (isSplit == info.isSplit) { return } // we should hide the window and show it in a 'new place' to automatically hide possible window that is already located in a 'new place' hideIfNeededAndShowAfterTask(entry, info) { info.isSplit = isSplit for (otherEntry in idToEntry.values) { otherEntry.applyWindowInfo((layout.getInfo(otherEntry.id) ?: continue).copy()) } } toolWindowPane!!.getStripeFor(entry.readOnlyWindowInfo.anchor).revalidate() } fun setContentUiType(id: String, type: ToolWindowContentUiType) { val info = getRegisteredMutableInfoOrLogError(id) info.contentUiType = type idToEntry[info.id!!]!!.applyWindowInfo(info.copy()) fireStateChanged() } fun setSideToolAndAnchor(id: String, anchor: ToolWindowAnchor, order: Int, isSplit: Boolean) { val entry = idToEntry[id]!! val info = getRegisteredMutableInfoOrLogError(id) if (anchor == entry.readOnlyWindowInfo.anchor && order == entry.readOnlyWindowInfo.order && entry.readOnlyWindowInfo.isSplit == isSplit) { return } hideIfNeededAndShowAfterTask(entry, info) { info.isSplit = isSplit doSetAnchor(entry, info, anchor, order) } fireStateChanged() } private fun hideIfNeededAndShowAfterTask(entry: ToolWindowEntry, info: WindowInfoImpl, source: ToolWindowEventSource? = null, task: () -> Unit) { val wasVisible = entry.readOnlyWindowInfo.isVisible val wasFocused = entry.toolWindow.isActive if (wasVisible) { doHide(entry, info, dirtyMode = true) } task() if (wasVisible) { ToolWindowCollector.getInstance().recordShown(project, source, info) info.isVisible = true val infoSnapshot = info.copy() entry.applyWindowInfo(infoSnapshot) doShowWindow(entry, infoSnapshot, dirtyMode = true) if (wasFocused) { getShowingComponentToRequestFocus(entry.toolWindow)?.requestFocusInWindow() } } toolWindowPane!!.validateAndRepaint() } protected open fun fireStateChanged() { project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).stateChanged(this) } private fun fireToolWindowShown(toolWindow: ToolWindow) { project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowShown(toolWindow) } internal fun setToolWindowAutoHide(id: String, autoHide: Boolean) { ApplicationManager.getApplication().assertIsDispatchThread() val info = getRegisteredMutableInfoOrLogError(id) if (info.isAutoHide == autoHide) { return } info.isAutoHide = autoHide val entry = idToEntry[id] ?: return val newInfo = info.copy() entry.applyWindowInfo(newInfo) fireStateChanged() } fun setToolWindowType(id: String, type: ToolWindowType) { ApplicationManager.getApplication().assertIsDispatchThread() val entry = idToEntry[id]!! if (entry.readOnlyWindowInfo.type == type) { return } setToolWindowTypeImpl(entry, getRegisteredMutableInfoOrLogError(entry.id), type) fireStateChanged() } private fun setToolWindowTypeImpl(entry: ToolWindowEntry, info: WindowInfoImpl, type: ToolWindowType) { if (!entry.readOnlyWindowInfo.isVisible) { info.type = type entry.applyWindowInfo(info.copy()) return } val dirtyMode = entry.readOnlyWindowInfo.type == ToolWindowType.DOCKED || entry.readOnlyWindowInfo.type == ToolWindowType.SLIDING updateStateAndRemoveDecorator(info, entry, dirtyMode) info.type = type val newInfo = info.copy() entry.applyWindowInfo(newInfo) doShowWindow(entry, newInfo, dirtyMode) if (ApplicationManager.getApplication().isActive) { entry.toolWindow.requestFocusInToolWindow() } val frame = frame!! val rootPane = frame.rootPane ?: return rootPane.revalidate() rootPane.repaint() } override fun clearSideStack() { if (isStackEnabled) { sideStack.clear() } } override fun getState(): Element? { // do nothing if the project was not opened if (frame == null) { return null } val element = Element("state") if (isEditorComponentActive) { element.addContent(Element(EDITOR_ELEMENT).setAttribute(ACTIVE_ATTR_VALUE, "true")) } // save layout of tool windows layout.writeExternal(DesktopLayout.TAG)?.let { element.addContent(it) } layoutToRestoreLater?.writeExternal(LAYOUT_TO_RESTORE)?.let { element.addContent(it) } if (recentToolWindows.isNotEmpty()) { val recentState = Element(RECENT_TW_TAG) recentToolWindows.forEach { recentState.addContent(Element("value").apply { addContent(it) }) } element.addContent(recentState) } return element } override fun noStateLoaded() { scheduleSetLayout(WindowManagerEx.getInstanceEx().layout.copy()) } override fun loadState(state: Element) { for (element in state.children) { if (DesktopLayout.TAG == element.name) { val layout = DesktopLayout() layout.readExternal(element) scheduleSetLayout(layout) } else if (LAYOUT_TO_RESTORE == element.name) { layoutToRestoreLater = DesktopLayout() layoutToRestoreLater!!.readExternal(element) } else if (RECENT_TW_TAG == element.name) { recentToolWindows.clear() element.content.forEach { recentToolWindows.add(it.value) } } } } private fun scheduleSetLayout(newLayout: DesktopLayout) { val app = ApplicationManager.getApplication() val task = Runnable { setLayout(newLayout) } if (app.isDispatchThread) { pendingSetLayoutTask.set(null) task.run() } else { pendingSetLayoutTask.set(task) app.invokeLater(Runnable { runPendingLayoutTask() }, project.disposed) } } internal fun setDefaultState(toolWindow: ToolWindowImpl, anchor: ToolWindowAnchor?, type: ToolWindowType?, floatingBounds: Rectangle?) { val info = getRegisteredMutableInfoOrLogError(toolWindow.id) if (info.isFromPersistentSettings) { return } if (floatingBounds != null) { info.floatingBounds = floatingBounds } if (anchor != null) { toolWindow.setAnchor(anchor, null) } if (type != null) { toolWindow.setType(type, null) } } internal fun setDefaultContentUiType(toolWindow: ToolWindowImpl, type: ToolWindowContentUiType) { val info = getRegisteredMutableInfoOrLogError(toolWindow.id) if (info.isFromPersistentSettings) { return } toolWindow.setContentUiType(type, null) } internal fun stretchWidth(toolWindow: ToolWindowImpl, value: Int) { toolWindowPane!!.stretchWidth(toolWindow, value) } override fun isMaximized(window: ToolWindow) = toolWindowPane!!.isMaximized(window) override fun setMaximized(window: ToolWindow, maximized: Boolean) { if (window.type == ToolWindowType.FLOATING && window is ToolWindowImpl) { MaximizeActiveDialogAction.doMaximize(getFloatingDecorator(window.id)) return } if (window.type == ToolWindowType.WINDOWED && window is ToolWindowImpl) { val decorator = getWindowedDecorator(window.id) val frame = if (decorator != null && decorator.getFrame() is Frame) decorator.getFrame() as Frame else return val state = frame.state if (state == Frame.NORMAL) { frame.state = Frame.MAXIMIZED_BOTH } else if (state == Frame.MAXIMIZED_BOTH) { frame.state = Frame.NORMAL } return } toolWindowPane!!.setMaximized(window, maximized) } internal fun stretchHeight(toolWindow: ToolWindowImpl?, value: Int) { toolWindowPane!!.stretchHeight((toolWindow)!!, value) } private class BalloonHyperlinkListener constructor(private val listener: HyperlinkListener?) : HyperlinkListener { var balloon: Balloon? = null override fun hyperlinkUpdate(e: HyperlinkEvent) { val balloon = balloon if (balloon != null && e.eventType == HyperlinkEvent.EventType.ACTIVATED) { balloon.hide() } listener?.hyperlinkUpdate(e) } } private fun addFloatingDecorator(entry: ToolWindowEntry, info: WindowInfo) { val frame = frame!!.frame val floatingDecorator = FloatingDecorator(frame!!, entry.toolWindow.getOrCreateDecoratorComponent() as InternalDecoratorImpl) floatingDecorator.apply(info) entry.floatingDecorator = floatingDecorator val bounds = info.floatingBounds if ((bounds != null && bounds.width > 0 && bounds.height > 0 && WindowManager.getInstance().isInsideScreenBounds(bounds.x, bounds.y, bounds.width))) { floatingDecorator.bounds = Rectangle(bounds) } else { val decorator = entry.toolWindow.decorator // place new frame at the center of main frame if there are no floating bounds var size = decorator.size if (size.width == 0 || size.height == 0) { size = decorator.preferredSize } floatingDecorator.size = size floatingDecorator.setLocationRelativeTo(frame) } @Suppress("DEPRECATION") floatingDecorator.show() } private fun addWindowedDecorator(entry: ToolWindowEntry, info: WindowInfo) { if (ApplicationManager.getApplication().isHeadlessEnvironment) { return } val id = entry.id val decorator = entry.toolWindow.getOrCreateDecoratorComponent() val windowedDecorator = FrameWrapper(project, title = "$id - ${project.name}", component = decorator) val window = windowedDecorator.getFrame() MnemonicHelper.init((window as RootPaneContainer).contentPane) val shouldBeMaximized = info.isMaximized val bounds = info.floatingBounds if ((bounds != null && bounds.width > 0 && (bounds.height > 0) && WindowManager.getInstance().isInsideScreenBounds(bounds.x, bounds.y, bounds.width))) { window.bounds = Rectangle(bounds) } else { // place new frame at the center of main frame if there are no floating bounds var size = decorator.size if (size.width == 0 || size.height == 0) { size = decorator.preferredSize } window.size = size window.setLocationRelativeTo(frame!!.frame) } entry.windowedDecorator = windowedDecorator Disposer.register(windowedDecorator, Disposable { if (idToEntry[id]?.windowedDecorator != null) { hideToolWindow(id, false) } }) windowedDecorator.show(false) val rootPane = (window as RootPaneContainer).rootPane val rootPaneBounds = rootPane.bounds val point = rootPane.locationOnScreen val windowBounds = window.bounds window.setLocation(2 * windowBounds.x - point.x, 2 * windowBounds.y - point.y) window.setSize(2 * windowBounds.width - rootPaneBounds.width, 2 * windowBounds.height - rootPaneBounds.height) if (shouldBeMaximized && window is Frame) { window.extendedState = Frame.MAXIMIZED_BOTH } window.toFront() } /** * Notifies window manager about focus traversal in a tool window */ internal class ToolWindowFocusWatcher(private val toolWindow: ToolWindowImpl, component: JComponent) : FocusWatcher() { private val id = toolWindow.id init { install(component) Disposer.register(toolWindow.disposable, Disposable { deinstall(component) }) } override fun isFocusedComponentChangeValid(component: Component?, cause: AWTEvent?) = component != null override fun focusedComponentChanged(component: Component?, cause: AWTEvent?) { if (component == null || !toolWindow.isActive) { return } val toolWindowManager = toolWindow.toolWindowManager toolWindowManager.focusManager .doWhenFocusSettlesDown(ExpirableRunnable.forProject(toolWindowManager.project) { GuiUtils.invokeLaterIfNeeded(Runnable { val entry = toolWindowManager.idToEntry[id] ?: return@Runnable val windowInfo = entry.readOnlyWindowInfo if (!windowInfo.isVisible) { return@Runnable } toolWindowManager.activateToolWindow(entry, toolWindowManager.getRegisteredMutableInfoOrLogError(entry.id), autoFocusContents = false) }, ModalityState.defaultModalityState(), toolWindowManager.project.disposed) }) } } /** * Spies on IdeToolWindow properties and applies them to the window * state. */ internal fun toolWindowPropertyChanged(toolWindow: ToolWindowImpl, property: ToolWindowProperty) { val entry = idToEntry[toolWindow.id] if (property == ToolWindowProperty.AVAILABLE && !toolWindow.isAvailable && entry?.readOnlyWindowInfo?.isVisible == true) { hideToolWindow(toolWindow.id, false) } val stripeButton = entry?.stripeButton if (stripeButton != null) { if (property == ToolWindowProperty.ICON) { stripeButton.updateIcon(toolWindow.icon) } else { stripeButton.updatePresentation() } } ActivateToolWindowAction.updateToolWindowActionPresentation(toolWindow) } internal fun activated(toolWindow: ToolWindowImpl, source: ToolWindowEventSource?) { activateToolWindow(idToEntry[toolWindow.id]!!, getRegisteredMutableInfoOrLogError(toolWindow.id), source = source) } /** * Handles event from decorator and modify weight/floating bounds of the * tool window depending on decoration type. */ @ApiStatus.Internal fun resized(source: InternalDecoratorImpl) { if (!source.isShowing) { // do not recalculate the tool window size if it is not yet shown (and, therefore, has 0,0,0,0 bounds) return } val toolWindow = source.toolWindow val info = getRegisteredMutableInfoOrLogError(toolWindow.id) if (info.type == ToolWindowType.FLOATING) { val owner = SwingUtilities.getWindowAncestor(source) if (owner != null) { info.floatingBounds = owner.bounds } } else if (info.type == ToolWindowType.WINDOWED) { val decorator = getWindowedDecorator(toolWindow.id) val frame = decorator?.getFrame() if (frame == null || !frame.isShowing) { return } info.floatingBounds = getRootBounds(frame as JFrame) info.isMaximized = frame.extendedState == Frame.MAXIMIZED_BOTH } else { // docked and sliding windows val anchor = info.anchor var another: InternalDecoratorImpl? = null val wholeSize = toolWindowPane!!.rootPane.size if (source.parent is Splitter) { var sizeInSplit = if (anchor.isSplitVertically) source.height else source.width val splitter = source.parent as Splitter if (splitter.secondComponent === source) { sizeInSplit += splitter.dividerWidth another = splitter.firstComponent as InternalDecoratorImpl } else { another = splitter.secondComponent as InternalDecoratorImpl } info.sideWeight = getAdjustedRatio(sizeInSplit, if (anchor.isSplitVertically) splitter.height else splitter.width, if (splitter.secondComponent === source) -1 else 1) } val paneWeight = getAdjustedRatio(if (anchor.isHorizontal) source.height else source.width, if (anchor.isHorizontal) wholeSize.height else wholeSize.width, 1) info.weight = paneWeight if (another != null) { getRegisteredMutableInfoOrLogError(another.toolWindow.id).weight = paneWeight } } } private fun getAdjustedRatio(partSize: Int, totalSize: Int, direction: Int): Float { var ratio = partSize.toFloat() / totalSize ratio += (((partSize.toFloat() + direction) / totalSize) - ratio) / 2 return ratio } private fun focusToolWindowByDefault() { var toFocus: ToolWindowEntry? = null for (each in activeStack.stack) { if (each.readOnlyWindowInfo.isVisible) { toFocus = each break } } if (toFocus == null) { for (each in activeStack.persistentStack) { if (each.readOnlyWindowInfo.isVisible) { toFocus = each break } } } if (toFocus != null && !ApplicationManager.getApplication().isDisposed) { activateToolWindow(toFocus, getRegisteredMutableInfoOrLogError(toFocus.id)) } } fun setShowStripeButton(id: String, visibleOnPanel: Boolean) { val info = getRegisteredMutableInfoOrLogError(id) if (visibleOnPanel == info.isShowStripeButton) { return } info.isShowStripeButton = visibleOnPanel idToEntry[info.id!!]!!.applyWindowInfo(info.copy()) fireStateChanged() } internal class InitToolWindowsActivity : StartupActivity { override fun runActivity(project: Project) { val app = ApplicationManager.getApplication() if (app.isUnitTestMode || app.isHeadlessEnvironment) { return } LOG.assertTrue(!app.isDispatchThread) val manager = getInstance(project) as ToolWindowManagerImpl val tasks = runActivity("toolwindow init command creation") { manager.computeToolWindowBeans() } app.invokeLater( manager.beforeProjectOpenedTask(tasks, app), project.disposed, ) } } private fun checkInvariants(additionalMessage: String) { if (!ApplicationManager.getApplication().isEAP && !ApplicationManager.getApplication().isInternal) { return } val violations = mutableListOf<String>() for (entry in idToEntry.values) { val info = layout.getInfo(entry.id) ?: continue if (!info.isVisible) { continue } if (info.type == ToolWindowType.FLOATING) { if (entry.floatingDecorator == null) { violations.add("Floating window has no decorator: ${entry.id}") } } else if (info.type == ToolWindowType.WINDOWED) { if (entry.windowedDecorator == null) { violations.add("Windowed window has no decorator: ${entry.id}") } } } if (violations.isNotEmpty()) { LOG.error("Invariants failed: \n${violations.joinToString("\n")}\nContext: $additionalMessage") } } private inline fun processDescriptors(crossinline handler: (bean: ToolWindowEP, pluginDescriptor: PluginDescriptor) -> Unit) { ToolWindowEP.EP_NAME.processWithPluginDescriptor { bean, pluginDescriptor -> try { handler(bean, pluginDescriptor) } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { LOG.error("Cannot process toolwindow ${bean.id}", e) } } } } private enum class KeyState { WAITING, PRESSED, RELEASED, HOLD } private fun areAllModifiersPressed(@JdkConstants.InputEventMask modifiers: Int, @JdkConstants.InputEventMask mask: Int): Boolean { return (modifiers xor mask) == 0 } @JdkConstants.InputEventMask private fun keyCodeToInputMask(code: Int): Int { return when (code) { KeyEvent.VK_SHIFT -> Event.SHIFT_MASK KeyEvent.VK_CONTROL -> Event.CTRL_MASK KeyEvent.VK_META -> Event.META_MASK KeyEvent.VK_ALT -> Event.ALT_MASK else -> 0 } } // We should filter out 'mixed' mask like InputEvent.META_MASK | InputEvent.META_DOWN_MASK @get:JdkConstants.InputEventMask private val activateToolWindowVKsMask: Int get() { if (!LoadingState.COMPONENTS_LOADED.isOccurred) { return 0 } if (Registry.`is`("toolwindow.disable.overlay.by.double.key")) { return 0 } val keymap = KeymapManager.getInstance().activeKeymap val baseShortcut = keymap.getShortcuts("ActivateProjectToolWindow") var baseModifiers = if (SystemInfo.isMac) InputEvent.META_MASK else InputEvent.ALT_MASK for (each in baseShortcut) { if (each is KeyboardShortcut) { val keyStroke = each.firstKeyStroke baseModifiers = keyStroke.modifiers if (baseModifiers > 0) { break } } } // We should filter out 'mixed' mask like InputEvent.META_MASK | InputEvent.META_DOWN_MASK return baseModifiers and (InputEvent.SHIFT_MASK or InputEvent.CTRL_MASK or InputEvent.META_MASK or InputEvent.ALT_MASK) } private val isStackEnabled: Boolean get() = Registry.`is`("ide.enable.toolwindow.stack") private fun getRootBounds(frame: JFrame): Rectangle { val rootPane = frame.rootPane val bounds = rootPane.bounds bounds.setLocation(frame.x + rootPane.x, frame.y + rootPane.y) return bounds } private const val EDITOR_ELEMENT = "editor" private const val ACTIVE_ATTR_VALUE = "active" private const val LAYOUT_TO_RESTORE = "layout-to-restore" private const val RECENT_TW_TAG = "recentWindows" internal enum class ToolWindowProperty { TITLE, ICON, AVAILABLE, STRIPE_TITLE } private fun isInActiveToolWindow(component: Any?, activeToolWindow: ToolWindowImpl): Boolean { var source = if (component is JComponent) component else null val activeToolWindowComponent = activeToolWindow.getComponentIfInitialized() if (activeToolWindowComponent != null) { while (source != null && source !== activeToolWindowComponent) { source = ComponentUtil.getClientProperty(source, ToolWindowManagerImpl.PARENT_COMPONENT) ?: source.parent as? JComponent } } return source != null } fun findIconFromBean(bean: ToolWindowEP, factory: ToolWindowFactory, pluginDescriptor: PluginDescriptor): Icon? { try { return IconLoader.findIcon(bean.icon ?: return null, factory.javaClass, pluginDescriptor.pluginClassLoader, null, true) } catch (e: Exception) { LOG.error(e) return EmptyIcon.ICON_13 } } fun getStripeTitleSupplier(id: String, pluginDescriptor: PluginDescriptor): Supplier<String>? { val classLoader = pluginDescriptor.pluginClassLoader val bundleName = when (pluginDescriptor.pluginId) { PluginManagerCore.CORE_ID -> IdeBundle.BUNDLE else -> pluginDescriptor.resourceBundleBaseName ?: return null } try { val bundle = DynamicBundle.INSTANCE.getResourceBundle(bundleName, classLoader) val key = "toolwindow.stripe.${id}".replace(" ", "_") @Suppress("HardCodedStringLiteral", "UnnecessaryVariable") val fallback = id val label = BundleBase.messageOrDefault(bundle, key, fallback) return Supplier { label } } catch (e: MissingResourceException) { LOG.warn("Missing bundle $bundleName at $classLoader", e) } return null } private fun addStripeButton(button: StripeButton, stripe: Stripe) { stripe.addButton(button) { o1, o2 -> windowInfoComparator.compare(o1.windowInfo, o2.windowInfo) } } private fun removeStripeButton(button: StripeButton) { (button.parent as? Stripe)?.removeButton(button) } @ApiStatus.Internal interface RegisterToolWindowTaskProvider { fun getTasks(project: Project): Collection<ToolWindowEP> } //Adding or removing items? Don't forget to increment the version in ToolWindowEventLogGroup.GROUP enum class ToolWindowEventSource { StripeButton, SquareStripeButton, ToolWindowHeader, ToolWindowHeaderAltClick, Content, Switcher, SwitcherSearch, ToolWindowsWidget, RemoveStripeButtonAction, HideOnShowOther, HideSide, CloseFromSwitcher, ActivateActionMenu, ActivateActionKeyboardShortcut, ActivateActionGotoAction, ActivateActionOther, CloseAction, HideButton, HideToolWindowAction, HideSideWindowsAction, HideAllWindowsAction, JumpToLastWindowAction, ToolWindowSwitcher, InspectionsWidget }
apache-2.0
b24213a100d38be488782acf9c9a5c4e
34.999569
207
0.691402
4.959713
false
false
false
false
leafclick/intellij-community
python/src/com/jetbrains/python/inspections/PyTypedDictInspection.kt
1
15847
// 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.inspections import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiNameIdentifierOwner import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.typing.PyTypedDictTypeProvider import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.documentation.PythonDocumentationProvider import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyEvaluator import com.jetbrains.python.psi.impl.PyPsiUtils import com.jetbrains.python.psi.types.PyTypeChecker import com.jetbrains.python.psi.types.PyTypedDictType import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_FIELDS_PARAMETER import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_NAME_PARAMETER import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_TOTAL_PARAMETER class PyTypedDictInspection : PyInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return Visitor(holder, session) } private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) { override fun visitPySubscriptionExpression(node: PySubscriptionExpression) { val operandType = myTypeEvalContext.getType(node.operand) if (operandType !is PyTypedDictType) return val indexExpression = node.indexExpression val indexExprValue = PyEvaluator.evaluate(indexExpression, String::class.java) if (indexExprValue == null) { registerProblem(indexExpression, "TypedDict key must be a string literal; expected one of " + "(${operandType.fields.keys.joinToString(transform = { "'$it'" })})") return } if (indexExprValue !in operandType.fields) { registerProblem(indexExpression, String.format("TypedDict \"%s\" has no key '%s'", operandType.name, indexExprValue)) } } override fun visitPyTargetExpression(node: PyTargetExpression) { val value = node.findAssignedValue() if (value is PyCallExpression && value.callee != null && PyTypedDictTypeProvider.isTypedDict(value.callee!!, myTypeEvalContext)) { val typedDictName = value.getArgument(0, TYPED_DICT_NAME_PARAMETER, PyExpression::class.java) if (typedDictName is PyStringLiteralExpression && node.name != typedDictName.stringValue) { registerProblem(typedDictName, "First argument has to match the variable name") } } } override fun visitPyArgumentList(node: PyArgumentList) { if (node.parent is PyClass && PyTypedDictTypeProvider.isTypingTypedDictInheritor(node.parent as PyClass, myTypeEvalContext)) { val arguments = node.arguments for (argument in arguments) { val type = myTypeEvalContext.getType(argument) if (argument !is PyKeywordArgument && type !is PyTypedDictType && !PyTypedDictTypeProvider.isTypedDict(argument, myTypeEvalContext)) { registerProblem(argument, "TypedDict cannot inherit from a non-TypedDict base class") } if (argument is PyKeywordArgument && argument.keyword == TYPED_DICT_TOTAL_PARAMETER && argument.valueExpression != null) { checkValidTotality(argument.valueExpression!!) } } } else if (node.callExpression != null) { val callExpression = node.callExpression val callee = callExpression!!.callee if (callee != null && PyTypedDictTypeProvider.isTypedDict(callee, myTypeEvalContext)) { val fields = callExpression.getArgument(1, TYPED_DICT_FIELDS_PARAMETER, PyExpression::class.java) if (fields !is PyDictLiteralExpression) { return } fields.elements.forEach { if (it !is PyKeyValueExpression) return checkValueIsAType(it.value, it.value?.text) } val totalityArgument = callExpression.getArgument(2, TYPED_DICT_TOTAL_PARAMETER, PyExpression::class.java) if (totalityArgument != null) { checkValidTotality(totalityArgument) } } } } override fun visitPyClass(node: PyClass) { if (!PyTypedDictTypeProvider.isTypingTypedDictInheritor(node, myTypeEvalContext)) return if (node.metaClassExpression != null) { registerProblem((node.metaClassExpression as PyExpression).parent, "Specifying a metaclass is not allowed in TypedDict") } val ancestorsFields = mutableMapOf<String, PyTypedDictType.FieldTypeAndTotality>() val typedDictAncestors = node.getAncestorTypes(myTypeEvalContext).filterIsInstance<PyTypedDictType>() typedDictAncestors.forEach { typedDict -> typedDict.fields.forEach { field -> val key = field.key val value = field.value if (key in ancestorsFields && !matchTypedDictFieldTypeAndTotality(ancestorsFields[key]!!, value)) { registerProblem(node.superClassExpressionList, "Cannot overwrite TypedDict field \'$key\' while merging") } else { ancestorsFields[key] = value } } } val singleStatement = node.statementList.statements.singleOrNull() if (singleStatement != null && singleStatement is PyExpressionStatement && singleStatement.expression is PyNoneLiteralExpression && (singleStatement.expression as PyNoneLiteralExpression).isEllipsis) { registerProblem(tryGetNameIdentifier(singleStatement), "Invalid statement in TypedDict definition; expected 'field_name: field_type'", ProblemHighlightType.WEAK_WARNING) return } node.processClassLevelDeclarations { element, _ -> if (element !is PyTargetExpression) { registerProblem(tryGetNameIdentifier(element), "Invalid statement in TypedDict definition; expected 'field_name: field_type'", ProblemHighlightType.WEAK_WARNING) return@processClassLevelDeclarations true } if (element.hasAssignedValue()) { registerProblem(element.findAssignedValue(), "Right hand side values are not supported in TypedDict") return@processClassLevelDeclarations true } if (element.name in ancestorsFields) { registerProblem(element, "Cannot overwrite TypedDict field") return@processClassLevelDeclarations true } checkValueIsAType(element.annotation?.value, element.annotationValue) true } } override fun visitPyDelStatement(node: PyDelStatement) { for (target in node.targets) { for (expr in PyUtil.flattenedParensAndTuples(target)) { if (expr !is PySubscriptionExpression) continue val type = myTypeEvalContext.getType(expr.operand) if (type is PyTypedDictType) { val index = PyEvaluator.evaluate(expr.indexExpression, String::class.java) if (index == null || index !in type.fields) continue if (type.fields[index]!!.isRequired) { registerProblem(expr.indexExpression, "Key '$index' of TypedDict '${type.name}' cannot be deleted") } } } } } override fun visitPyCallExpression(node: PyCallExpression) { val callee = node.callee if (callee !is PyReferenceExpression || callee.qualifier == null) return val nodeType = myTypeEvalContext.getType(callee.qualifier!!) if (nodeType !is PyTypedDictType) return val arguments = node.arguments if (PyNames.UPDATE == callee.name) { inspectUpdateSequenceArgument( if (arguments.size == 1 && arguments[0] is PySequenceExpression) (arguments[0] as PySequenceExpression).elements else arguments, nodeType) } if (PyNames.CLEAR == callee.name || PyNames.POPITEM == callee.name) { if (nodeType.fields.any { it.value.isRequired }) { registerProblem(callee.nameElement?.psi, "This operation might break TypedDict consistency", if (PyNames.CLEAR == callee.name) ProblemHighlightType.WARNING else ProblemHighlightType.WEAK_WARNING) } } if (PyNames.POP == callee.name) { val key = if (arguments.isNotEmpty()) PyEvaluator.evaluate(arguments[0], String::class.java) else null if (key != null && key in nodeType.fields && nodeType.fields[key]!!.isRequired) { registerProblem(callee.nameElement?.psi, "Key '$key' of TypedDict '${nodeType.name}' cannot be deleted") } } if (PyNames.SETDEFAULT == callee.name) { val key = if (arguments.isNotEmpty()) PyEvaluator.evaluate(arguments[0], String::class.java) else null if (key != null && key in nodeType.fields && !nodeType.fields[key]!!.isRequired) { if (node.arguments.size > 1) { val valueType = myTypeEvalContext.getType(arguments[1]) if (!PyTypeChecker.match(nodeType.fields[key]!!.type, valueType, myTypeEvalContext)) { registerProblem(arguments[1], String.format("Expected type '%s', got '%s' instead", PythonDocumentationProvider.getTypeName(nodeType.fields[key]!!.type, myTypeEvalContext), PythonDocumentationProvider.getTypeName(valueType, myTypeEvalContext))) } } } } if (PyTypingTypeProvider.resolveToQualifiedNames(callee, myTypeEvalContext).contains(PyTypingTypeProvider.MAPPING_GET)) { val keyArgument = node.getArgument(0, "key", PyExpression::class.java) ?: return val key = PyEvaluator.evaluate(keyArgument, String::class.java) if (key == null) { registerProblem(keyArgument, "Key should be string") return } if (!nodeType.fields.containsKey(key)) { registerProblem(keyArgument, "TypedDict \"${nodeType.name}\" has no key '$key'\n") } } } override fun visitPyAssignmentStatement(node: PyAssignmentStatement) { val targetsToValuesMapping = node.targetsToValuesMapping node.targets.forEach { target -> if (target !is PySubscriptionExpression) return@forEach val targetType = myTypeEvalContext.getType(target.operand) if (targetType !is PyTypedDictType) return@forEach val indexString = PyEvaluator.evaluate(target.indexExpression, String::class.java) if (indexString == null) return@forEach val expected = targetType.getElementType(indexString) val actualExpressions = targetsToValuesMapping.filter { it.first == target }.map { it.second } actualExpressions.forEach { actual -> val actualType = myTypeEvalContext.getType(actual) if (!PyTypeChecker.match(expected, actualType, myTypeEvalContext)) { registerProblem(actual, String.format("Expected type '%s', got '%s' instead", PythonDocumentationProvider.getTypeName(expected, myTypeEvalContext), PythonDocumentationProvider.getTypeName(actualType, myTypeEvalContext))) } } } } /** * Checks that [expression] with [strType] name is a type */ private fun checkValueIsAType(expression: PyExpression?, strType: String?) { if (expression !is PyReferenceExpression && expression !is PySubscriptionExpression || strType == null) { registerProblem(expression, "Value must be a type", ProblemHighlightType.WEAK_WARNING) return } val type = Ref.deref(PyTypingTypeProvider.getStringBasedType(strType, expression, myTypeEvalContext)) if (type == null && !PyTypingTypeProvider.resolveToQualifiedNames(expression, myTypeEvalContext).any { qualifiedName -> PyTypingTypeProvider.ANY == qualifiedName }) { registerProblem(expression, "Value must be a type", ProblemHighlightType.WEAK_WARNING) } } private fun tryGetNameIdentifier(element: PsiElement): PsiElement { return if (element is PsiNameIdentifierOwner) element.nameIdentifier ?: element else element } private fun checkValidTotality(totalityValue: PyExpression) { if (LanguageLevel.forElement(totalityValue.originalElement).isPy3K && totalityValue !is PyBoolLiteralExpression || !listOf(PyNames.TRUE, PyNames.FALSE).contains(totalityValue.text)) { registerProblem(totalityValue, "Value of 'total' must be True or False") } } private fun matchTypedDictFieldTypeAndTotality(expected: PyTypedDictType.FieldTypeAndTotality, actual: PyTypedDictType.FieldTypeAndTotality): Boolean { return expected.isRequired == actual.isRequired && PyTypeChecker.match(expected.type, actual.type, myTypeEvalContext) } private fun inspectUpdateSequenceArgument(sequenceElements: Array<PyExpression>, typedDictType: PyTypedDictType) { sequenceElements.forEach { var key: PsiElement? = null var keyAsString: String? = null var value: PyExpression? = null if (it is PyKeyValueExpression && it.key is PyStringLiteralExpression) { key = it.key keyAsString = (it.key as PyStringLiteralExpression).stringValue value = it.value } else if (it is PyParenthesizedExpression) { val expression = PyPsiUtils.flattenParens(it) if (expression == null) return@forEach if (expression is PyTupleExpression && expression.elements.size == 2 && expression.elements[0] is PyStringLiteralExpression) { key = expression.elements[0] keyAsString = (expression.elements[0] as PyStringLiteralExpression).stringValue value = expression.elements[1] } } else if (it is PyKeywordArgument && it.valueExpression != null) { key = it.keywordNode?.psi keyAsString = it.keyword value = it.valueExpression } else return@forEach val fields = typedDictType.fields if (value == null) { return@forEach } if (keyAsString == null) { registerProblem(key, "Cannot add a non-string key to TypedDict ${typedDictType.name}") return@forEach } if (!fields.containsKey(keyAsString)) { registerProblem(key, "TypedDict ${typedDictType.name} cannot have key ${keyAsString}") return@forEach } val valueType = myTypeEvalContext.getType(value) if (!PyTypeChecker.match(fields[keyAsString]?.type, valueType, myTypeEvalContext)) { registerProblem(value, String.format("Expected type '%s', got '%s' instead", PythonDocumentationProvider.getTypeName(fields[keyAsString]!!.type, myTypeEvalContext), PythonDocumentationProvider.getTypeName(valueType, myTypeEvalContext))) return@forEach } } } } }
apache-2.0
2f2320fe2961598d704e1f4594ca6997
47.170213
140
0.662965
5.195738
false
false
false
false
leafclick/intellij-community
plugins/stats-collector/src/com/intellij/stats/completion/LookupStateManager.kt
1
5281
/* * Copyright 2000-2018 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.stats.completion import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.stats.storage.factors.LookupStorage class LookupStateManager { private val elementToId = mutableMapOf<String, Int>() private val idToEntryInfo = mutableMapOf<Int, LookupEntryInfo>() private val lookupStringToHash = mutableMapOf<String, Int>() private var currentSessionFactors: Map<String, String> = emptyMap() fun update(lookup: LookupImpl, factorsUpdated: Boolean): LookupState { val ids = mutableListOf<Int>() val newIds = mutableSetOf<Int>() val items = lookup.items val currentPosition = items.indexOf(lookup.currentItem) val elementToId = mutableMapOf<LookupElement, Int>() for (item in items) { var id = getElementId(item) if (id == null) { id = registerElement(item) newIds.add(id) } elementToId[item] = id ids.add(id) } val storage = LookupStorage.get(lookup) val commonSessionFactors = storage?.sessionFactors?.getLastUsedCommonFactors() ?: emptyMap() val sessionFactorsToLog = computeSessionFactorsToLog(commonSessionFactors) if (factorsUpdated) { val infos = items.toLookupInfos(lookup, elementToId) val newInfos = infos.filter { it.id in newIds } val itemsDiff = infos.mapNotNull { idToEntryInfo[it.id]?.calculateDiff(it) } infos.forEach { idToEntryInfo[it.id] = it } return LookupState(ids, newInfos, itemsDiff, currentPosition, sessionFactorsToLog) } else { val newItems = items.filter { getElementId(it) in newIds }.toLookupInfos(lookup, elementToId) newItems.forEach { idToEntryInfo[it.id] = it } return LookupState(ids, newItems, emptyList(), currentPosition, sessionFactorsToLog) } } fun getElementId(item: LookupElement): Int? { val itemString = item.idString() return elementToId[itemString] } private fun computeSessionFactorsToLog(factors: Map<String, String>): Map<String, String> { if (factors == currentSessionFactors) return emptyMap() currentSessionFactors = factors return factors } private fun registerElement(item: LookupElement): Int { val itemString = item.idString() val newId = elementToId.size elementToId[itemString] = newId return newId } private fun List<LookupElement>.toLookupInfos(lookup: LookupImpl, elementToId: Map<LookupElement, Int>): List<LookupEntryInfo> { val item2relevance = calculateRelevance(lookup, this) return this.map { lookupElement -> val lookupString = lookupElement.lookupString val itemHash = getLookupStringHash(lookupString) LookupEntryInfo(elementToId.getValue(lookupElement), lookupString.length, itemHash, item2relevance.getValue(lookupElement)) } } private fun calculateRelevance(lookup: LookupImpl, items: List<LookupElement>): Map<LookupElement, Map<String, String>> { val lookupStorage = LookupStorage.get(lookup) val result = mutableMapOf<LookupElement, Map<String, String>>() if (lookupStorage != null) { for (item in items) { val factors = lookupStorage.getItemStorage(item.idString()).getLastUsedFactors()?.mapValues { it.value.toString() } if (factors != null) { result[item] = factors } } } // fallback (get factors from the relevance objects) val rest = items.filter { it !in result } if (rest.isNotEmpty()) { val relevanceObjects = lookup.getRelevanceObjects(rest, false) for (item in rest) { val relevanceMap: Map<String, String> = relevanceObjects[item]?.let { objects -> val (relevanceMap, additionalMap) = RelevanceUtil.asRelevanceMaps(objects) val features = mutableMapOf<String, String>() relevanceMap.forEach { features[it.key] = it.value.toString() } additionalMap.forEach { features[it.key] = it.value.toString() } return@let features } ?: emptyMap() result[item] = relevanceMap } } return result } private fun getLookupStringHash(lookupString: String): Int { return lookupStringToHash.computeIfAbsent(lookupString) { lookupStringToHash.size } } }
apache-2.0
c6b8d8dd03421f0872fbfc457cfd3ba1
40.265625
135
0.649877
4.809654
false
false
false
false
JuliusKunze/kotlin-native
runtime/src/main/kotlin/kotlin/math/math.kt
1
33337
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotlin.math // region ================ Constants ======================================== /** Ratio of the circumference of a circle to its diameter, approximately 3.14159. */ @SinceKotlin("1.2") public const val PI: Double = 3.141592653589793 /** Base of the natural logarithms, approximately 2.71828. */ @SinceKotlin("1.2") public const val E: Double = 2.718281828459045 // endregion // region ================ Double Math ======================================== /** Computes the sine of the angle [x] given in radians. * * Special cases: * - `sin(NaN|+Inf|-Inf)` is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_sin") external public fun sin(x: Double): Double /** Computes the cosine of the angle [x] given in radians. * * Special cases: * - `cos(NaN|+Inf|-Inf)` is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_cos") external public fun cos(x: Double): Double /** Computes the tangent of the angle [x] given in radians. * * Special cases: * - `tan(NaN|+Inf|-Inf)` is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_tan") external public fun tan(x: Double): Double /** * Computes the arc sine of the value [x]; * the returned value is an angle in the range from `-PI/2` to `PI/2` radians. * * Special cases: * - `asin(x)` is `NaN`, when `abs(x) > 1` or x is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_asin") external public fun asin(x: Double): Double /** * Computes the arc cosine of the value [x]; * the returned value is an angle in the range from `0.0` to `PI` radians. * * Special cases: * - `acos(x)` is `NaN`, when `abs(x) > 1` or x is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_acos") external public fun acos(x: Double): Double /** * Computes the arc tangent of the value [x]; * the returned value is an angle in the range from `-PI/2` to `PI/2` radians. * * Special cases: * - `atan(NaN)` is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_atan") external public fun atan(x: Double): Double /** * Returns the angle `theta` of the polar coordinates `(r, theta)` that correspond * to the rectangular coordinates `(x, y)` by computing the arc tangent of the value [y] / [x]; * the returned value is an angle in the range from `-PI` to `PI` radians. * * Special cases: * - `atan2(0.0, 0.0)` is `0.0` * - `atan2(0.0, x)` is `0.0` for `x > 0` and `PI` for `x < 0` * - `atan2(-0.0, x)` is `-0.0` for 'x > 0` and `-PI` for `x < 0` * - `atan2(y, +Inf)` is `0.0` for `0 < y < +Inf` and `-0.0` for '-Inf < y < 0` * - `atan2(y, -Inf)` is `PI` for `0 < y < +Inf` and `-PI` for `-Inf < y < 0` * - `atan2(y, 0.0)` is `PI/2` for `y > 0` and `-PI/2` for `y < 0` * - `atan2(+Inf, x)` is `PI/2` for finite `x`y * - `atan2(-Inf, x)` is `-PI/2` for finite `x` * - `atan2(NaN, x)` and `atan2(y, NaN)` is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_atan2") external public fun atan2(y: Double, x: Double): Double /** * Computes the hyperbolic sine of the value [x]. * * Special cases: * - `sinh(NaN)` is `NaN` * - `sinh(+Inf)` is `+Inf` * - `sinh(-Inf)` is `-Inf` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_sinh") external public fun sinh(x: Double): Double /** * Computes the hyperbolic cosine of the value [x]. * * Special cases: * - `cosh(NaN)` is `NaN` * - `cosh(+Inf|-Inf)` is `+Inf` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_cosh") external public fun cosh(x: Double): Double /** * Computes the hyperbolic tangent of the value [x]. * * Special cases: * - `tanh(NaN)` is `NaN` * - `tanh(+Inf)` is `1.0` * - `tanh(-Inf)` is `-1.0` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_tanh") external public fun tanh(x: Double): Double /** * Computes the inverse hyperbolic sine of the value [x]. * * The returned value is `y` such that `sinh(y) == x`. * * Special cases: * - `asinh(NaN)` is `NaN` * - `asinh(+Inf)` is `+Inf` * - `asinh(-Inf)` is `-Inf` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_asinh") external public fun asinh(x: Double): Double /** * Computes the inverse hyperbolic cosine of the value [x]. * * The returned value is positive `y` such that `cosh(y) == x`. * * Special cases: * - `acosh(NaN)` is `NaN` * - `acosh(x)` is `NaN` when `x < 1` * - `acosh(+Inf)` is `+Inf` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_acosh") external public fun acosh(x: Double): Double /** * Computes the inverse hyperbolic tangent of the value [x]. * * The returned value is `y` such that `tanh(y) == x`. * * Special cases: * - `tanh(NaN)` is `NaN` * - `tanh(x)` is `NaN` when `x > 1` or `x < -1` * - `tanh(1.0)` is `+Inf` * - `tanh(-1.0)` is `-Inf` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_atanh") external public fun atanh(x: Double): Double /** * Computes `sqrt(x^2 + y^2)` without intermediate overflow or underflow. * * Special cases: * - returns `+Inf` if any of arguments is infinite * - returns `NaN` if any of arguments is `NaN` and the other is not infinite */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_hypot") external public fun hypot(x: Double, y: Double): Double /** * Computes the positive square root of the value [x]. * * Special cases: * - `sqrt(x)` is `NaN` when `x < 0` or `x` is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_sqrt") external public fun sqrt(x: Double): Double /** * Computes Euler's number `e` raised to the power of the value [x]. * * Special cases: * - `exp(NaN)` is `NaN` * - `exp(+Inf)` is `+Inf` * - `exp(-Inf)` is `0.0` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_exp") external public fun exp(x: Double): Double /** * Computes `exp(x) - 1`. * * This function can be implemented to produce more precise result for [x] near zero. * * Special cases: * - `expm1(NaN)` is `NaN` * - `expm1(+Inf)` is `+Inf` * - `expm1(-Inf)` is `-1.0` * * @see [exp] function. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_expm1") external public fun expm1(x: Double): Double /** * Computes the logarithm of the value [x] to the given [base]. * * Special cases: * - `log(x, b)` is `NaN` if either `x` or `b` are `NaN` * - `log(x, b)` is `NaN` when `x < 0` or `b <= 0` or `b == 1.0` * - `log(+Inf, +Inf)` is `NaN` * - `log(+Inf, b)` is `+Inf` for `b > 1` and `-Inf` for `b < 1` * - `log(0.0, b)` is `-Inf` for `b > 1` and `+Inf` for `b > 1` * * See also logarithm functions for common fixed bases: [ln], [log10] and [log2]. */ @SinceKotlin("1.2") public fun log(x: Double, base: Double): Double { if (base <= 0.0 || base == 1.0) return Double.NaN return ln(x) / ln(base) } /** * Computes the natural logarithm (base `E`) of the value [x]. * * Special cases: * - `ln(NaN)` is `NaN` * - `ln(x)` is `NaN` when `x < 0.0` * - `ln(+Inf)` is `+Inf` * - `ln(0.0)` is `-Inf` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_ln") external public fun ln(x: Double): Double /** * Computes the common logarithm (base 10) of the value [x]. * * @see [ln] function for special cases. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_log10") external public fun log10(x: Double): Double /** * Computes the binary logarithm (base 2) of the value [x]. * * @see [ln] function for special cases. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_log2") external public fun log2(x: Double): Double /** * Computes `ln(x + 1)`. * * This function can be implemented to produce more precise result for [x] near zero. * * Special cases: * - `ln1p(NaN)` is `NaN` * - `ln1p(x)` is `NaN` where `x < -1.0` * - `ln1p(-1.0)` is `-Inf` * - `ln1p(+Inf)` is `+Inf` * * @see [ln] function * @see [expm1] function */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_ln1p") external public fun ln1p(x: Double): Double /** * Rounds the given value [x] to an integer towards positive infinity. * @return the smallest double value that is greater than the given value [x] and is a mathematical integer. * * Special cases: * - `ceil(x)` is `x` where `x` is `NaN` or `+Inf` or `-Inf` or already a mathematical integer. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_ceil") external public fun ceil(x: Double): Double /** * Rounds the given value [x] to an integer towards negative infinity. * @return the largest double value that is smaller than the given value [x] and is a mathematical integer. * * Special cases: * - `floor(x)` is `x` where `x` is `NaN` or `+Inf` or `-Inf` or already a mathematical integer. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_floor") external public fun floor(x: Double): Double /** * Rounds the given value [x] to an integer towards zero. * * @return the value [x] having its fractional part truncated. * * Special cases: * - `truncate(x)` is `x` where `x` is `NaN` or `+Inf` or `-Inf` or already a mathematical integer. */ @SinceKotlin("1.2") public fun truncate(x: Double): Double = when { x.isNaN() || x.isInfinite() -> x x > 0 -> floor(x) else -> ceil(x) } /** * Rounds the given value [x] towards the closest integer with ties rounded towards even integer. * * Special cases: * - `round(x)` is `x` where `x` is `NaN` or `+Inf` or `-Inf` or already a mathematical integer. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_round") external public fun round(x: Double): Double /** * Returns the absolute value of the given value [x]. * * Special cases: * - `abs(NaN)` is `NaN` * * @see absoluteValue extension property for [Double] */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_abs") external public fun abs(x: Double): Double /** * Returns the sign of the given value [x]: * - `-1.0` if the value is negative, * - zero if the value is zero, * - `1.0` if the value is positive * * Special case: * - `sign(NaN)` is `NaN` */ @SinceKotlin("1.2") public fun sign(x: Double): Double = when { x.isNaN() -> Double.NaN x > 0 -> 1.0 x < 0 -> -1.0 else -> x } /** * Returns the smaller of two values. * * If either value is `NaN`, then the result is `NaN`. */ @SinceKotlin("1.2") public fun min(a: Double, b: Double): Double = when { a.isNaN() || b.isNaN() -> Double.NaN a == 0.0 && b == 0.0 -> if (a.signBit()) a else b // -0.0 < +0.0 else -> if (a < b) a else b } /** * Returns the greater of two values. * * If either value is `NaN`, then the result is `NaN`. */ @SinceKotlin("1.2") public fun max(a: Double, b: Double): Double = when { a.isNaN() || b.isNaN() -> Double.NaN a == 0.0 && b == 0.0 -> if (!a.signBit()) a else b // -0.0 < +0.0 else -> if (a > b) a else b } // extensions /** * Raises this value to the power [x]. * * Special cases: * - `b.pow(0.0)` is `1.0` * - `b.pow(1.0) == b` * - `b.pow(NaN)` is `NaN` * - `NaN.pow(x)` is `NaN` for `x != 0.0` * - `b.pow(Inf)` is `NaN` for `abs(b) == 1.0` * - `b.pow(x)` is `NaN` for `b < 0` and `x` is finite and not an integer */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_Double_pow") external public fun Double.pow(x: Double): Double /** * Raises this value to the integer power [n]. * * See the other overload of [pow] for details. */ @SinceKotlin("1.2") public fun Double.pow(n: Int): Double = pow(n.toDouble()) /** * Computes the remainder of division of this value by the [divisor] value according to the IEEE 754 standard. * * The result is computed as `r = this - (q * divisor)` where `q` is the quotient of division rounded to the nearest integer, * `q = round(this / other)`. * * Special cases: * - `x.IEEErem(y)` is `NaN`, when `x` is `NaN` or `y` is `NaN` or `x` is `+Inf|-Inf` or `y` is zero. * - `x.IEEErem(y) == x` when `x` is finite and `y` is infinite. * * @see round */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_Double_IEEErem") external public fun Double.IEEErem(divisor: Double): Double /** * Returns the absolute value of this value. * * Special cases: * - `NaN.absoluteValue` is `NaN` * * @see abs function */ @SinceKotlin("1.2") public val Double.absoluteValue: Double get() = abs(this) /** * Returns the sign of this value: * - `-1.0` if the value is negative, * - zero if the value is zero, * - `1.0` if the value is positive * * Special case: * - `NaN.sign` is `NaN` */ @SinceKotlin("1.2") public val Double.sign: Double get() = sign(this) /** * Returns this value with the sign bit same as of the [sign] value. * * If [sign] is `NaN` the sign of the result is undefined. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_Double_withSign") external public fun Double.withSign(sign: Double): Double /** * Returns this value with the sign bit same as of the [sign] value. */ @SinceKotlin("1.2") public fun Double.withSign(sign: Int): Double = withSign(sign.toDouble()) /** * Returns the ulp (unit in the last place) of this value. * * An ulp is a positive distance between this value and the next nearest [Double] value larger in magnitude. * * Special Cases: * - `NaN.ulp` is `NaN` * - `x.ulp` is `+Inf` when `x` is `+Inf` or `-Inf` * - `0.0.ulp` is `Double.MIN_VALUE` */ @SinceKotlin("1.2") public val Double.ulp: Double get() = when { isNaN() -> Double.NaN isInfinite() -> Double.POSITIVE_INFINITY this == Double.MAX_VALUE || this == -Double.MAX_VALUE -> 2.0.pow(971) else -> { val d = absoluteValue d.nextUp() - d } } /** * Returns the [Double] value nearest to this value in direction of positive infinity. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_Double_nextUp") external public fun Double.nextUp(): Double /** * Returns the [Double] value nearest to this value in direction of negative infinity. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_Double_nextDown") external public fun Double.nextDown(): Double /** * Returns the [Double] value nearest to this value in direction from this value towards the value [to]. * * Special cases: * - `x.nextTowards(y)` is `NaN` if either `x` or `y` are `NaN` * - `x.nextTowards(x) == x` * */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_Double_nextTowards") external public fun Double.nextTowards(to: Double): Double /** * Returns true if the sign of [this] value is negative and false otherwise */ @SymbolName("Kotlin_math_Double_signBit") external private fun Double.signBit(): Boolean /** * Rounds this [Double] value to the nearest integer and converts the result to [Int]. * Ties are rounded towards positive infinity. * * Special cases: * - `x.roundToInt() == Int.MAX_VALUE` when `x > Int.MAX_VALUE` * - `x.roundToInt() == Int.MIN_VALUE` when `x < Int.MIN_VALUE` * * @throws IllegalArgumentException when this value is `NaN` */ @SinceKotlin("1.2") public fun Double.roundToInt(): Int = when { isNaN() -> throw IllegalArgumentException("Cannot round NaN value.") this > Int.MAX_VALUE -> Int.MAX_VALUE this < Int.MIN_VALUE -> Int.MIN_VALUE else -> floor(this + 0.5).toInt() } /** * Rounds this [Double] value to the nearest integer and converts the result to [Long]. * Ties are rounded towards positive infinity. * * Special cases: * - `x.roundToLong() == Long.MAX_VALUE` when `x > Long.MAX_VALUE` * - `x.roundToLong() == Long.MIN_VALUE` when `x < Long.MIN_VALUE` * * @throws IllegalArgumentException when this value is `NaN` */ @SinceKotlin("1.2") public fun Double.roundToLong(): Long = when { isNaN() -> throw IllegalArgumentException("Cannot round NaN value.") this > Long.MAX_VALUE -> Long.MAX_VALUE this < Long.MIN_VALUE -> Long.MIN_VALUE else -> floor(this + 0.5).toLong() } // endregion // region ================ Float Math ======================================== /** Computes the sine of the angle [x] given in radians. * * Special cases: * - `sin(NaN|+Inf|-Inf)` is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_sinf") external public fun sin(x: Float): Float /** Computes the cosine of the angle [x] given in radians. * * Special cases: * - `cos(NaN|+Inf|-Inf)` is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_cosf") external public fun cos(x: Float): Float /** Computes the tangent of the angle [x] given in radians. * * Special cases: * - `tan(NaN|+Inf|-Inf)` is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_tanf") external public fun tan(x: Float): Float /** * Computes the arc sine of the value [x]; * the returned value is an angle in the range from `-PI/2` to `PI/2` radians. * * Special cases: * - `asin(x)` is `NaN`, when `abs(x) > 1` or x is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_asinf") external public fun asin(x: Float): Float /** * Computes the arc cosine of the value [x]; * the returned value is an angle in the range from `0.0` to `PI` radians. * * Special cases: * - `acos(x)` is `NaN`, when `abs(x) > 1` or x is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_acosf") external public fun acos(x: Float): Float /** * Computes the arc tangent of the value [x]; * the returned value is an angle in the range from `-PI/2` to `PI/2` radians. * * Special cases: * - `atan(NaN)` is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_atanf") external public fun atan(x: Float): Float /** * Returns the angle `theta` of the polar coordinates `(r, theta)` that correspond * to the rectangular coordinates `(x, y)` by computing the arc tangent of the value [y] / [x]; * the returned value is an angle in the range from `-PI` to `PI` radians. * * Special cases: * - `atan2(0.0, 0.0)` is `0.0` * - `atan2(0.0, x)` is `0.0` for `x > 0` and `PI` for `x < 0` * - `atan2(-0.0, x)` is `-0.0` for 'x > 0` and `-PI` for `x < 0` * - `atan2(y, +Inf)` is `0.0` for `0 < y < +Inf` and `-0.0` for '-Inf < y < 0` * - `atan2(y, -Inf)` is `PI` for `0 < y < +Inf` and `-PI` for `-Inf < y < 0` * - `atan2(y, 0.0)` is `PI/2` for `y > 0` and `-PI/2` for `y < 0` * - `atan2(+Inf, x)` is `PI/2` for finite `x`y * - `atan2(-Inf, x)` is `-PI/2` for finite `x` * - `atan2(NaN, x)` and `atan2(y, NaN)` is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_atan2f") external public fun atan2(y: Float, x: Float): Float /** * Computes the hyperbolic sine of the value [x]. * * Special cases: * - `sinh(NaN)` is `NaN` * - `sinh(+Inf)` is `+Inf` * - `sinh(-Inf)` is `-Inf` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_sinhf") external public fun sinh(x: Float): Float /** * Computes the hyperbolic cosine of the value [x]. * * Special cases: * - `cosh(NaN)` is `NaN` * - `cosh(+Inf|-Inf)` is `+Inf` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_coshf") external public fun cosh(x: Float): Float /** * Computes the hyperbolic tangent of the value [x]. * * Special cases: * - `tanh(NaN)` is `NaN` * - `tanh(+Inf)` is `1.0` * - `tanh(-Inf)` is `-1.0` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_tanhf") external public fun tanh(x: Float): Float /** * Computes the inverse hyperbolic sine of the value [x]. * * The returned value is `y` such that `sinh(y) == x`. * * Special cases: * - `asinh(NaN)` is `NaN` * - `asinh(+Inf)` is `+Inf` * - `asinh(-Inf)` is `-Inf` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_asinhf") external public fun asinh(x: Float): Float /** * Computes the inverse hyperbolic cosine of the value [x]. * * The returned value is positive `y` such that `cosh(y) == x`. * * Special cases: * - `acosh(NaN)` is `NaN` * - `acosh(x)` is `NaN` when `x < 1` * - `acosh(+Inf)` is `+Inf` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_acoshf") external public fun acosh(x: Float): Float /** * Computes the inverse hyperbolic tangent of the value [x]. * * The returned value is `y` such that `tanh(y) == x`. * * Special cases: * - `tanh(NaN)` is `NaN` * - `tanh(x)` is `NaN` when `x > 1` or `x < -1` * - `tanh(1.0)` is `+Inf` * - `tanh(-1.0)` is `-Inf` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_atanhf") external public fun atanh(x: Float): Float /** * Computes `sqrt(x^2 + y^2)` without intermediate overflow or underflow. * * Special cases: * - returns `+Inf` if any of arguments is infinite * - returns `NaN` if any of arguments is `NaN` and the other is not infinite */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_hypotf") external public fun hypot(x: Float, y: Float): Float /** * Computes the positive square root of the value [x]. * * Special cases: * - `sqrt(x)` is `NaN` when `x < 0` or `x` is `NaN` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_sqrtf") external public fun sqrt(x: Float): Float /** * Computes Euler's number `e` raised to the power of the value [x]. * * Special cases: * - `exp(NaN)` is `NaN` * - `exp(+Inf)` is `+Inf` * - `exp(-Inf)` is `0.0` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_expf") external public fun exp(x: Float): Float /** * Computes `exp(x) - 1`. * * This function can be implemented to produce more precise result for [x] near zero. * * Special cases: * - `expm1(NaN)` is `NaN` * - `expm1(+Inf)` is `+Inf` * - `expm1(-Inf)` is `-1.0` * * @see [exp] function. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_expm1f") external public fun expm1(x: Float): Float /** * Computes the logarithm of the value [x] to the given [base]. * * Special cases: * - `log(x, b)` is `NaN` if either `x` or `b` are `NaN` * - `log(x, b)` is `NaN` when `x < 0` or `b <= 0` or `b == 1.0` * - `log(+Inf, +Inf)` is `NaN` * - `log(+Inf, b)` is `+Inf` for `b > 1` and `-Inf` for `b < 1` * - `log(0.0, b)` is `-Inf` for `b > 1` and `+Inf` for `b > 1` * * See also logarithm functions for common fixed bases: [ln], [log10] and [log2]. */ @SinceKotlin("1.2") public fun log(x: Float, base: Float): Float { if (base <= 0.0F || base == 1.0F) return Float.NaN return ln(x) / ln(base) } /** * Computes the natural logarithm (base `E`) of the value [x]. * * Special cases: * - `ln(NaN)` is `NaN` * - `ln(x)` is `NaN` when `x < 0.0` * - `ln(+Inf)` is `+Inf` * - `ln(0.0)` is `-Inf` */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_lnf") external public fun ln(x: Float): Float /** * Computes the common logarithm (base 10) of the value [x]. * * @see [ln] function for special cases. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_log10f") external public fun log10(x: Float): Float /** * Computes the binary logarithm (base 2) of the value [x]. * * @see [ln] function for special cases. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_log2f") external public fun log2(x: Float): Float /** * Computes `ln(a + 1)`. * * This function can be implemented to produce more precise result for [x] near zero. * * Special cases: * - `ln1p(NaN)` is `NaN` * - `ln1p(x)` is `NaN` where `x < -1.0` * - `ln1p(-1.0)` is `-Inf` * - `ln1p(+Inf)` is `+Inf` * * @see [ln] function * @see [expm1] function */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_ln1pf") external public fun ln1p(x: Float): Float /** * Rounds the given value [x] to an integer towards positive infinity. * @return the smallest Float value that is greater than the given value [x] and is a mathematical integer. * * Special cases: * - `ceil(x)` is `x` where `x` is `NaN` or `+Inf` or `-Inf` or already a mathematical integer. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_ceilf") external public fun ceil(x: Float): Float /** * Rounds the given value [x] to an integer towards negative infinity. * @return the largest Float value that is smaller than the given value [x] and is a mathematical integer. * * Special cases: * - `floor(x)` is `x` where `x` is `NaN` or `+Inf` or `-Inf` or already a mathematical integer. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_floorf") external public fun floor(x: Float): Float /** * Rounds the given value [x] to an integer towards zero. * * @return the value [x] having its fractional part truncated. * * Special cases: * - `truncate(x)` is `x` where `x` is `NaN` or `+Inf` or `-Inf` or already a mathematical integer. */ @SinceKotlin("1.2") public fun truncate(x: Float): Float = when { x.isNaN() || x.isInfinite() -> x x > 0 -> floor(x) else -> ceil(x) } /** * Rounds the given value [x] towards the closest integer with ties rounded towards even integer. * * Special cases: * - `round(x)` is `x` where `x` is `NaN` or `+Inf` or `-Inf` or already a mathematical integer. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_roundf") external public fun round(x: Float): Float /** * Returns the absolute value of the given value [x]. * * Special cases: * - `abs(NaN)` is `NaN` * * @see absoluteValue extension property for [Float] */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_absf") external public fun abs(x: Float): Float /** * Returns the sign of the given value [x]: * - `-1.0` if the value is negative, * - zero if the value is zero, * - `1.0` if the value is positive * * Special case: * - `sign(NaN)` is `NaN` */ @SinceKotlin("1.2") public fun sign(x: Float): Float = when { x.isNaN() -> Float.NaN x > 0 -> 1.0f x < 0 -> -1.0f else -> x } /** * Returns the smaller of two values. * * If either value is `NaN`, then the result is `NaN`. */ @SinceKotlin("1.2") public fun min(a: Float, b: Float): Float = when { a.isNaN() || b.isNaN() -> Float.NaN a == 0.0f && b == 0.0f -> if (a.signBit()) a else b // -0.0 < +0.0 else -> if (a < b) a else b } /** * Returns the greater of two values. * * If either value is `NaN`, then the result is `NaN`. */ @SinceKotlin("1.2") public fun max(a: Float, b: Float): Float = when { a.isNaN() || b.isNaN() -> Float.NaN a == 0.0f && b == 0.0f -> if (!a.signBit()) a else b // -0.0 < +0.0 else -> if (a > b) a else b } // extensions /** * Raises this value to the power [x]. * * Special cases: * - `b.pow(0.0)` is `1.0` * - `b.pow(1.0) == b` * - `b.pow(NaN)` is `NaN` * - `NaN.pow(x)` is `NaN` for `x != 0.0` * - `b.pow(Inf)` is `NaN` for `abs(b) == 1.0` * - `b.pow(x)` is `NaN` for `b < 0` and `x` is finite and not an integer */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_Float_pow") external public fun Float.pow(x: Float): Float /** * Raises this value to the integer power [n]. * * See the other overload of [pow] for details. */ @SinceKotlin("1.2") public fun Float.pow(n: Int): Float = pow(n.toFloat()) /** * Computes the remainder of division of this value by the [divisor] value according to the IEEE 754 standard. * * The result is computed as `r = this - (q * divisor)` where `q` is the quotient of division rounded to the nearest integer, * `q = round(this / other)`. * * Special cases: * - `x.IEEErem(y)` is `NaN`, when `x` is `NaN` or `y` is `NaN` or `x` is `+Inf|-Inf` or `y` is zero. * - `x.IEEErem(y) == x` when `x` is finite and `y` is infinite. * * @see round */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_Float_IEEErem") external public fun Float.IEEErem(divisor: Float): Float /** * Returns the absolute value of this value. * * Special cases: * - `NaN.absoluteValue` is `NaN` * * @see abs function */ @SinceKotlin("1.2") public val Float.absoluteValue: Float get() = abs(this) /** * Returns the sign of this value: * - `-1.0` if the value is negative, * - zero if the value is zero, * - `1.0` if the value is positive * * Special case: * - `NaN.sign` is `NaN` */ @SinceKotlin("1.2") public val Float.sign: Float get() = sign(this) /** * Returns this value with the sign bit same as of the [sign] value. * * If [sign] is `NaN` the sign of the result is undefined. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_Float_withSign") external public fun Float.withSign(sign: Float): Float /** * Returns this value with the sign bit same as of the [sign] value. */ @SinceKotlin("1.2") public fun Float.withSign(sign: Int): Float = withSign(sign.toFloat()) @SinceKotlin("1.2") public val Float.ulp: Float get() = when { isNaN() -> Float.NaN isInfinite() -> Float.POSITIVE_INFINITY this == Float.MAX_VALUE || this == -Float.MAX_VALUE -> 2.0f.pow(104) else -> { val d = absoluteValue d.nextUp() - d } } /** * Returns the [Float] value nearest to this value in direction of positive infinity. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_Float_nextUp") external public fun Float.nextUp(): Float /** * Returns the [Float] value nearest to this value in direction of negative infinity. */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_Float_nextDown") external public fun Float.nextDown(): Float /** * Returns the [Float] value nearest to this value in direction from this value towards the value [to]. * * Special cases: * - `x.nextTowards(y)` is `NaN` if either `x` or `y` are `NaN` * - `x.nextTowards(x) == x` * */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_Float_nextTowards") external public fun Float.nextTowards(to: Float): Float /** * Returns true if the sign of [this] value is negative and false otherwise */ @SymbolName("Kotlin_math_Float_signBit") external private fun Float.signBit(): Boolean /** * Rounds this [Float] value to the nearest integer and converts the result to [Int]. * Ties are rounded towards positive infinity. * * Special cases: * - `x.roundToInt() == Int.MAX_VALUE` when `x > Int.MAX_VALUE` * - `x.roundToInt() == Int.MIN_VALUE` when `x < Int.MIN_VALUE` * * @throws IllegalArgumentException when this value is `NaN` */ @SinceKotlin("1.2") public fun Float.roundToInt(): Int = when { isNaN() -> throw IllegalArgumentException("Cannot round NaN value.") this > Int.MAX_VALUE -> Int.MAX_VALUE this < Int.MIN_VALUE -> Int.MIN_VALUE else -> floor(this + 0.5f).toInt() } /** * Rounds this [Float] value to the nearest integer and converts the result to [Long]. * Ties are rounded towards positive infinity. * * Special cases: * - `x.roundToLong() == Long.MAX_VALUE` when `x > Long.MAX_VALUE` * - `x.roundToLong() == Long.MIN_VALUE` when `x < Long.MIN_VALUE` * * @throws IllegalArgumentException when this value is `NaN` */ @SinceKotlin("1.2") public fun Float.roundToLong(): Long = when { isNaN() -> throw IllegalArgumentException("Cannot round NaN value.") this > Long.MAX_VALUE -> Long.MAX_VALUE this < Long.MIN_VALUE -> Long.MIN_VALUE else -> floor(this + 0.5f).toLong() } // endregion // region ================ Integer Math ======================================== /** * Returns the absolute value of the given value [n]. * * Special cases: * - `abs(Int.MIN_VALUE)` is `Int.MIN_VALUE` due to an overflow * * @see absoluteValue extension property for [Int] */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_absi") external public fun abs(n: Int): Int /** * Returns the smaller of two values. */ @SinceKotlin("1.2") public fun min(a: Int, b: Int): Int = if (a < b) a else b /** * Returns the greater of two values. */ @SinceKotlin("1.2") public fun max(a: Int, b: Int): Int = if (a > b) a else b /** * Returns the absolute value of this value. * * Special cases: * - `Int.MIN_VALUE.absoluteValue` is `Int.MIN_VALUE` due to an overflow * * @see abs function */ @SinceKotlin("1.2") public val Int.absoluteValue: Int get() = abs(this) /** * Returns the sign of this value: * - `-1` if the value is negative, * - `0` if the value is zero, * - `1` if the value is positive */ @SinceKotlin("1.2") public val Int.sign: Int get() = when { this < 0 -> -1 this > 0 -> 1 else -> 0 } /** * Returns the absolute value of the given value [n]. * * Special cases: * - `abs(Long.MIN_VALUE)` is `Long.MIN_VALUE` due to an overflow * * @see absoluteValue extension property for [Long] */ @SinceKotlin("1.2") @SymbolName("Kotlin_math_absl") external public fun abs(n: Long): Long /** * Returns the smaller of two values. */ @SinceKotlin("1.2") public fun min(a: Long, b: Long): Long = if (a < b) a else b /** * Returns the greater of two values. */ @SinceKotlin("1.2") public fun max(a: Long, b: Long): Long = if (a > b) a else b /** * Returns the absolute value of this value. * * Special cases: * - `Long.MIN_VALUE.absoluteValue` is `Long.MIN_VALUE` due to an overflow * * @see abs function */ @SinceKotlin("1.2") public val Long.absoluteValue: Long get() = abs(this) /** * Returns the sign of this value: * - `-1` if the value is negative, * - `0` if the value is zero, * - `1` if the value is positive */ @SinceKotlin("1.2") public val Long.sign: Int get() = when { this < 0 -> -1 this > 0 -> 1 else -> 0 } // endregion
apache-2.0
b91d27f15ea54957da3cecd3daac9383
26.303849
125
0.613103
2.92276
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/classes/rightHandOverride.kt
5
357
// Changed when traits were introduced. May not make sense any more interface Left {} open class Right() { open fun f() = 42 } class D() : Left, Right() { override fun f() = 239 } fun box() : String { val r : Right = Right() val d : D = D() if (r.f() != 42) return "Fail #1" if (d.f() != 239) return "Fail #2" return "OK" }
apache-2.0
5ab5a8105477a174a008cd563960f345
16.85
67
0.546218
3.051282
false
false
false
false
chromeos/video-composition-sample
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/ui/custom/ResolutionView.kt
1
3793
/* * 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 * * 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 dev.chromeos.videocompositionsample.presentation.ui.custom import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.widget.LinearLayout import android.widget.TextView import dev.chromeos.videocompositionsample.presentation.R class ResolutionView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : LinearLayout(context, attrs, defStyleAttr) { enum class Resolution(val width: Int, val height: Int) { Eighth(480, 270), Quarter(960, 540), Half(1920, 1080), Full(3840, 2160) } private lateinit var tvEighth: TextView private lateinit var tvQuarter: TextView private lateinit var tvHalf: TextView private lateinit var tvFull: TextView private val checkedBackgroundResId: Int = R.drawable.rect_round_white_80 private var listener: OnResolutionCheckListener? = null interface OnResolutionCheckListener { fun onEighthChecked() fun onQuarterChecked() fun onHalfChecked() fun onFullChecked() } var resolution: Resolution = Resolution.Full set(value) { if (value != field) { field = value when (value) { Resolution.Eighth -> tvEighth.performClick() Resolution.Quarter -> tvQuarter.performClick() Resolution.Half -> tvHalf.performClick() Resolution.Full -> tvFull.performClick() } } } init { init() } fun setOnResolutionCheckListener(listener: OnResolutionCheckListener) { this.listener = listener } private fun init() { val root = LayoutInflater.from(context).inflate(R.layout.resolution_view, this, true) tvEighth = root.findViewById(R.id.tvEighth) tvQuarter = root.findViewById(R.id.tvQuarter) tvHalf = root.findViewById(R.id.tvHalf) tvFull = root.findViewById(R.id.tvFull) tvEighth.setOnClickListener { setBackgroundRes(checkedBackgroundResId, 0, 0, 0) resolution = Resolution.Eighth listener?.onEighthChecked() } tvQuarter.setOnClickListener { setBackgroundRes(0, checkedBackgroundResId, 0, 0) resolution = Resolution.Quarter listener?.onQuarterChecked() } tvHalf.setOnClickListener { setBackgroundRes(0, 0, checkedBackgroundResId, 0) resolution = Resolution.Half listener?.onHalfChecked() } tvFull.setOnClickListener { setBackgroundRes(0, 0, 0, checkedBackgroundResId) resolution = Resolution.Full listener?.onFullChecked() } setBackgroundRes(0, 0, 0, checkedBackgroundResId) } private fun setBackgroundRes(eighthResId: Int, quarterResId: Int, halfResId: Int, fullResId: Int) { tvEighth.setBackgroundResource(eighthResId) tvQuarter.setBackgroundResource(quarterResId) tvHalf.setBackgroundResource(halfResId) tvFull.setBackgroundResource(fullResId) } }
apache-2.0
4b744e7fc969b215b1e810921fc8f79b
31.706897
103
0.662009
4.653988
false
false
false
false
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/handlers/MarkdownTableBackspaceHandler.kt
6
3848
// 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.intellij.plugins.markdown.editor.tables.handlers import com.intellij.codeInsight.editorActions.BackspaceHandlerDelegate import com.intellij.openapi.command.executeCommand import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.registry.Registry import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import org.intellij.plugins.markdown.editor.tables.TableFormattingUtils.reformatColumnOnChange import org.intellij.plugins.markdown.editor.tables.TableModificationUtils.modifyColumn import org.intellij.plugins.markdown.editor.tables.TableUtils import org.intellij.plugins.markdown.editor.tables.TableUtils.separatorRow import org.intellij.plugins.markdown.lang.MarkdownFileType import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableSeparatorRow import org.intellij.plugins.markdown.settings.MarkdownSettings internal class MarkdownTableBackspaceHandler: BackspaceHandlerDelegate() { override fun beforeCharDeleted(c: Char, file: PsiFile, editor: Editor) = Unit override fun charDeleted(char: Char, file: PsiFile, editor: Editor): Boolean { if (!Registry.`is`("markdown.tables.editing.support.enable") || !MarkdownSettings.getInstance(file.project).isEnhancedEditingEnabled) { return false } if (file.fileType != MarkdownFileType.INSTANCE) { return false } val caretOffset = editor.caretModel.currentCaret.offset val document = editor.document if (!TableUtils.isProbablyInsideTableCell(document, caretOffset)) { return false } PsiDocumentManager.getInstance(file.project).commitDocument(document) val table = TableUtils.findTable(file, caretOffset) ?: return false val cellIndex = TableUtils.findCellIndex(file, caretOffset) ?: return false val alignment = table.separatorRow?.getCellAlignment(cellIndex) ?: return false val width = TableUtils.findCell(file, caretOffset)?.textRange?.length ?: table.separatorRow?.getCellRange(cellIndex)?.length ?: 0 val text = document.charsSequence executeCommand(table.project) { table.modifyColumn( cellIndex, transformSeparator = { updateSeparator(document, it, width) }, transformCell = { cell -> val range = cell.textRange if (range.length > width && text[range.endOffset - 1] == ' ' && text[range.endOffset - 2] == ' ') { document.deleteString(range.endOffset - 1, range.endOffset) } } ) if (alignment != MarkdownTableSeparatorRow.CellAlignment.NONE) { PsiDocumentManager.getInstance(file.project).commitDocument(document) val reparsedTable = TableUtils.findTable(file, caretOffset) val isBlank = TableUtils.findCell(file, caretOffset)?.textRange?.let { text.substring(it.startOffset, it.endOffset) }?.isBlank() ?: true val shouldPreventExpand = isBlank && char == ' ' reparsedTable?.reformatColumnOnChange( document, editor.caretModel.allCarets, cellIndex, trimToMaxContent = false, preventExpand = shouldPreventExpand ) } } return true } private fun updateSeparator(document: Document, separatorRange: TextRange, width: Int) { val text = document.charsSequence if (separatorRange.length > width) { val endOffset = separatorRange.endOffset val offset = when { text[endOffset - 1] == '-' -> separatorRange.endOffset - 1 text[endOffset - 2] == '-' -> separatorRange.endOffset - 2 else -> return } document.deleteString(offset, offset + 1) } } }
apache-2.0
4fa0b34e910ceb8abd3c4e02ddaf5dbb
46.506173
158
0.72973
4.580952
false
false
false
false
android/storage-samples
ActionOpenDocumentTree/app/src/main/java/com/example/android/ktfiles/DirectoryFragmentViewModel.kt
1
2695
/* * 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 com.example.android.ktfiles import android.app.Application import android.net.Uri import androidx.documentfile.provider.DocumentFile import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * ViewModel for the [DirectoryFragment]. */ class DirectoryFragmentViewModel(application: Application) : AndroidViewModel(application) { private val _documents = MutableLiveData<List<CachingDocumentFile>>() val documents = _documents private val _openDirectory = MutableLiveData<Event<CachingDocumentFile>>() val openDirectory = _openDirectory private val _openDocument = MutableLiveData<Event<CachingDocumentFile>>() val openDocument = _openDocument fun loadDirectory(directoryUri: Uri) { val documentsTree = DocumentFile.fromTreeUri(getApplication(), directoryUri) ?: return val childDocuments = documentsTree.listFiles().toCachingList() // It's much nicer when the documents are sorted by something, so we'll sort the documents // we got by name. Unfortunate there may be quite a few documents, and sorting can take // some time, so we'll take advantage of coroutines to take this work off the main thread. viewModelScope.launch { val sortedDocuments = withContext(Dispatchers.IO) { childDocuments.toMutableList().apply { sortBy { it.name } } } _documents.postValue(sortedDocuments) } } /** * Method to dispatch between clicking on a document (which should be opened), and * a directory (which the user wants to navigate into). */ fun documentClicked(clickedDocument: CachingDocumentFile) { if (clickedDocument.isDirectory) { openDirectory.postValue(Event(clickedDocument)) } else { openDocument.postValue(Event(clickedDocument)) } } }
apache-2.0
d988e66e97561b8abd8b0e7b57606051
37.514286
98
0.716141
4.9
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/surroundWith/expression/KotlinWhenSurrounder.kt
2
2241
// 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.codeInsight.surroundWith.expression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.idea.core.surroundWith.KotlinExpressionSurrounder import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtWhenExpression import com.intellij.codeInsight.CodeInsightUtilBase import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.TextRange import com.intellij.refactoring.suggested.startOffset import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.quickfix.AddWhenRemainingBranchesFix class KotlinWhenSurrounder : KotlinExpressionSurrounder() { @NlsSafe override fun getTemplateDescription() = "when (expr) {}" override fun surroundExpression(project: Project, editor: Editor, expression: KtExpression): TextRange { val template = "when(a) { \nb -> {}\n else -> {}\n}" val whenExpression = (KtPsiFactory(expression).createExpression(template) as KtWhenExpression).let { it.subjectExpression?.replace(expression) expression.replaced(it) } val hasRemainingBranches = AddWhenRemainingBranchesFix.isAvailable(whenExpression) if (hasRemainingBranches) { AddWhenRemainingBranchesFix.addRemainingBranches(whenExpression) whenExpression.entries.also { it.first().delete() it.last().delete() } } CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(whenExpression) val firstEntry = whenExpression.entries.first() val offset = if (hasRemainingBranches) { firstEntry.expression?.startOffset ?: firstEntry.startOffset } else { val conditionRange = firstEntry.conditions.first().textRange editor.document.deleteString(conditionRange.startOffset, conditionRange.endOffset) conditionRange.startOffset } return TextRange(offset, offset) } }
apache-2.0
edaf9f38c7b095ec5256848a8c73a85d
44.734694
158
0.735832
5.116438
false
false
false
false
smmribeiro/intellij-community
platform/platform-util-netty/src/org/jetbrains/ide/HttpRequestHandler.kt
1
3953
// 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.ide import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.util.io.getHostName import com.intellij.util.io.isLocalHost import com.intellij.util.io.isLocalOrigin import io.netty.channel.Channel import io.netty.channel.ChannelFutureListener import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.http.* import io.netty.handler.stream.ChunkedStream import org.jetbrains.io.FileResponses import org.jetbrains.io.addCommonHeaders import org.jetbrains.io.addKeepAliveIfNeeded import java.io.ByteArrayInputStream import java.io.IOException import java.util.* /** * See [Remote Communication](https://youtrack.jetbrains.com/articles/IDEA-A-63/Remote-Communication) */ abstract class HttpRequestHandler { enum class OriginCheckResult { ALLOW, FORBID, // any origin is allowed but user confirmation is required ASK_CONFIRMATION } companion object { // Your handler will be instantiated on first user request val EP_NAME = ExtensionPointName<HttpRequestHandler>("com.intellij.httpRequestHandler") @JvmStatic fun checkPrefix(uri: String, prefix: String): Boolean { if (uri.length > prefix.length && uri[0] == '/' && uri.regionMatches(1, prefix, 0, prefix.length, ignoreCase = true)) { if (uri.length - prefix.length == 1) { return true } else { val c = uri.get(prefix.length + 1) return c == '/' || c == '?' } } return false } } /** * Write request from browser without Origin will always be blocked regardless of your implementation. */ @SuppressWarnings("SpellCheckingInspection") open fun isAccessible(request: HttpRequest): Boolean { val hostName = getHostName(request) // If attacker.com DNS rebound to 127.0.0.1 and user open site directly - no Origin or Referrer headers. // So we should check Host header. return hostName != null && isOriginAllowed(request) != OriginCheckResult.FORBID && isLocalHost(hostName) } protected open fun isOriginAllowed(request: HttpRequest): OriginCheckResult { return if (request.isLocalOrigin()) OriginCheckResult.ALLOW else OriginCheckResult.FORBID } open fun isSupported(request: FullHttpRequest): Boolean { return request.method() === HttpMethod.GET || request.method() === HttpMethod.HEAD } /** * @return true if processed successfully, false to pass processing to other handlers. */ @Throws(IOException::class) abstract fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean protected fun sendData(content: ByteArray, name: String, request: FullHttpRequest, channel: Channel, extraHeaders: HttpHeaders): Boolean { val response = DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK) response.headers().set(HttpHeaderNames.CONTENT_TYPE, FileResponses.getContentType(name)) response.addCommonHeaders() response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, must-revalidate") //NON-NLS response.headers().set(HttpHeaderNames.LAST_MODIFIED, Date(Calendar.getInstance().timeInMillis)) response.headers().add(extraHeaders) val keepAlive = response.addKeepAliveIfNeeded(request) if (request.method() != HttpMethod.HEAD) { HttpUtil.setContentLength(response, content.size.toLong()) } channel.write(response) if (request.method() != HttpMethod.HEAD) { val stream = ByteArrayInputStream(content) channel.write(ChunkedStream(stream)) stream.close() } val future = channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT) if (!keepAlive) { future.addListener(ChannelFutureListener.CLOSE) } return true } }
apache-2.0
50a6583fe684315395dbb9c48f7b6fcd
37.38835
158
0.73362
4.436588
false
false
false
false
smmribeiro/intellij-community
platform/statistics/src/com/intellij/internal/statistic/eventLog/EventLogGroup.kt
1
4431
// 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.internal.statistic.eventLog import com.intellij.internal.statistic.IdeActivityDefinition import com.intellij.internal.statistic.eventLog.events.* /** * Best practices: * - Prefer a bigger group with many (related) event types to many small groups of 1-2 events each * - Prefer shorter group names; avoid common prefixes (such as "statistics.") */ class EventLogGroup(val id: String, val version: Int) { private val registeredEventIds = mutableSetOf<String>() private val registeredEvents = mutableListOf<BaseEventId>() val events: List<BaseEventId> get() = registeredEvents private fun addToRegisteredEvents(eventId: BaseEventId) { registeredEvents.add(eventId) registeredEventIds.add(eventId.eventId) } /** * New style API to record IDE events (e.g. invoked action, opened dialog) or state. * * For events with more than 3 fields use EventLogGroup.registerVarargEvent * * To implement a new collector: * - Record events according to a "fus-collectors.md" dev guide and register it in plugin.xml * - Implement custom validation rules if necessary (see [com.intellij.internal.statistic.eventLog.validator.IntellijSensitiveDataValidator]) * - If new group is implemented in a platform or a plugin built with IntelliJ Ultimate, YT issue will be created automatically * - Otherwise, create a YT issue in FUS project with group data scheme and descriptions to register it on the statistics metadata server * * To test collector: * - If group is not registered on the server, add it to events test scheme with "Add Group to Events Test Scheme" action. * (com.intellij.internal.statistic.actions.scheme.AddGroupToTestSchemeAction) * * @see registerVarargEvent */ fun registerEvent(eventId: String): EventId { return EventId(this, eventId).also { addToRegisteredEvents(it) } } /** * See docs for com.intellij.internal.statistic.eventLog.EventLogGroup.registerEvent(java.lang.String) * * @see registerEvent * @see registerVarargEvent */ fun <T1> registerEvent(eventId: String, eventField1: EventField<T1>): EventId1<T1> { return EventId1(this, eventId, eventField1).also { addToRegisteredEvents(it) } } /** * See docs for com.intellij.internal.statistic.eventLog.EventLogGroup.registerEvent(java.lang.String) * * @see registerEvent * @see registerVarargEvent */ fun <T1, T2> registerEvent(eventId: String, eventField1: EventField<T1>, eventField2: EventField<T2>): EventId2<T1, T2> { return EventId2(this, eventId, eventField1, eventField2).also { addToRegisteredEvents(it) } } /** * See docs for com.intellij.internal.statistic.eventLog.EventLogGroup.registerEvent(java.lang.String) * * @see registerEvent * @see registerVarargEvent */ fun <T1, T2, T3> registerEvent(eventId: String, eventField1: EventField<T1>, eventField2: EventField<T2>, eventField3: EventField<T3>): EventId3<T1, T2, T3> { return EventId3(this, eventId, eventField1, eventField2, eventField3).also { addToRegisteredEvents(it) } } /** * See docs for com.intellij.internal.statistic.eventLog.EventLogGroup.registerEvent(java.lang.String) * * @see registerEvent */ fun registerVarargEvent(eventId: String, vararg fields: EventField<*>): VarargEventId { return VarargEventId(this, eventId, *fields).also { addToRegisteredEvents(it) } } @JvmOverloads fun registerIdeActivity(activityName: String?, startEventAdditionalFields: Array<EventField<*>> = emptyArray(), finishEventAdditionalFields: Array<EventField<*>> = emptyArray(), parentActivity: IdeActivityDefinition? = null): IdeActivityDefinition { return IdeActivityDefinition(this, parentActivity, activityName, startEventAdditionalFields, finishEventAdditionalFields) } internal fun validateEventId(eventId: String) { if (!isEventIdValid(eventId)) { throw IllegalArgumentException("Trying to report unregistered event ID $eventId to group $id") } } private fun isEventIdValid(eventId: String): Boolean { if (EventLogSystemEvents.SYSTEM_EVENTS.contains(eventId)) return true return registeredEventIds.isEmpty() || eventId in registeredEventIds } }
apache-2.0
d04717976aac82d8d0cd0b289fca1476
42.881188
160
0.733694
4.466734
false
false
false
false
FuturemanGaming/FutureBot-Discord
src/main/kotlin/com/futuremangaming/futurebot/internal/ReadExecPrintLoop.kt
1
4759
/* * Copyright 2014-2017 FuturemanGaming * * 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.futuremangaming.futurebot.internal import com.futuremangaming.futurebot.FutureBot import com.futuremangaming.futurebot.set import net.dv8tion.jda.core.JDA import net.dv8tion.jda.core.MessageBuilder import net.dv8tion.jda.core.events.Event import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent import net.dv8tion.jda.core.hooks.EventListener import java.io.Writer import javax.script.ScriptEngine import javax.script.ScriptEngineManager import javax.script.ScriptException class ReadExecPrintLoop( val channelId: Long, val userId: Long, val api: JDA, val bot: FutureBot) : EventListener { val engine: ScriptEngine by lazy { val e = ScriptEngineManager().getEngineByExtension("js") e.context.writer = ChannelWriter(api, channelId) e.context.errorWriter = ChannelWriter(api, channelId, true) e["bot"] = bot e["api"] = api e["writer"] = e.context.writer e.eval(""" imports = JavaImporter(java.lang, java.util, java.io, java.nio, Packages.net.dv8tion.jda.core, Packages.net.dv8tion.jda.core.utils, Packages.net.dv8tion.jda.core.entities, Packages.net.dv8tion.jda.core.requests, Packages.net.dv8tion.jda.core.managers) function log(s) { if (s == null) return; writer.append(s.toString()); writer.flush(); } """) return@lazy e } init { api.addEventListener(this) } override fun onEvent(event: Event) { if (event is GuildMessageReceivedEvent) { if (event.channel.idLong == channelId && event.author.idLong == userId) onMessage(event) } } fun onMessage(event: GuildMessageReceivedEvent) { val content = event.message.rawContent if (content.isNullOrEmpty()) return if (!content.startsWith("```")) return var code = content.substring(3, content.length - 3).trim() if (code.startsWith("js", true)) code = code.substring(2).trim() if (code.equals("exit", true)) { event.message.addReaction("👌🏻").queue() return api.removeEventListener(this) } engine["event"] = event engine["channel"] = event.channel engine["guild"] = event.guild engine["message"] = event.message engine["self"] = event.jda.selfUser engine["author"] = event.author try { engine.eval(code) } catch (ex: Exception) { if (ex !is ScriptException) ex.printStackTrace() else { val writer = engine.context.errorWriter writer.append(ex.cause.toString()) writer.flush() } } } } class ChannelWriter( val api: JDA, val channelId: Long, val error: Boolean = false) : Writer() { companion object { const val ERROR_2000 = "```diff\n- Output too large. See console.```" } var stringBuilder = StringBuilder() override fun write(cbuf: CharArray, off: Int, len: Int) { stringBuilder.append(String(cbuf, off, len)) if (stringBuilder.length > 1000) flush() } override fun flush() { if (stringBuilder.isEmpty()) return val msgBuilder = newBuilder() val string = stringBuilder.toString() val channel = api.getTextChannelById(channelId) stringBuilder = StringBuilder() if (string.length > 2000) { println("\nEVAL OUTPUT\n") println(string) println("\n=======\n") return channel?.sendMessage(ERROR_2000)?.queue() ?: Unit } msgBuilder.append(string).append("```") channel?.sendMessage(msgBuilder.build())?.queue() } override fun close() { } fun newBuilder(): MessageBuilder { val builder = MessageBuilder().append("```") if (error) builder.append("diff\n- Error -\n") return builder } }
apache-2.0
c975b9211f2cd2845b326ec954bc0c94
30.899329
83
0.607195
4.26278
false
false
false
false
ex3ndr/telegram-tl
Builder/src/org/telegram/tl/builder/JavaModel.kt
1
4532
package org.telegram.tl.builder import java.util.ArrayList import java.util.HashMap /** * Created with IntelliJ IDEA. * User: ex3ndr * Date: 23.10.13 * Time: 13:10 */ class JavaModel(var types: HashMap<String, JavaTypeObject>, var methods: List<JavaRpcMethod>) class JavaTypeObject(var tlType: TLCombinedTypeDef) { public val javaPackage: String = mapJavaPackage(tlType) public val javaTypeName: String = mapJavaTypeName(tlType) public val constructors: List<JavaTypeConstructor> = tlType.constructors.map {(x) -> JavaTypeConstructor(x, this) }; public val commonParameters: List<JavaParameter> { var parameters = ArrayList<JavaParameter>() if (!IgnoreUniting.any {(x) -> x == tlType.name }) { var baseConstructor = constructors.first!!; @outer for (p in baseConstructor.parameters) { var pName = p.tlParameterDef.name var pType = p.tlParameterDef.typeDef for (constr in constructors) { var hasParameter = false for (cP in constr.parameters) { var areSameType = cP.tlParameterDef.typeDef == pType; if (cP.tlParameterDef.name == pName && areSameType) { hasParameter = true; break; } } if (!hasParameter) { continue@outer } } parameters.add(p) } } commonParameters = parameters } } class JavaTypeConstructor(var tlConstructor: TLConstructorDef, javaType: JavaTypeObject) { public val javaClassName: String = mapJavaChildName(tlConstructor); public val parameters: List<JavaParameter> = tlConstructor.parameters.map {(x) -> JavaParameter(x) } } abstract class JavaTypeReference(var tlReference: TLTypeDef, var javaName: String) class JavaTypeTlReference(tlReference: TLTypeDef, var javaReference: JavaTypeObject) : JavaTypeReference(tlReference, javaReference.javaPackage + "." + javaReference.javaTypeName) class JavaTypeFunctionalReference(tlReference: TLTypeDef) : JavaTypeReference(tlReference, "TLMethod") class JavaTypeAnyReference(tlReference: TLTypeDef) : JavaTypeReference(tlReference, "TLObject") class JavaTypeUnknownReference(tlReference: TLTypeDef) : JavaTypeReference(tlReference, "???") class JavaTypeVectorReference(tlReference: TLTypeDef, var internalReference: JavaTypeReference) : JavaTypeReference(tlReference, when(internalReference) { is JavaTypeBuiltInReference -> { when (internalReference.javaName) { "int" -> JavaCorePackage + ".TLIntVector" "long" -> JavaCorePackage + ".TLLongVector" "String" -> JavaCorePackage + ".TLStringVector" else -> throw RuntimeException("Unsupported built in reference in vector: " + internalReference.javaName) } } is JavaTypeVectorReference -> JavaCorePackage + ".TLVector<" + internalReference.javaName + ">" is JavaTypeTlReference -> JavaCorePackage + ".TLVector<" + internalReference.javaName + ">" else -> throw RuntimeException("Unsupported reference in vector: " + internalReference.javaName) }) class JavaTypeBuiltInReference(tlReference: TLBuiltInTypeDef) : JavaTypeReference(tlReference, when(tlReference.name) { "int" -> "int" "long" -> "long" "double" -> "double" "string" -> "String" "bytes" -> "TLBytes" "Bool" -> "boolean" else -> throw RuntimeException("Unsupported built in reference: " + tlReference.name) }) class JavaParameter(var tlParameterDef: TLParameterDef) { public val internalName: String = mapVariableBaseName(tlParameterDef) public val getterName: String = "get" + internalName.uCamelCase(); public val setterName: String = "set" + internalName.uCamelCase(); public var reference: JavaTypeReference? = null; } class JavaRpcMethod(var tlMethod: TLMethodDef) { public val methodName: String = mapJavaMethodName(tlMethod) public val requestClassName: String = mapJavaMethodClassName(tlMethod) public var returnReference: JavaTypeReference? = null; public val parameters: List<JavaParameter> = tlMethod.args.map {(x) -> JavaParameter(x) } }
mit
1d2376266722fda1f011a627b9af6500
38.077586
125
0.640997
4.735632
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/suggested/KotlinSuggestedRefactoringUI.kt
1
2472
// 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.refactoring.suggested import com.intellij.psi.PsiCodeFragment import com.intellij.refactoring.suggested.SignaturePresentationBuilder import com.intellij.refactoring.suggested.SuggestedChangeSignatureData import com.intellij.refactoring.suggested.SuggestedRefactoringExecution.NewParameterValue import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Parameter import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Signature import com.intellij.refactoring.suggested.SuggestedRefactoringUI import org.jetbrains.kotlin.psi.KtExpressionCodeFragment import org.jetbrains.kotlin.psi.KtPsiFactory object KotlinSuggestedRefactoringUI : SuggestedRefactoringUI() { override fun createSignaturePresentationBuilder( signature: Signature, otherSignature: Signature, isOldSignature: Boolean ): SignaturePresentationBuilder { return KotlinSignaturePresentationBuilder(signature, otherSignature, isOldSignature) } override fun extractNewParameterData(data: SuggestedChangeSignatureData): List<NewParameterData> { val result = mutableListOf<NewParameterData>() val declaration = data.declaration val factory = KtPsiFactory(declaration.project) fun createCodeFragment() = factory.createExpressionCodeFragment("", declaration) if (data.newSignature.receiverType != null && data.oldSignature.receiverType == null) { result.add(NewParameterData("<receiver>", createCodeFragment(), false/*TODO*/)) } fun isNewParameter(parameter: Parameter) = data.oldSignature.parameterById(parameter.id) == null val newParameters = data.newSignature.parameters val dropLastN = newParameters.reversed().count { isNewParameter(it) && it.defaultValue != null } for (parameter in newParameters.dropLast(dropLastN)) { if (isNewParameter(parameter)) { result.add(NewParameterData(parameter.name, createCodeFragment(), false/*TODO*/)) } } return result } override fun extractValue(fragment: PsiCodeFragment): NewParameterValue.Expression? { return (fragment as KtExpressionCodeFragment).getContentElement() ?.let { NewParameterValue.Expression(it) } } }
apache-2.0
15a6e17b91457931f59d5383e2388ba9
46.538462
158
0.756472
5.362256
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/SimplifyBooleanWithConstantsIntention.kt
1
8982
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.tree.IElementType import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.copied import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isTrueConstant import org.jetbrains.kotlin.lexer.KtTokens.* import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.psi2ir.deparenthesize import org.jetbrains.kotlin.resolve.CompileTimeConstantUtils import org.jetbrains.kotlin.resolve.calls.callUtil.getType import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode.PARTIAL import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.isFlexible @Suppress("DEPRECATION") class SimplifyBooleanWithConstantsInspection : IntentionBasedInspection<KtBinaryExpression>(SimplifyBooleanWithConstantsIntention::class) { override fun inspectionProblemText(element: KtBinaryExpression): String { return KotlinBundle.message("inspection.simplify.boolean.with.constants.display.name") } } class SimplifyBooleanWithConstantsIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>( KtBinaryExpression::class.java, KotlinBundle.lazyMessage("simplify.boolean.expression") ) { override fun isApplicableTo(element: KtBinaryExpression): Boolean = areThereExpressionsToBeSimplified(element.topBinary()) private fun KtBinaryExpression.topBinary(): KtBinaryExpression = this.parentsWithSelf.takeWhile { it is KtBinaryExpression }.lastOrNull() as? KtBinaryExpression ?: this private fun areThereExpressionsToBeSimplified(element: KtExpression?): Boolean { if (element == null) return false when (element) { is KtParenthesizedExpression -> return areThereExpressionsToBeSimplified(element.expression) is KtBinaryExpression -> { val op = element.operationToken if (op == ANDAND || op == OROR || op == EQEQ || op == EXCLEQ) { if (areThereExpressionsToBeSimplified(element.left) && element.right.hasBooleanType()) return true if (areThereExpressionsToBeSimplified(element.right) && element.left.hasBooleanType()) return true } if (isPositiveNegativeZeroComparison(element)) return false } } return element.canBeReducedToBooleanConstant() } private fun isPositiveNegativeZeroComparison(element: KtBinaryExpression): Boolean { val op = element.operationToken if (op != EQEQ && op != EQEQEQ) { return false } val left = element.left?.deparenthesize() as? KtExpression ?: return false val right = element.right?.deparenthesize() as? KtExpression ?: return false val context = element.analyze(PARTIAL) fun KtExpression.getConstantValue() = ConstantExpressionEvaluator.getConstant(this, context)?.toConstantValue(TypeUtils.NO_EXPECTED_TYPE)?.value val leftValue = left.getConstantValue() val rightValue = right.getConstantValue() fun isPositiveZero(value: Any?) = value == +0.0 || value == +0.0f fun isNegativeZero(value: Any?) = value == -0.0 || value == -0.0f val hasPositiveZero = isPositiveZero(leftValue) || isPositiveZero(rightValue) val hasNegativeZero = isNegativeZero(leftValue) || isNegativeZero(rightValue) return hasPositiveZero && hasNegativeZero } override fun applyTo(element: KtBinaryExpression, editor: Editor?) { val topBinary = element.topBinary() val simplified = toSimplifiedExpression(topBinary) val result = topBinary.replaced(KtPsiUtil.safeDeparenthesize(simplified, true)) removeRedundantAssertion(result) } internal fun removeRedundantAssertion(expression: KtExpression) { val callExpression = expression.getNonStrictParentOfType<KtCallExpression>() ?: return val fqName = callExpression.getCallableDescriptor()?.fqNameOrNull() val valueArguments = callExpression.valueArguments val isRedundant = fqName?.asString() == "kotlin.assert" && valueArguments.singleOrNull()?.getArgumentExpression().isTrueConstant() if (isRedundant) callExpression.delete() } private fun toSimplifiedExpression(expression: KtExpression): KtExpression { val psiFactory = KtPsiFactory(expression) when { expression.canBeReducedToTrue() -> { return psiFactory.createExpression("true") } expression.canBeReducedToFalse() -> { return psiFactory.createExpression("false") } expression is KtParenthesizedExpression -> { val expr = expression.expression if (expr != null) { val simplified = toSimplifiedExpression(expr) return if (simplified is KtBinaryExpression) { // wrap in new parentheses to keep the user's original format psiFactory.createExpressionByPattern("($0)", simplified) } else { // if we now have a simpleName, constant, or parenthesized we don't need parentheses simplified } } } expression is KtBinaryExpression -> { if (!areThereExpressionsToBeSimplified(expression)) return expression.copied() val left = expression.left val right = expression.right val op = expression.operationToken if (left != null && right != null && (op == ANDAND || op == OROR || op == EQEQ || op == EXCLEQ)) { val simpleLeft = simplifyExpression(left) val simpleRight = simplifyExpression(right) return when { simpleLeft.canBeReducedToTrue() -> toSimplifiedBooleanBinaryExpressionWithConstantOperand(true, simpleRight, op) simpleLeft.canBeReducedToFalse() -> toSimplifiedBooleanBinaryExpressionWithConstantOperand(false, simpleRight, op) simpleRight.canBeReducedToTrue() -> toSimplifiedBooleanBinaryExpressionWithConstantOperand(true, simpleLeft, op) simpleRight.canBeReducedToFalse() -> toSimplifiedBooleanBinaryExpressionWithConstantOperand(false, simpleLeft, op) else -> { val opText = expression.operationReference.text psiFactory.createExpressionByPattern("$0 $opText $1", simpleLeft, simpleRight) } } } } } return expression.copied() } private fun toSimplifiedBooleanBinaryExpressionWithConstantOperand( constantOperand: Boolean, otherOperand: KtExpression, operation: IElementType ): KtExpression { val factory = KtPsiFactory(otherOperand) when (operation) { OROR -> { if (constantOperand) return factory.createExpression("true") } ANDAND -> { if (!constantOperand) return factory.createExpression("false") } EQEQ, EXCLEQ -> toSimplifiedExpression(otherOperand).let { return if (constantOperand == (operation == EQEQ)) it else factory.createExpressionByPattern("!$0", it) } } return toSimplifiedExpression(otherOperand) } private fun simplifyExpression(expression: KtExpression) = expression.replaced(toSimplifiedExpression(expression)) private fun KtExpression?.hasBooleanType(): Boolean { val type = this?.getType(this.analyze(PARTIAL)) ?: return false return KotlinBuiltIns.isBoolean(type) && !type.isFlexible() } private fun KtExpression.canBeReducedToBooleanConstant(constant: Boolean? = null): Boolean = CompileTimeConstantUtils.canBeReducedToBooleanConstant(this, this.analyze(PARTIAL), constant) private fun KtExpression.canBeReducedToTrue() = canBeReducedToBooleanConstant(true) private fun KtExpression.canBeReducedToFalse() = canBeReducedToBooleanConstant(false) }
apache-2.0
2dea57710e23d4a9c30cb17dc733db67
45.298969
158
0.677355
5.761386
false
false
false
false
jwren/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/ScriptNewDependenciesNotification.kt
2
4408
// 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.core.script import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.Ref import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.HyperlinkLabel import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings import org.jetbrains.kotlin.idea.core.util.KotlinIdeaCoreBundle import org.jetbrains.kotlin.psi.UserDataProperty import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper fun VirtualFile.removeScriptDependenciesNotificationPanel(project: Project) { withSelectedEditor(project) { manager -> notificationPanel?.let { manager.removeTopComponent(this, it) } notificationPanel = null } } fun VirtualFile.addScriptDependenciesNotificationPanel( compilationConfigurationResult: ScriptCompilationConfigurationWrapper, project: Project, onClick: () -> Unit ) { withSelectedEditor(project) { manager -> val existingPanel = notificationPanel if (existingPanel != null) { if (existingPanel.compilationConfigurationResult == compilationConfigurationResult) { return@withSelectedEditor } notificationPanel?.let { manager.removeTopComponent(this, it) } } val panel = NewScriptDependenciesNotificationPanel(onClick, compilationConfigurationResult, project, this@addScriptDependenciesNotificationPanel) notificationPanel = panel manager.addTopComponent(this, panel) } } @TestOnly fun VirtualFile.hasSuggestedScriptConfiguration(project: Project): Boolean { return FileEditorManager.getInstance(project).getSelectedEditor(this)?.notificationPanel != null } @TestOnly fun VirtualFile.applySuggestedScriptConfiguration(project: Project): Boolean { val notificationPanel = FileEditorManager.getInstance(project).getSelectedEditor(this)?.notificationPanel ?: return false notificationPanel.onClick.invoke() return true } private fun VirtualFile.withSelectedEditor(project: Project, f: FileEditor.(FileEditorManager) -> Unit) { ApplicationManager.getApplication().invokeLater { if (project.isDisposed) return@invokeLater val fileEditorManager = FileEditorManager.getInstance(project) (fileEditorManager.getSelectedEditor(this))?.let { f(it, fileEditorManager) } } } private var FileEditor.notificationPanel: NewScriptDependenciesNotificationPanel? by UserDataProperty<FileEditor, NewScriptDependenciesNotificationPanel>(Key.create("script.dependencies.panel")) private class NewScriptDependenciesNotificationPanel( val onClick: () -> Unit, val compilationConfigurationResult: ScriptCompilationConfigurationWrapper, project: Project, file: VirtualFile ) : EditorNotificationPanel() { init { setText(KotlinIdeaCoreBundle.message("notification.text.there.is.a.new.script.context.available")) createComponentActionLabel(KotlinIdeaCoreBundle.message("notification.action.text.apply.context")) { onClick() } createComponentActionLabel(KotlinIdeaCoreBundle.message("notification.action.text.enable.auto.reload")) { onClick() val scriptDefinition = file.findScriptDefinition(project) ?: return@createComponentActionLabel KotlinScriptingSettings.getInstance(project).setAutoReloadConfigurations(scriptDefinition, true) } } private fun EditorNotificationPanel.createComponentActionLabel(@NlsContexts.LinkLabel labelText: String, callback: (HyperlinkLabel) -> Unit) { val label: Ref<HyperlinkLabel> = Ref.create() val action = Runnable { callback(label.get()) } label.set(createActionLabel(labelText, action)) } }
apache-2.0
236831f66369fed25feabb9b669b0d3d
39.814815
194
0.756806
5.298077
false
true
false
false
jwren/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/references/KotlinWebReferenceContributor.kt
4
2689
// 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.references import com.intellij.openapi.paths.GlobalPathReferenceProvider import com.intellij.openapi.paths.WebReference import com.intellij.openapi.util.TextRange import com.intellij.patterns.PlatformPatterns.psiElement import com.intellij.psi.* import com.intellij.util.ProcessingContext import com.intellij.util.SmartList import org.jetbrains.kotlin.psi.KtStringTemplateExpression internal class KotlinWebReferenceContributor : PsiReferenceContributor() { private val spaceSymbolsSplitter: Regex = Regex("\\s") override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) { // see org.jetbrains.kotlin.idea.references.KtIdeReferenceProviderService.getReferences // ContributedReferenceHost elements are not queried for Kotlin-specific references, contribute using PsiReferenceRegistrar registrar.registerReferenceProvider( psiElement(KtStringTemplateExpression::class.java), object : PsiReferenceProvider() { override fun acceptsTarget(target: PsiElement): Boolean { return false // web references do not point to any real PsiElement } override fun getReferencesByElement( element: PsiElement, context: ProcessingContext ): Array<PsiReference> { val stringTemplateExpression = element as? KtStringTemplateExpression ?: return PsiReference.EMPTY_ARRAY if (!stringTemplateExpression.textContains(':')) { return PsiReference.EMPTY_ARRAY } val results = SmartList<PsiReference>() for (entry in stringTemplateExpression.entries) { if (entry.expression != null) continue val texts = entry.text.split(spaceSymbolsSplitter) var startIndex = entry.startOffsetInParent for (text in texts) { if (text.isNotEmpty() && GlobalPathReferenceProvider.isWebReferenceUrl(text)) { results.add(WebReference(stringTemplateExpression, TextRange(startIndex, startIndex + text.length), text)) } startIndex += text.length + 1 } } return results.toArray(PsiReference.EMPTY_ARRAY) } }) } }
apache-2.0
ae1e7144fea7a14d84f40bb1f596732f
48.814815
158
0.63518
6.002232
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/equalsOrHashCode/hashCodeInChildClass.kt
1
283
open class Base<T>(t: T) { override fun hashCode(): Int = 0 override fun equals(foo: Any?) = false } class With<caret>Constructor(x: Int, s: String) : Base<Int>(3) { val x: Int = 0 val s: String = "" override fun equals(foo: Any?): Boolean = super.equals(foo) }
apache-2.0
64906c705d78c7c4c495862ce4f3a860
24.818182
64
0.611307
3.144444
false
false
false
false
androidx/androidx
compose/integration-tests/docs-snippets/src/main/java/androidx/compose/integration/docs/animation/Animation.kt
3
28741
/* * 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. */ // Ignore lint warnings in documentation snippets @file:Suppress( "CanBeVal", "UNUSED_VARIABLE", "RemoveExplicitTypeArguments", "unused", "MemberVisibilityCanBePrivate", "TransitionPropertiesLabel", "UpdateTransitionLabel", "UNUSED_PARAMETER" ) @file:SuppressLint("ModifierInspectorInfo", "NewApi") package androidx.compose.integration.docs.animation import android.annotation.SuppressLint import androidx.compose.animation.Animatable import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.Crossfade import androidx.compose.animation.EnterExitState import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.SizeTransform import androidx.compose.animation.animateColor import androidx.compose.animation.animateColorAsState import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.AnimationVector1D import androidx.compose.animation.core.AnimationVector2D import androidx.compose.animation.core.Easing import androidx.compose.animation.core.ExperimentalTransitionApi import androidx.compose.animation.core.FastOutLinearInEasing import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.Spring import androidx.compose.animation.core.TargetBasedAnimation import androidx.compose.animation.core.Transition import androidx.compose.animation.core.TwoWayConverter import androidx.compose.animation.core.VectorConverter import androidx.compose.animation.core.animateDp import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.animateRect import androidx.compose.animation.core.animateValueAsState import androidx.compose.animation.core.calculateTargetValue import androidx.compose.animation.core.createChildTransition import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.keyframes import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.repeatable import androidx.compose.animation.core.snap import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.animation.core.updateTransition import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkVertically import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.animation.splineBasedDecay import androidx.compose.animation.with import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.horizontalDrag import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.integration.docs.animation.UpdateTransitionEnumState.BoxState import androidx.compose.material.Button import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Phone import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.runtime.withFrameNanos import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.positionChange import androidx.compose.ui.input.pointer.util.VelocityTracker import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onRoot import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import org.junit.Rule import org.junit.Test import kotlin.math.absoluteValue import kotlin.math.roundToInt /** * This file lets DevRel track changes to snippets present in * https://developer.android.com/jetpack/compose/animation * * No action required if it's modified. */ @OptIn(ExperimentalAnimationApi::class) @Composable private fun AnimatedVisibilitySimple() { var editable by remember { mutableStateOf(true) } AnimatedVisibility(visible = editable) { Text(text = "Edit") } } @OptIn(ExperimentalAnimationApi::class) @Composable private fun AnimatedVisibilityWithEnterAndExit() { var visible by remember { mutableStateOf(true) } val density = LocalDensity.current AnimatedVisibility( visible = visible, enter = slideInVertically { // Slide in from 40 dp from the top. with(density) { -40.dp.roundToPx() } } + expandVertically( // Expand from the top. expandFrom = Alignment.Top ) + fadeIn( // Fade in with the initial alpha of 0.3f. initialAlpha = 0.3f ), exit = slideOutVertically() + shrinkVertically() + fadeOut() ) { Text("Hello", Modifier.fillMaxWidth().height(200.dp)) } } @OptIn(ExperimentalAnimationApi::class, ExperimentalTransitionApi::class) @Composable private fun AnimatedVisibilityMutable() { // Create a MutableTransitionState<Boolean> for the AnimatedVisibility. val state = remember { MutableTransitionState(false).apply { // Start the animation immediately. targetState = true } } Column { AnimatedVisibility(visibleState = state) { Text(text = "Hello, world!") } // Use the MutableTransitionState to know the current animation state // of the AnimatedVisibility. Text( text = when { state.isIdle && state.currentState -> "Visible" !state.isIdle && state.currentState -> "Disappearing" state.isIdle && !state.currentState -> "Invisible" else -> "Appearing" } ) } } @OptIn(ExperimentalAnimationApi::class) @Composable private fun AnimatedVisibilityAnimateEnterExit(visible: Boolean) { AnimatedVisibility( visible = visible, enter = fadeIn(), exit = fadeOut() ) { // Fade in/out the background and the foreground. Box(Modifier.fillMaxSize().background(Color.DarkGray)) { Box( Modifier .align(Alignment.Center) .animateEnterExit( // Slide in/out the inner box. enter = slideInVertically(), exit = slideOutVertically() ) .sizeIn(minWidth = 256.dp, minHeight = 64.dp) .background(Color.Red) ) { // Content of the notification… } } } } @OptIn(ExperimentalAnimationApi::class) @Composable private fun AnimatedVisibilityTransition(visible: Boolean) { AnimatedVisibility( visible = visible, enter = fadeIn(), exit = fadeOut() ) { // this: AnimatedVisibilityScope // Use AnimatedVisibilityScope#transition to add a custom animation // to the AnimatedVisibility. val background by transition.animateColor { state -> if (state == EnterExitState.Visible) Color.Blue else Color.Gray } Box(modifier = Modifier.size(128.dp).background(background)) } } @OptIn(ExperimentalAnimationApi::class) @Composable private fun AnimatedContentSimple() { Row { var count by remember { mutableStateOf(0) } Button(onClick = { count++ }) { Text("Add") } AnimatedContent(targetState = count) { targetCount -> // Make sure to use `targetCount`, not `count`. Text(text = "Count: $targetCount") } } } @OptIn(ExperimentalAnimationApi::class) @Composable private fun AnimatedContentTransitionSpec(count: Int) { AnimatedContent( targetState = count, transitionSpec = { // Compare the incoming number with the previous number. if (targetState > initialState) { // If the target number is larger, it slides up and fades in // while the initial (smaller) number slides up and fades out. slideInVertically { height -> height } + fadeIn() with slideOutVertically { height -> -height } + fadeOut() } else { // If the target number is smaller, it slides down and fades in // while the initial number slides down and fades out. slideInVertically { height -> -height } + fadeIn() with slideOutVertically { height -> height } + fadeOut() }.using( // Disable clipping since the faded slide-in/out should // be displayed out of bounds. SizeTransform(clip = false) ) } ) { targetCount -> Text(text = "$targetCount") } } @OptIn(ExperimentalAnimationApi::class, ExperimentalMaterialApi::class) @Composable private fun AnimatedContentSizeTransform() { var expanded by remember { mutableStateOf(false) } Surface( color = MaterialTheme.colors.primary, onClick = { expanded = !expanded } ) { AnimatedContent( targetState = expanded, transitionSpec = { fadeIn(animationSpec = tween(150, 150)) with fadeOut(animationSpec = tween(150)) using SizeTransform { initialSize, targetSize -> if (targetState) { keyframes { // Expand horizontally first. IntSize(targetSize.width, initialSize.height) at 150 durationMillis = 300 } } else { keyframes { // Shrink vertically first. IntSize(initialSize.width, targetSize.height) at 150 durationMillis = 300 } } } } ) { targetExpanded -> if (targetExpanded) { Expanded() } else { ContentIcon() } } } } @Composable private fun AnimateContentSizeSimple() { var message by remember { mutableStateOf("Hello") } Box( modifier = Modifier.background(Color.Blue).animateContentSize() ) { Text(text = message) } } @Composable private fun CrossfadeSimple() { var currentPage by remember { mutableStateOf("A") } Crossfade(targetState = currentPage) { screen -> when (screen) { "A" -> Text("Page A") "B" -> Text("Page B") } } } @Composable private fun AnimateAsStateSimple(enabled: Boolean) { val alpha: Float by animateFloatAsState(if (enabled) 1f else 0.5f) Box( Modifier.fillMaxSize() .graphicsLayer(alpha = alpha) .background(Color.Red) ) } @Composable private fun AnimatableSimple(ok: Boolean) { // Start out gray and animate to green/red based on `ok` val color = remember { Animatable(Color.Gray) } LaunchedEffect(ok) { color.animateTo(if (ok) Color.Green else Color.Red) } Box(Modifier.fillMaxSize().background(color.value)) } private object UpdateTransitionEnumState { enum class BoxState { Collapsed, Expanded } } @Composable private fun UpdateTransitionInstance() { var currentState by remember { mutableStateOf(BoxState.Collapsed) } val transition = updateTransition(currentState) } @Composable private fun UpdateTransitionAnimationValues(transition: Transition<BoxState>) { val rect by transition.animateRect { state -> when (state) { BoxState.Collapsed -> Rect(0f, 0f, 100f, 100f) BoxState.Expanded -> Rect(100f, 100f, 300f, 300f) } } val borderWidth by transition.animateDp { state -> when (state) { BoxState.Collapsed -> 1.dp BoxState.Expanded -> 0.dp } } } @Composable private fun UpdateTransitionTransitionSpec(transition: Transition<BoxState>) { val color by transition.animateColor( transitionSpec = { when { BoxState.Expanded isTransitioningTo BoxState.Collapsed -> spring(stiffness = 50f) else -> tween(durationMillis = 500) } } ) { state -> when (state) { BoxState.Collapsed -> MaterialTheme.colors.primary BoxState.Expanded -> MaterialTheme.colors.background } } } @Composable private fun UpdateTransitionMutableTransitionState() { // Start in collapsed state and immediately animate to expanded var currentState = remember { MutableTransitionState(BoxState.Collapsed) } currentState.targetState = BoxState.Expanded val transition = updateTransition(currentState) // …… } @OptIn(ExperimentalTransitionApi::class) private object UpdateTransitionCreateChildTransition { enum class DialerState { DialerMinimized, NumberPad } @Composable fun DialerButton(isVisibleTransition: Transition<Boolean>) { // `isVisibleTransition` spares the need for the content to know // about other DialerStates. Instead, the content can focus on // animating the state change between visible and not visible. } @Composable fun NumberPad(isVisibleTransition: Transition<Boolean>) { // `isVisibleTransition` spares the need for the content to know // about other DialerStates. Instead, the content can focus on // animating the state change between visible and not visible. } @Composable fun Dialer(dialerState: DialerState) { val transition = updateTransition(dialerState) Box { // Creates separate child transitions of Boolean type for NumberPad // and DialerButton for any content animation between visible and // not visible NumberPad( transition.createChildTransition { it == DialerState.NumberPad } ) DialerButton( transition.createChildTransition { it == DialerState.DialerMinimized } ) } } } @OptIn(ExperimentalAnimationApi::class, ExperimentalMaterialApi::class) @Composable private fun UpdateTransitionAnimatedVisibility() { var selected by remember { mutableStateOf(false) } // Animates changes when `selected` is changed. val transition = updateTransition(selected) val borderColor by transition.animateColor { isSelected -> if (isSelected) Color.Magenta else Color.White } val elevation by transition.animateDp { isSelected -> if (isSelected) 10.dp else 2.dp } Surface( onClick = { selected = !selected }, shape = RoundedCornerShape(8.dp), border = BorderStroke(2.dp, borderColor), elevation = elevation ) { Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) { Text(text = "Hello, world!") // AnimatedVisibility as a part of the transition. transition.AnimatedVisibility( visible = { targetSelected -> targetSelected }, enter = expandVertically(), exit = shrinkVertically() ) { Text(text = "It is fine today.") } // AnimatedContent as a part of the transition. transition.AnimatedContent { targetState -> if (targetState) { Text(text = "Selected") } else { Icon(imageVector = Icons.Default.Phone, contentDescription = "Phone") } } } } } private object UpdateTransitionEncapsulating { enum class BoxState { Collapsed, Expanded } @Composable fun AnimatingBox(boxState: BoxState) { val transitionData = updateTransitionData(boxState) // UI tree Box( modifier = Modifier .background(transitionData.color) .size(transitionData.size) ) } // Holds the animation values. private class TransitionData( color: State<Color>, size: State<Dp> ) { val color by color val size by size } // Create a Transition and return its animation values. @Composable private fun updateTransitionData(boxState: BoxState): TransitionData { val transition = updateTransition(boxState) val color = transition.animateColor { state -> when (state) { BoxState.Collapsed -> Color.Gray BoxState.Expanded -> Color.Red } } val size = transition.animateDp { state -> when (state) { BoxState.Collapsed -> 64.dp BoxState.Expanded -> 128.dp } } return remember(transition) { TransitionData(color, size) } } } @Composable private fun RememberInfiniteTransitionSimple() { val infiniteTransition = rememberInfiniteTransition() val color by infiniteTransition.animateColor( initialValue = Color.Red, targetValue = Color.Green, animationSpec = infiniteRepeatable( animation = tween(1000, easing = LinearEasing), repeatMode = RepeatMode.Reverse ) ) Box(Modifier.fillMaxSize().background(color)) } @Composable private fun TargetBasedAnimationSimple(someCustomCondition: () -> Boolean) { val anim = remember { TargetBasedAnimation( animationSpec = tween(200), typeConverter = Float.VectorConverter, initialValue = 200f, targetValue = 1000f ) } var playTime by remember { mutableStateOf(0L) } LaunchedEffect(anim) { val startTime = withFrameNanos { it } do { playTime = withFrameNanos { it } - startTime val animationValue = anim.getValueFromNanos(playTime) } while (someCustomCondition()) } } @Composable private fun AnimationSpecTween(enabled: Boolean) { val alpha: Float by animateFloatAsState( targetValue = if (enabled) 1f else 0.5f, // Configure the animation duration and easing. animationSpec = tween(durationMillis = 300, easing = FastOutSlowInEasing) ) } @Composable private fun AnimationSpecSpring() { val value by animateFloatAsState( targetValue = 1f, animationSpec = spring( dampingRatio = Spring.DampingRatioHighBouncy, stiffness = Spring.StiffnessMedium ) ) } @Composable private fun AnimationSpecTween() { val value by animateFloatAsState( targetValue = 1f, animationSpec = tween( durationMillis = 300, delayMillis = 50, easing = LinearOutSlowInEasing ) ) } @Composable private fun AnimationSpecKeyframe() { val value by animateFloatAsState( targetValue = 1f, animationSpec = keyframes { durationMillis = 375 0.0f at 0 with LinearOutSlowInEasing // for 0-15 ms 0.2f at 15 with FastOutLinearInEasing // for 15-75 ms 0.4f at 75 // ms 0.4f at 225 // ms } ) } @Composable private fun AnimationSpecRepeatable() { val value by animateFloatAsState( targetValue = 1f, animationSpec = repeatable( iterations = 3, animation = tween(durationMillis = 300), repeatMode = RepeatMode.Reverse ) ) } @Composable private fun AnimationSpecInfiniteRepeatable() { val value by animateFloatAsState( targetValue = 1f, animationSpec = infiniteRepeatable( animation = tween(durationMillis = 300), repeatMode = RepeatMode.Reverse ) ) } @Composable private fun AnimationSpecSnap() { val value by animateFloatAsState( targetValue = 1f, animationSpec = snap(delayMillis = 50) ) } private object Easing { val CustomEasing = Easing { fraction -> fraction * fraction } @Composable fun EasingUsage() { val value by animateFloatAsState( targetValue = 1f, animationSpec = tween( durationMillis = 300, easing = CustomEasing ) ) // …… } } private object AnimationVectorTwoWayConverter { val IntToVector: TwoWayConverter<Int, AnimationVector1D> = TwoWayConverter({ AnimationVector1D(it.toFloat()) }, { it.value.toInt() }) } private object AnimationVectorCustomType { data class MySize(val width: Dp, val height: Dp) @Composable fun MyAnimation(targetSize: MySize) { val animSize: MySize by animateValueAsState<MySize, AnimationVector2D>( targetSize, TwoWayConverter( convertToVector = { size: MySize -> // Extract a float value from each of the `Dp` fields. AnimationVector2D(size.width.value, size.height.value) }, convertFromVector = { vector: AnimationVector2D -> MySize(vector.v1.dp, vector.v2.dp) } ) ) } } private object GestureAndAnimationSimple { @Composable fun Gesture() { val offset = remember { Animatable(Offset(0f, 0f), Offset.VectorConverter) } Box( modifier = Modifier .fillMaxSize() .pointerInput(Unit) { coroutineScope { while (true) { // Detect a tap event and obtain its position. awaitPointerEventScope { val position = awaitFirstDown().position launch { // Animate to the tap position. offset.animateTo(position) } } } } } ) { Circle(modifier = Modifier.offset { offset.value.toIntOffset() }) } } private fun Offset.toIntOffset() = IntOffset(x.roundToInt(), y.roundToInt()) } private object GestureAndAnimationSwipeToDismiss { fun Modifier.swipeToDismiss( onDismissed: () -> Unit ): Modifier = composed { val offsetX = remember { Animatable(0f) } pointerInput(Unit) { // Used to calculate fling decay. val decay = splineBasedDecay<Float>(this) // Use suspend functions for touch events and the Animatable. coroutineScope { while (true) { val velocityTracker = VelocityTracker() // Stop any ongoing animation. offsetX.stop() awaitPointerEventScope { // Detect a touch down event. val pointerId = awaitFirstDown().id horizontalDrag(pointerId) { change -> // Update the animation value with touch events. launch { offsetX.snapTo( offsetX.value + change.positionChange().x ) } velocityTracker.addPosition( change.uptimeMillis, change.position ) } } // No longer receiving touch events. Prepare the animation. val velocity = velocityTracker.calculateVelocity().x val targetOffsetX = decay.calculateTargetValue( offsetX.value, velocity ) // The animation stops when it reaches the bounds. offsetX.updateBounds( lowerBound = -size.width.toFloat(), upperBound = size.width.toFloat() ) launch { if (targetOffsetX.absoluteValue <= size.width) { // Not enough velocity; Slide back. offsetX.animateTo( targetValue = 0f, initialVelocity = velocity ) } else { // The element was swiped away. offsetX.animateDecay(velocity, decay) onDismissed() } } } } } .offset { IntOffset(offsetX.value.roundToInt(), 0) } } } private object Testing { @get:Rule val rule = createComposeRule() @Test fun testAnimationWithClock() { // Pause animations rule.mainClock.autoAdvance = false var enabled by mutableStateOf(false) rule.setContent { val color by animateColorAsState( targetValue = if (enabled) Color.Red else Color.Green, animationSpec = tween(durationMillis = 250) ) Box(Modifier.size(64.dp).background(color)) } // Initiate the animation. enabled = true // Let the animation proceed. rule.mainClock.advanceTimeBy(50L) // Compare the result with the image showing the expected result. // `assertAgainGolden` needs to be implemented in your code. rule.onRoot().captureToImage().assertAgainstGolden() } } /* Fakes needed for snippets to build: */ private fun ImageBitmap.assertAgainstGolden() { } @Composable private fun Circle(modifier: Modifier = Modifier) { } @Composable private fun Expanded() { } @Composable private fun ContentIcon() { }
apache-2.0
8b32de648e5b2239ae72010f861c9fb1
33.162901
89
0.625944
5.081535
false
false
false
false
stoyicker/dinger
data/src/main/kotlin/data/autoswipe/FromRateLimitedPostAutoSwipeAction.kt
1
920
package data.autoswipe import domain.autoswipe.FromRateLimitedPostAutoSwipeUseCase import domain.interactor.DisposableUseCase import io.reactivex.observers.DisposableCompletableObserver import io.reactivex.schedulers.Schedulers internal class FromRateLimitedPostAutoSwipeAction(private val notBeforeMillis: Long) : AutoSwipeIntentService.Action<Unit>() { private var useCaseDelegate: DisposableUseCase? = null override fun execute(owner: AutoSwipeIntentService, callback: Unit) = FromRateLimitedPostAutoSwipeUseCase(owner, Schedulers.trampoline(), notBeforeMillis).let { useCaseDelegate = it it.execute(object : DisposableCompletableObserver() { override fun onComplete() = commonDelegate.onComplete(owner) override fun onError(error: Throwable) = commonDelegate.onError(error, owner) }) } override fun dispose() { useCaseDelegate?.dispose() } }
mit
d002da655f7e2f5e7b1f69f90ce85194
37.333333
96
0.771739
5.054945
false
false
false
false
MoonlightOwl/Yui
src/main/kotlin/totoro/yui/actions/QuoteAction.kt
1
3864
package totoro.yui.actions import totoro.yui.client.Command import totoro.yui.client.IRCClient import totoro.yui.db.Database import totoro.yui.db.Quote import totoro.yui.util.Dict import totoro.yui.util.F import totoro.yui.util.LimitedHashMap import totoro.yui.util.LimitedList class QuoteAction(private val database: Database) : SensitivityAction("q", "quote", "mq", "multiquote"), MessageAction { companion object { private var action: QuoteAction? = null fun instance(database: Database): QuoteAction { if (action == null) action = QuoteAction(database) return action!! } } private val unfinishedQuotesLimit = 10 private val quoteLengthLimit = 100 private val outputLinesLimit = 5 private val unfinished = LimitedHashMap<String, LimitedList<String>>(unfinishedQuotesLimit) override fun handle(client: IRCClient, command: Command): Boolean { if (command.name == "q" || command.name == "quote") { // process one-line quotes and quote requests if (command.args.isNotEmpty()) { // if this is a new quote - write it to the database save(client, command.chan, Quote(0, command.args.joinToString(" "))) } else { // else - read a random quote from the database val quote = database.quotes?.random() if (quote != null) { val numberOfLines = quote.text.count { it == '\n' } + 1 val id = quote.id.toString() var lines = quote.text.split('\n').toMutableList() if (numberOfLines > 1) { val tab = " ".repeat((id.length + 3)) lines = lines.mapIndexed { index, s -> if (index > 0) tab + s else s }.toMutableList() if (numberOfLines > outputLinesLimit) { lines = (lines.take(outputLinesLimit - 1) + (tab + "... (https://quotes.fomalhaut.me/quote/${quote.id})")).toMutableList() } } lines[0] = "${F.Yellow}#$id${F.Reset}: ${lines[0]}" client.sendMultiline(command.chan, lines) } else { client.send(command.chan, "no quotes today " + Dict.Kawaii()) } } } else { // process multi-line quotes creation requests if (unfinished.containsKey(command.user)) { // finish this multiline quote save(client, command.chan, Quote(0, unfinished[command.user]!!.joinToString("\n"))) unfinished.remove(command.user) } else { // begin a new multiline quote unfinished[command.user] = LimitedList(quoteLengthLimit) client.send(command.chan, "enter your quote line by line and then finish it with another ~mq command") } } return true } override fun process(client: IRCClient, channel: String, user: String, message: String): String? { // check if there are any unfinished quotes return if (unfinished.size > 0 && unfinished.containsKey(user)) { // and then add a new line to the quote unfinished[user]!!.add(message) null } else message } private fun save(client: IRCClient, channel: String, quote: Quote) { if (quote.text.isNotBlank()) { val index = database.quotes?.add(quote) val text = index?.let { "i'll remember this" } ?: "something went wrong with my storage "+Dict.Upset() client.send(channel, text) } else { client.send(channel, "${F.Gray}you really need to spice up this quote${F.Reset}") } } }
mit
919bfc460cd1a2ae9c3aeaff0b628972
42.909091
120
0.561594
4.529894
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/avatar/photo/PhotoEditorFragment.kt
1
2853
package org.thoughtcrime.securesms.avatar.photo import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.commit import androidx.fragment.app.setFragmentResult import androidx.navigation.Navigation import org.signal.core.util.ThreadUtil import org.signal.core.util.concurrent.SignalExecutors import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.avatar.AvatarBundler import org.thoughtcrime.securesms.avatar.AvatarPickerStorage import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.providers.BlobProvider import org.thoughtcrime.securesms.scribbles.ImageEditorFragment class PhotoEditorFragment : Fragment(R.layout.avatar_photo_editor_fragment), ImageEditorFragment.Controller { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val args = PhotoEditorFragmentArgs.fromBundle(requireArguments()) val photo = AvatarBundler.extractPhoto(args.photoAvatar) val imageEditorFragment = ImageEditorFragment.newInstanceForAvatarEdit(photo.uri) childFragmentManager.commit { add(R.id.fragment_container, imageEditorFragment, IMAGE_EDITOR) } } override fun onTouchEventsNeeded(needed: Boolean) { } override fun onRequestFullScreen(fullScreen: Boolean, hideKeyboard: Boolean) { } override fun onDoneEditing() { val args = PhotoEditorFragmentArgs.fromBundle(requireArguments()) val applicationContext = requireContext().applicationContext val imageEditorFragment: ImageEditorFragment = childFragmentManager.findFragmentByTag(IMAGE_EDITOR) as ImageEditorFragment SignalExecutors.BOUNDED.execute { val editedImageUri = imageEditorFragment.renderToSingleUseBlob() val size = BlobProvider.getFileSize(editedImageUri) ?: 0 val inputStream = BlobProvider.getInstance().getStream(applicationContext, editedImageUri) val onDiskUri = AvatarPickerStorage.save(applicationContext, inputStream) val photo = AvatarBundler.extractPhoto(args.photoAvatar) val database = SignalDatabase.avatarPicker val newPhoto = photo.copy(uri = onDiskUri, size = size) database.update(newPhoto) BlobProvider.getInstance().delete(requireContext(), photo.uri) ThreadUtil.runOnMain { setFragmentResult(REQUEST_KEY_EDIT, AvatarBundler.bundlePhoto(newPhoto)) Navigation.findNavController(requireView()).popBackStack() } } } override fun onCancelEditing() { Navigation.findNavController(requireView()).popBackStack() } override fun restoreState() { } override fun onMainImageLoaded() { } override fun onMainImageFailedToLoad() { } companion object { const val REQUEST_KEY_EDIT = "org.thoughtcrime.securesms.avatar.photo.EDIT" private const val IMAGE_EDITOR = "image_editor" } }
gpl-3.0
9be185e9b2cb28965cf86e157d803272
35.576923
126
0.783386
4.778894
false
false
false
false
androidx/androidx
navigation/navigation-common/src/main/java/androidx/navigation/NavDestinationBuilder.kt
3
8400
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation import androidx.annotation.IdRes import androidx.core.os.bundleOf @DslMarker public annotation class NavDestinationDsl /** * DSL for constructing a new [NavDestination] */ @NavDestinationDsl public open class NavDestinationBuilder<out D : NavDestination> internal constructor( /** * The navigator the destination was created from */ protected val navigator: Navigator<out D>, /** * The destination's unique ID. */ @IdRes public val id: Int, /** * The destination's unique route. */ public val route: String? ) { /** * DSL for constructing a new [NavDestination] with a unique id. * * This sets the destination's [route] to `null`. * * @param navigator navigator used to create the destination * @param id the destination's unique id * * @return the newly constructed [NavDestination] */ @Deprecated( "Use routes to build your NavDestination instead", ReplaceWith("NavDestinationBuilder(navigator, route = id.toString())") ) public constructor(navigator: Navigator<out D>, @IdRes id: Int) : this(navigator, id, null) /** * DSL for constructing a new [NavDestination] with a unique route. * * This will also update the [id] of the destination based on route. * * @param navigator navigator used to create the destination * @param route the destination's unique route * * @return the newly constructed [NavDestination] */ public constructor(navigator: Navigator<out D>, route: String?) : this(navigator, -1, route) /** * The descriptive label of the destination */ public var label: CharSequence? = null private var arguments = mutableMapOf<String, NavArgument>() /** * Add a [NavArgument] to this destination. */ public fun argument(name: String, argumentBuilder: NavArgumentBuilder.() -> Unit) { arguments[name] = NavArgumentBuilder().apply(argumentBuilder).build() } private var deepLinks = mutableListOf<NavDeepLink>() /** * Add a deep link to this destination. * * In addition to a direct Uri match, the following features are supported: * * * Uris without a scheme are assumed as http and https. For example, * `www.example.com` will match `http://www.example.com` and * `https://www.example.com`. * * Placeholders in the form of `{placeholder_name}` matches 1 or more * characters. The String value of the placeholder will be available in the arguments * [Bundle] with a key of the same name. For example, * `http://www.example.com/users/{id}` will match * `http://www.example.com/users/4`. * * The `.*` wildcard can be used to match 0 or more characters. * * @param uriPattern The uri pattern to add as a deep link * @see deepLink */ public fun deepLink(uriPattern: String) { deepLinks.add(NavDeepLink(uriPattern)) } /** * Add a deep link to this destination. * * In addition to a direct Uri match, the following features are supported: * * * Uris without a scheme are assumed as http and https. For example, * `www.example.com` will match `http://www.example.com` and * `https://www.example.com`. * * Placeholders in the form of `{placeholder_name}` matches 1 or more * characters. The String value of the placeholder will be available in the arguments * [Bundle] with a key of the same name. For example, * `http://www.example.com/users/{id}` will match * `http://www.example.com/users/4`. * * The `.*` wildcard can be used to match 0 or more characters. * * @param navDeepLink the NavDeepLink to be added to this destination */ public fun deepLink(navDeepLink: NavDeepLinkDslBuilder.() -> Unit) { deepLinks.add(NavDeepLinkDslBuilder().apply(navDeepLink).build()) } private var actions = mutableMapOf<Int, NavAction>() /** * Adds a new [NavAction] to the destination */ @Deprecated( "Building NavDestinations using IDs with the Kotlin DSL has been deprecated in " + "favor of using routes. When using routes there is no need for actions." ) public fun action(actionId: Int, actionBuilder: NavActionBuilder.() -> Unit) { actions[actionId] = NavActionBuilder().apply(actionBuilder).build() } /** * Build the NavDestination by calling [Navigator.createDestination]. */ public open fun build(): D { return navigator.createDestination().also { destination -> if (route != null) { destination.route = route } if (id != -1) { destination.id = id } destination.label = label arguments.forEach { (name, argument) -> destination.addArgument(name, argument) } deepLinks.forEach { deepLink -> destination.addDeepLink(deepLink) } actions.forEach { (actionId, action) -> destination.putAction(actionId, action) } } } } /** * DSL for building a [NavAction]. */ @NavDestinationDsl public class NavActionBuilder { /** * The ID of the destination that should be navigated to when this action is used */ public var destinationId: Int = 0 /** * The set of default arguments that should be passed to the destination. The keys * used here should be the same as those used on the [NavDestinationBuilder.argument] * for the destination. * * All values added here should be able to be added to a [android.os.Bundle]. * * @see NavAction.getDefaultArguments */ public val defaultArguments: MutableMap<String, Any?> = mutableMapOf() private var navOptions: NavOptions? = null /** * Sets the [NavOptions] for this action that should be used by default */ public fun navOptions(optionsBuilder: NavOptionsBuilder.() -> Unit) { navOptions = NavOptionsBuilder().apply(optionsBuilder).build() } internal fun build() = NavAction( destinationId, navOptions, if (defaultArguments.isEmpty()) null else bundleOf(*defaultArguments.toList().toTypedArray()) ) } /** * DSL for constructing a new [NavArgument] */ @NavDestinationDsl public class NavArgumentBuilder { private val builder = NavArgument.Builder() private var _type: NavType<*>? = null /** * The NavType for this argument. * * If you don't set a type explicitly, it will be inferred * from the default value of this argument. */ public var type: NavType<*> set(value) { _type = value builder.setType(value) } get() { return _type ?: throw IllegalStateException("NavType has not been set on this builder.") } /** * Controls if this argument allows null values. */ public var nullable: Boolean = false set(value) { field = value builder.setIsNullable(value) } /** * An optional default value for this argument. * * Any object that you set here must be compatible with [type], if it was specified. */ public var defaultValue: Any? = null set(value) { field = value builder.setDefaultValue(value) } /** * Builds the NavArgument by calling [NavArgument.Builder.build]. */ public fun build(): NavArgument { return builder.build() } }
apache-2.0
cecad9f02d64703e3833ca21ba3ac956
31.436293
100
0.62631
4.550379
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/checker/infos/SmartCastOnIf.kt
8
275
// FIR_IDENTICAL fun baz(s: String?): Int { return if (s == null) { "" } else { val u: String? = null if (u == null) return 0 <info descr="Smart cast to kotlin.String" tooltip="Smart cast to kotlin.String">u</info> }.length }
apache-2.0
e0d2354471ad5d79df5d35a890bf3821
21.916667
96
0.530909
3.481013
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/cloneableProjects/CloneableProjectsService.kt
3
7523
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.welcomeScreen.cloneableProjects import com.intellij.CommonBundle import com.intellij.ide.RecentProjectMetaInfo import com.intellij.ide.RecentProjectsManager import com.intellij.ide.RecentProjectsManagerBase import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.components.Service.Level import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.TaskInfo import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.wm.ex.ProgressIndicatorEx import com.intellij.openapi.wm.impl.welcomeScreen.recentProjects.CloneableProjectItem import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.messages.Topic import org.jetbrains.annotations.CalledInAny import org.jetbrains.annotations.Nls import org.jetbrains.annotations.SystemIndependent import java.util.* @Service(Level.APP) class CloneableProjectsService { private val cloneableProjects: MutableSet<CloneableProject> = Collections.synchronizedSet(mutableSetOf()) @CalledInAny fun runCloneTask(projectPath: @SystemIndependent String, cloneTask: CloneTask) { val taskInfo = cloneTask.taskInfo() val progressIndicator = CloneableProjectProgressIndicator(taskInfo) val cloneableProject = CloneableProject(projectPath, taskInfo, progressIndicator, CloneStatus.PROGRESS) addCloneableProject(cloneableProject) ApplicationManager.getApplication().executeOnPooledThread { ProgressManager.getInstance().runProcess(Runnable { val activity = VcsCloneCollector.cloneStarted() val cloneStatus: CloneStatus = try { cloneTask.run(progressIndicator) } catch (_: ProcessCanceledException) { CloneStatus.CANCEL } catch (exception: Throwable) { logger<CloneableProjectsService>().error(exception) CloneStatus.FAILURE } VcsCloneCollector.cloneFinished(activity, cloneStatus) ApplicationManager.getApplication().invokeLater { when (cloneStatus) { CloneStatus.SUCCESS -> onSuccess(cloneableProject) CloneStatus.FAILURE -> onFailure(cloneableProject) CloneStatus.CANCEL -> onCancel(cloneableProject) else -> {} } } }, progressIndicator) } } internal fun collectCloneableProjects(): List<CloneableProjectItem> { val recentProjectManager = RecentProjectsManager.getInstance() as RecentProjectsManagerBase return cloneableProjects.map { cloneableProject -> val projectPath = cloneableProject.projectPath val projectName = recentProjectManager.getProjectName(projectPath) val displayName = recentProjectManager.getDisplayName(projectPath) ?: projectName CloneableProjectItem(projectPath, projectName, displayName, cloneableProject) } } fun cloneCount(): Int { return cloneableProjects.filter { it.cloneStatus == CloneStatus.PROGRESS }.size } fun isCloneActive(): Boolean { return cloneableProjects.any { it.cloneStatus == CloneStatus.PROGRESS } } fun cancelClone(cloneableProject: CloneableProject) { cloneableProject.progressIndicator.cancel() } fun removeCloneableProject(cloneableProject: CloneableProject) { if (cloneableProject.cloneStatus == CloneStatus.PROGRESS) { cloneableProject.progressIndicator.cancel() } cloneableProjects.removeIf { it.projectPath == cloneableProject.projectPath } fireCloneRemovedEvent() } private fun upgradeCloneProjectToRecent(cloneableProject: CloneableProject) { val recentProjectsManager = RecentProjectsManager.getInstance() as RecentProjectsManagerBase recentProjectsManager.addRecentPath(cloneableProject.projectPath, RecentProjectMetaInfo()) removeCloneableProject(cloneableProject) } private fun addCloneableProject(cloneableProject: CloneableProject) { cloneableProjects.removeIf { it.projectPath == cloneableProject.projectPath } cloneableProjects.add(cloneableProject) fireCloneAddedEvent(cloneableProject) } private fun onSuccess(cloneableProject: CloneableProject) { cloneableProject.cloneStatus = CloneStatus.SUCCESS upgradeCloneProjectToRecent(cloneableProject) fireCloneSuccessEvent() } private fun onFailure(cloneableProject: CloneableProject) { cloneableProject.cloneStatus = CloneStatus.FAILURE fireCloneFailedEvent() } private fun onCancel(cloneableProject: CloneableProject) { cloneableProject.cloneStatus = CloneStatus.CANCEL fireCloneCanceledEvent() } private fun fireCloneAddedEvent(cloneableProject: CloneableProject) { ApplicationManager.getApplication().messageBus .syncPublisher(TOPIC) .onCloneAdded(cloneableProject.progressIndicator, cloneableProject.cloneTaskInfo) } private fun fireCloneRemovedEvent() { ApplicationManager.getApplication().messageBus .syncPublisher(TOPIC) .onCloneRemoved() } private fun fireCloneSuccessEvent() { ApplicationManager.getApplication().messageBus .syncPublisher(TOPIC) .onCloneSuccess() } private fun fireCloneFailedEvent() { ApplicationManager.getApplication().messageBus .syncPublisher(TOPIC) .onCloneFailed() } private fun fireCloneCanceledEvent() { ApplicationManager.getApplication().messageBus .syncPublisher(TOPIC) .onCloneCanceled() } enum class CloneStatus { SUCCESS, PROGRESS, FAILURE, CANCEL } class CloneTaskInfo( @NlsContexts.ProgressTitle private val title: String, @Nls private val cancelTooltipText: String, @Nls val actionTitle: String, @Nls val actionTooltipText: String, @Nls val failedTitle: String, @Nls val canceledTitle: String, @Nls val stopTitle: String, @Nls val stopDescription: String ) : TaskInfo { override fun getTitle(): String = title override fun getCancelText(): String = CommonBundle.getCancelButtonText() override fun getCancelTooltipText(): String = cancelTooltipText override fun isCancellable(): Boolean = true } data class CloneableProject( val projectPath: @SystemIndependent String, val cloneTaskInfo: CloneTaskInfo, val progressIndicator: ProgressIndicatorEx, var cloneStatus: CloneStatus ) private class CloneableProjectProgressIndicator(cloneTaskInfo: CloneTaskInfo) : AbstractProgressIndicatorExBase() { init { setOwnerTask(cloneTaskInfo) } } interface CloneTask { fun taskInfo(): CloneTaskInfo fun run(indicator: ProgressIndicator): CloneStatus } interface CloneProjectListener { @RequiresEdt fun onCloneAdded(progressIndicator: ProgressIndicatorEx, taskInfo: TaskInfo) { } @RequiresEdt fun onCloneRemoved() { } @RequiresEdt fun onCloneSuccess() { } @RequiresEdt fun onCloneFailed() { } @RequiresEdt fun onCloneCanceled() { } } companion object { @JvmField val TOPIC = Topic(CloneProjectListener::class.java) @JvmStatic fun getInstance() = service<CloneableProjectsService>() } }
apache-2.0
d6d1f31cff8d5e8825e44a205f6c2772
32.145374
120
0.757544
4.968956
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/persistent_Id.kt
2
3518
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.bridgeEntities import com.intellij.workspaceModel.storage.SymbolicEntityId import org.jetbrains.deft.annotations.Open import java.io.Serializable data class ModuleId(val name: String) : SymbolicEntityId<ModuleEntity> { override val presentableName: String get() = name override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ModuleId) return false return name == other.name } override fun hashCode(): Int = name.hashCode() } data class FacetId(val name: String, val type: String, val parentId: ModuleId) : SymbolicEntityId<FacetEntity> { override val presentableName: String get() = name } data class ArtifactId(val name: String) : SymbolicEntityId<ArtifactEntity> { override val presentableName: String get() = name } @Open sealed class ModuleDependencyItem : Serializable { @Open sealed class Exportable : ModuleDependencyItem() { abstract val exported: Boolean abstract val scope: DependencyScope abstract fun withScope(scope: DependencyScope): Exportable abstract fun withExported(exported: Boolean): Exportable data class ModuleDependency( val module: ModuleId, override val exported: Boolean, override val scope: DependencyScope, val productionOnTest: Boolean ) : Exportable() { override fun withScope(scope: DependencyScope): Exportable = copy(scope = scope) override fun withExported(exported: Boolean): Exportable = copy(exported = exported) } data class LibraryDependency( val library: LibraryId, override val exported: Boolean, override val scope: DependencyScope ) : Exportable() { override fun withScope(scope: DependencyScope): Exportable = copy(scope = scope) override fun withExported(exported: Boolean): Exportable = copy(exported = exported) } } //todo use LibraryProxyId to refer to SDK instead data class SdkDependency(val sdkName: String, val sdkType: String) : ModuleDependencyItem() object InheritedSdkDependency : ModuleDependencyItem() object ModuleSourceDependency : ModuleDependencyItem() enum class DependencyScope { COMPILE, TEST, RUNTIME, PROVIDED } } @Open sealed class LibraryTableId : Serializable { data class ModuleLibraryTableId(val moduleId: ModuleId) : LibraryTableId() { override val level: String get() = "module" } object ProjectLibraryTableId : LibraryTableId() { override val level: String get() = "project" } data class GlobalLibraryTableId(override val level: String) : LibraryTableId() abstract val level: String } data class LibraryId(val name: String, val tableId: LibraryTableId) : SymbolicEntityId<LibraryEntity> { override val presentableName: String get() = name @Transient private var codeCache: Int = 0 override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is LibraryId) return false if (this.codeCache != 0 && other.codeCache != 0 && this.codeCache != other.codeCache) return false if (name != other.name) return false if (tableId != other.tableId) return false return true } override fun hashCode(): Int { if (codeCache != 0) return codeCache var result = name.hashCode() result = 31 * result + tableId.hashCode() this.codeCache = result return result } }
apache-2.0
2d4990d34daf3fe7a13dd5dc8aa4c56e
30.702703
120
0.720864
4.641161
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedDataClassCopyResultInspection.kt
3
1616
// 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.inspections import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.psi.callExpressionVisitor import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver class UnusedDataClassCopyResultInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = callExpressionVisitor(fun(call) { val callee = call.calleeExpression ?: return if (callee.text != "copy") return val context = call.analyze(BodyResolveMode.PARTIAL_WITH_CFA) val descriptor = call.getResolvedCall(context)?.resultingDescriptor ?: return val receiver = descriptor.dispatchReceiverParameter ?: descriptor.extensionReceiverParameter ?: return if ((receiver.value as? ImplicitClassReceiver)?.classDescriptor?.isData != true) return if (call.getQualifiedExpressionForSelectorOrThis().isUsedAsExpression(context)) return holder.registerProblem(callee, KotlinBundle.message("inspection.unused.result.of.data.class.copy")) }) }
apache-2.0
abb2e7ccaf25b00e1974d6281ad940a5
61.153846
158
0.801361
5.018634
false
false
false
false
GunoH/intellij-community
java/java-impl-refactorings/src/com/intellij/refactoring/extractMethod/newImpl/CodeFragmentAnalyzer.kt
2
12379
// 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.refactoring.extractMethod.newImpl import com.intellij.codeInsight.ExceptionUtil import com.intellij.codeInsight.Nullability import com.intellij.codeInspection.dataFlow.DfaNullability import com.intellij.codeInspection.dataFlow.StandardDataFlowRunner import com.intellij.codeInspection.dataFlow.interpreter.RunnerResult import com.intellij.codeInspection.dataFlow.java.JavaDfaListener import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState import com.intellij.codeInspection.dataFlow.value.DfaValue import com.intellij.java.refactoring.JavaRefactoringBundle import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.psi.controlFlow.* import com.intellij.psi.controlFlow.ControlFlowUtil.DEFAULT_EXIT_STATEMENTS_CLASSES import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.getReturnedExpression import com.intellij.refactoring.util.classMembers.ElementNeedsThis import com.siyeh.ig.psiutils.VariableAccessUtils import it.unimi.dsi.fastutil.ints.IntArrayList data class ExitDescription(val statements: List<PsiStatement>, val numberOfExits: Int, val hasSpecialExits: Boolean) data class ExternalReference(val variable: PsiVariable, val references: List<PsiReferenceExpression>) data class MemberUsage(val member: PsiMember, val reference: PsiReferenceExpression) class CodeFragmentAnalyzer(val elements: List<PsiElement>) { init { require(elements.isNotEmpty()) } private val codeFragment = ControlFlowUtil.findCodeFragment(elements.first()) private val flow: ControlFlow = createControlFlow() private val flowRange = findFlowRange(flow, elements) private fun createControlFlow(): ControlFlow { try { val fragmentToAnalyze: PsiElement = codeFragment val flowPolicy = LocalsControlFlowPolicy(fragmentToAnalyze) return ControlFlowFactory.getControlFlow(fragmentToAnalyze, flowPolicy, ControlFlowOptions.NO_CONST_EVALUATE) } catch (e: AnalysisCanceledException) { throw ExtractException(JavaRefactoringBundle.message("extract.method.control.flow.analysis.failed"), e.errorElement) } } private fun findFlowRange(flow: ControlFlow, elements: List<PsiElement>): IntRange { val expression = elements.singleOrNull() as? PsiParenthesizedExpression val normalizedElements = if (expression != null) listOfNotNull(PsiUtil.skipParenthesizedExprDown(expression)) else elements val firstElementInFlow = normalizedElements.find { element -> flow.getStartOffset(element) >= 0 } val lastElementInFlow = normalizedElements.findLast { element -> flow.getEndOffset(element) >= 0 } requireNotNull(firstElementInFlow) requireNotNull(lastElementInFlow) return flow.getStartOffset(firstElementInFlow)..flow.getEndOffset(lastElementInFlow) } private fun findVariableReferences(variable: PsiVariable): List<PsiReferenceExpression> { return elements.flatMap { VariableAccessUtils.getVariableReferences(variable, it) } } fun findExternalReferences(): List<ExternalReference> { return ControlFlowUtil.getInputVariables(flow, flowRange.first, flowRange.last) .filterNot { variable -> variable in this } .sortedWith( Comparator { v1: PsiVariable, v2: PsiVariable -> when { v1.type is PsiEllipsisType -> 1 v2.type is PsiEllipsisType -> -1 else -> v1.textOffset - v2.textOffset }}) .map { variable -> ExternalReference(variable, findVariableReferences(variable)) } } fun findUsedVariablesAfter(): List<PsiVariable> { return ControlFlowUtil.getUsedVariables(flow, flowRange.last, flow.size) } fun findOuterLocals(sourceClassMember: PsiElement, targetClassMember: PsiElement): List<ExternalReference>? { val outerVariables = mutableListOf<PsiVariable>() val canBeExtracted = elements .all { element -> ControlFlowUtil.collectOuterLocals(outerVariables, element, sourceClassMember, targetClassMember) } if (!canBeExtracted) return null return outerVariables.map { variable -> ExternalReference(variable, findVariableReferences(variable)) } } fun findOutputVariables(): List<PsiVariable> { return ControlFlowUtil.getOutputVariables(flow, flowRange.first, flowRange.last, findExitPoints().toIntArray()).distinct() } fun findUndeclaredVariables(): List<PsiVariable> { return ControlFlowUtil .getWrittenVariables(flow, flowRange.first, flowRange.last, false) .filterNot { variable -> variable.textRange in TextRange(elements.first().textRange.startOffset, elements.last().textRange.endOffset) } } fun hasObservableThrowExit(): Boolean { return ControlFlowUtil.hasObservableThrowExitPoints(flow, flowRange.first, flowRange.last, elements.toTypedArray(), codeFragment) } fun findExitDescription(): ExitDescription { val exitStatements = DEFAULT_EXIT_STATEMENTS_CLASSES + PsiYieldStatement::class.java val statements = ControlFlowUtil .findExitPointsAndStatements(flow, flowRange.first, flowRange.last, IntArrayList(), *exitStatements) .filterNot { statement -> isExitInside(statement) } val exitPoints = findExitPoints() val hasSpecialExits = exitPoints.singleOrNull() != lastGotoPointFrom(flowRange.last) return ExitDescription(statements, maxOf(1, exitPoints.size), hasSpecialExits) } fun findExposedLocalDeclarations(): List<PsiVariable> { val declaredVariables = HashSet<PsiVariable>() val visitor = object : JavaRecursiveElementWalkingVisitor() { override fun visitDeclarationStatement(statement: PsiDeclarationStatement) { declaredVariables += statement.declaredElements.filterIsInstance<PsiVariable>() } } elements.forEach { it.accept(visitor) } val externallyWrittenVariables = ControlFlowUtil.getWrittenVariables(flow, flowRange.last, flow.size, false).toSet() return declaredVariables.intersect(externallyWrittenVariables).toList() } fun findInstanceMemberUsages(targetClass: PsiClass, elements: List<PsiElement>): List<MemberUsage> { val usedFields = ArrayList<MemberUsage>() val visitor: ElementNeedsThis = object : ElementNeedsThis(targetClass) { override fun visitClassMemberReferenceElement(classMember: PsiMember, classMemberReference: PsiJavaCodeReferenceElement) { val expression = PsiTreeUtil.getParentOfType(classMemberReference, PsiReferenceExpression::class.java, false) if (expression != null && !classMember.hasModifierProperty(PsiModifier.STATIC)) { usedFields += MemberUsage(classMember, expression) } super.visitClassMemberReferenceElement(classMember, classMemberReference) } } elements.forEach { it.accept(visitor) } return usedFields.distinct() } private fun lastGotoPointFrom(instructionOffset: Int): Int { if (instructionOffset >= flow.size) return instructionOffset val instruction = flow.instructions[instructionOffset] val statement = flow.getElement(instructionOffset) as? PsiStatement return if (instruction is GoToInstruction && statement != null && getReturnedExpression(statement) == null) { lastGotoPointFrom(instruction.offset) } else { instructionOffset } } private fun isNonLocalJump(instructionOffset: Int): Boolean { return when (val instruction = flow.instructions[instructionOffset]) { is ThrowToInstruction, is ConditionalThrowToInstruction, is ReturnInstruction -> false is GoToInstruction -> instruction.offset !in (flowRange.first until flowRange.last) is BranchingInstruction -> instruction.offset !in (flowRange.first until flowRange.last) else -> false } } private fun isInstructionReachable(offset: Int): Boolean { return offset == flowRange.first || ControlFlowUtil.isInstructionReachable(flow, offset, flowRange.first) } private fun findDefaultExits(): List<Int> { val lastInstruction = flow.instructions[flowRange.last - 1] if (isInstructionReachable(flowRange.last - 1)) { val defaultExits = when (lastInstruction) { is ThrowToInstruction -> emptyList() is GoToInstruction -> listOf(lastInstruction.offset) is ConditionalThrowToInstruction -> listOf(flowRange.last) is BranchingInstruction -> listOf(lastInstruction.offset, flowRange.last) else -> listOf(flowRange.last) } return defaultExits.filterNot { it in flowRange.first until flowRange.last } } else { return emptyList() } } private fun findExitPoints(): List<Int> { if (flowRange.first == flowRange.last) return listOf(flowRange.last) val gotoInstructions = (flowRange.first until flowRange.last) .asSequence() .filter { offset -> isNonLocalJump(offset) && isInstructionReachable(offset) } .distinctBy { offset -> (flow.instructions[offset] as BranchingInstruction).offset } .toList() val jumpPoints = gotoInstructions .map { offset -> (flow.instructions[offset] as BranchingInstruction).offset } .toSet() val allExitPoints = jumpPoints + findDefaultExits() return allExitPoints.map { lastGotoPointFrom(it) }.distinct() } fun findThrownExceptions(): List<PsiClassType> { return ExceptionUtil.getThrownCheckedExceptions(*elements.toTypedArray()) } fun findWrittenVariables(): List<PsiVariable> { return ControlFlowUtil.getWrittenVariables(flow, flowRange.first, flowRange.last, false).toList() } private fun isExitInside(statement: PsiStatement): Boolean { return when (statement) { is PsiBreakStatement -> contains(statement.findExitedStatement()) is PsiContinueStatement -> contains(statement.findContinuedStatement()) is PsiReturnStatement -> false else -> false } } operator fun contains(element: PsiElement?): Boolean { if (element == null) return false val textRange = TextRange(elements.first().textRange.startOffset, elements.last().textRange.endOffset) return element.textRange in textRange } companion object { fun inferNullability(expressionGroup: List<PsiExpression>): Nullability { val expressionSet = expressionGroup.toHashSet() if (expressionSet.any { it.type == PsiType.NULL }) return Nullability.NULLABLE if (expressionSet.isEmpty()) return Nullability.UNKNOWN val fragmentToAnalyze = ControlFlowUtil.findCodeFragment(expressionSet.first()) val dfaRunner = StandardDataFlowRunner(fragmentToAnalyze.project) var nullability = DfaNullability.NOT_NULL class Listener : JavaDfaListener { override fun beforeExpressionPush(value: DfaValue, expr: PsiExpression, state: DfaMemoryState) { if (expr in expressionSet) { val expressionNullability = DfaNullability.fromDfType(state.getDfType(value)) nullability = nullability.unite(expressionNullability) } } } val runnerState = dfaRunner.analyzeMethod(fragmentToAnalyze, Listener()) return if (runnerState == RunnerResult.OK) { DfaNullability.toNullability(nullability) } else { Nullability.UNKNOWN } } fun inferNullability(place: PsiElement, probeExpression: String?): Nullability { if (probeExpression == null) return Nullability.UNKNOWN val factory = PsiElementFactory.getInstance(place.project) val sourceClass = findClassMember(place)?.containingClass ?: return Nullability.UNKNOWN val copyFile = sourceClass.containingFile.copy() as PsiFile val copyPlace = PsiTreeUtil.findSameElementInCopy(place, copyFile) val probeStatement = factory.createStatementFromText("return $probeExpression;", null) val parent = copyPlace.parent val codeBlock = if (parent is PsiCodeBlock) { copyPlace.parent as PsiCodeBlock } else { val block = copyPlace.parent.replace(factory.createCodeBlock()) as PsiCodeBlock block.add(copyPlace) block } val artificialReturn = codeBlock.add(probeStatement) as PsiReturnStatement val artificialExpression = requireNotNull(artificialReturn.returnValue) return inferNullability(listOf(artificialExpression)) } } }
apache-2.0
3aa5ccc8a8f3e033db96948b89aa80e9
45.19403
140
0.752888
4.779537
false
false
false
false
forgodsake/TowerPlus
Android/src/com/fuav/android/maps/providers/google_map/DownloadMapboxMapActivity.kt
1
6938
package com.fuav.android.maps.providers.google_map import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.ProgressBar import android.widget.Toast import com.fuav.android.DroidPlannerApp import com.fuav.android.R import com.fuav.android.maps.providers.google_map.tiles.mapbox.offline.MapDownloader import com.fuav.android.maps.providers.google_map.tiles.mapbox.offline.MapDownloaderListener import com.fuav.android.utils.prefs.AutoPanMode import java.net.HttpURLConnection /** * Created by Fredia Huya-Kouadio on 6/17/15. */ public class DownloadMapboxMapActivity : AppCompatActivity() { val MAP_CACHE_ZOOM_LEVEL = 19 private val mapDownloader: MapDownloader by lazy(LazyThreadSafetyMode.NONE) { val dpApp = application as DroidPlannerApp dpApp.mapDownloader } private val mapboxId: String by lazy(LazyThreadSafetyMode.NONE) { GoogleMapPrefFragment.PrefManager.getMapboxId(applicationContext) } private val mapboxAccessToken: String by lazy(LazyThreadSafetyMode.NONE) { GoogleMapPrefFragment.PrefManager.getMapboxAccessToken(applicationContext) } private val mapDownloadListener = object : MapDownloaderListener { override fun completionOfOfflineDatabaseMap() { runOnUiThread { completeMapDownload() } } override fun httpStatusError(status: Int, url: String) { when(status){ HttpURLConnection.HTTP_UNAUTHORIZED -> { runOnUiThread { Toast.makeText(applicationContext, "Invalid mapbox credentials! Cancelling map download...", Toast.LENGTH_LONG).show() cancelMapDownload() } } } } override fun initialCountOfFiles(numberOfFiles: Int) { runOnUiThread { downloadProgressBar?.isIndeterminate = false downloadProgressBar?.max = numberOfFiles downloadProgressBar?.progress = 0 } } override fun networkConnectivityError(error: Throwable?) { } override fun progressUpdate(numberOfFilesWritten: Int, numberOfFilesExcepted: Int) { runOnUiThread { downloadProgressBar?.isIndeterminate = false downloadProgressBar?.max = numberOfFilesExcepted downloadProgressBar?.progress = numberOfFilesWritten } } override fun sqlLiteError(error: Throwable?) { } override fun stateChanged(newState: MapDownloader.MBXOfflineMapDownloaderState?) { when (newState) { MapDownloader.MBXOfflineMapDownloaderState.MBXOfflineMapDownloaderStateRunning -> { enableDownloadInstructions(false) enableDownloadProgress(true, resetProgress = true) } MapDownloader.MBXOfflineMapDownloaderState.MBXOfflineMapDownloaderStateCanceling -> { enableDownloadProgress(false, true) enableDownloadInstructions(true) } } } } private var instructionsContainer: View? = null private var downloadProgressContainer: View? = null private var cancelDownloadButton: View? = null private var downloadProgressBar: ProgressBar? = null private var downloadMapFragment: DownloadMapboxMapFragment? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_download_mapbox_map) val fm = supportFragmentManager downloadMapFragment = fm.findFragmentById(R.id.map_container) as DownloadMapboxMapFragment? if (downloadMapFragment == null) { downloadMapFragment = DownloadMapboxMapFragment() fm.beginTransaction().add(R.id.map_container, downloadMapFragment).commit() } instructionsContainer = findViewById(R.id.download_map_instructions) instructionsContainer?.setOnClickListener { triggerMapDownload() } downloadProgressContainer = findViewById(R.id.download_map_progress) cancelDownloadButton = findViewById(R.id.map_bottom_bar_close_button) cancelDownloadButton?.setOnClickListener { cancelMapDownload() } downloadProgressBar = findViewById(R.id.map_download_progress_bar) as ProgressBar? val goToMyLocation = findViewById(R.id.my_location_button) goToMyLocation?.setOnClickListener { downloadMapFragment?.goToMyLocation() } goToMyLocation?.setOnLongClickListener { downloadMapFragment?.setAutoPanMode(AutoPanMode.USER) true } val goToDroneLocation = findViewById(R.id.drone_location_button) goToDroneLocation?.setOnClickListener { downloadMapFragment?.goToDroneLocation() } goToDroneLocation?.setOnLongClickListener { downloadMapFragment?.setAutoPanMode(AutoPanMode.DRONE) true } } private fun completeMapDownload() { Toast.makeText(applicationContext, R.string.label_map_saved, Toast.LENGTH_LONG).show() enableDownloadInstructions(true) enableDownloadProgress(false, true) } private fun cancelMapDownload() { mapDownloader.cancelDownload() } override fun onStart() { super.onStart() if (mapDownloader.state == MapDownloader.MBXOfflineMapDownloaderState.MBXOfflineMapDownloaderStateRunning) { enableDownloadInstructions(false) enableDownloadProgress(true, true) } mapDownloader.addMapDownloaderListener(mapDownloadListener) } override fun onStop() { super.onStop() if (isFinishing) cancelMapDownload() mapDownloader.removeMapDownloaderListener(mapDownloadListener) } override fun onBackPressed() { super.onBackPressed() cancelMapDownload() } private fun triggerMapDownload() { val mapArea = downloadMapFragment?.visibleMapArea mapDownloader.beginDownloadingMapID(mapboxId, mapboxAccessToken, mapArea, 0, MAP_CACHE_ZOOM_LEVEL) } private fun enableDownloadInstructions(enabled: Boolean) { instructionsContainer?.visibility = if (enabled) View.VISIBLE else View.GONE } private fun enableDownloadProgress(enabled: Boolean, resetProgress: Boolean) { downloadProgressContainer?.visibility = if (enabled) View.VISIBLE else View.GONE if (resetProgress) { downloadProgressBar?.progress = 0 downloadProgressBar?.isIndeterminate = true } } }
gpl-3.0
78a8111f1993c580c8d25af55ffa5237
35.311828
116
0.660277
5.244142
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspections/protectedInFinal/protectedInFinal.kt
13
504
class F { protected val foo: Int = 0 protected fun bar() {} protected class Nested } class G { interface H { protected val foo: Int = 0 protected fun bar() {} protected class Nested } } sealed class S { protected val foo: Int = 0 protected fun bar() {} protected class Nested : S() protected object Obj : S() } enum class E { SINGLE { override val x = foo() }; abstract val x: Int protected fun foo() = 42 }
apache-2.0
02fe6572f3f07f42a4afe152d1979ec4
12.621622
34
0.553571
4.064516
false
false
false
false
smmribeiro/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookEditorAppearance.kt
7
4386
package org.jetbrains.plugins.notebooks.visualization import com.intellij.openapi.editor.colors.EditorColorsScheme import com.intellij.openapi.editor.impl.EditorImpl import org.jetbrains.plugins.notebooks.visualization.r.inlays.EditorInlaysManager import java.awt.Color /** * Constants and functions that affects only visual representation, like colors, sizes of elements, etc. */ interface NotebookEditorAppearance: NotebookEditorAppearanceColors, NotebookEditorAppearanceSizes interface NotebookEditorAppearanceSizes { val CODE_CELL_LEFT_LINE_PADDING: Int val LINE_NUMBERS_MARGIN: Int // TODO Do the pixel constants need JBUI.scale? val COMMAND_MODE_CELL_LEFT_LINE_WIDTH : Int val EDIT_MODE_CELL_LEFT_LINE_WIDTH : Int val CODE_AND_CODE_TOP_GRAY_HEIGHT : Int val CODE_AND_CODE_BOTTOM_GRAY_HEIGHT : Int val INNER_CELL_TOOLBAR_HEIGHT : Int val CELL_BORDER_HEIGHT : Int val SPACE_BELOW_CELL_TOOLBAR : Int val CELL_TOOLBAR_TOTAL_HEIGHT : Int val PROGRESS_STATUS_HEIGHT : Int val JUPYTER_CELL_SPACERS_INLAY_PRIORITY: Int val JUPYTER_BELOW_OUTPUT_CELL_SPACERS_INLAY_PRIORITY: Int val JUPYTER_CELL_TOOLBAR_INLAY_PRIORITY: Int val NOTEBOOK_OUTPUT_INLAY_PRIORITY: Int val EXTRA_PADDING_EXECUTION_COUNT: Int fun getCellLeftLineWidth(): Int fun getCellLeftLineHoverWidth(): Int fun getLeftBorderWidth(): Int val EXTRA_GUTTER_AREA_WIDTH_EXECUTION_COUNT: Int } interface NotebookEditorAppearanceColors { // TODO Sort everything lexicographically. fun getCodeCellBackground(scheme: EditorColorsScheme): Color? = null fun getGutterInputExecutionCountForegroundColor(scheme: EditorColorsScheme): Color? = null fun getGutterOutputExecutionCountForegroundColor(scheme: EditorColorsScheme): Color? = null fun getProgressStatusRunningColor(scheme: EditorColorsScheme): Color = Color.BLUE fun getInlayBackgroundColor(scheme: EditorColorsScheme): Color? = null fun getSausageButtonAppearanceBackgroundColor(scheme: EditorColorsScheme): Color = Color.WHITE fun getSausageButtonAppearanceForegroundColor(scheme: EditorColorsScheme): Color = Color.BLACK fun getSausageButtonShortcutColor(scheme: EditorColorsScheme): Color = Color.GRAY fun getSausageButtonBorderColor(scheme: EditorColorsScheme): Color = Color.GRAY /** * Takes lines of the cell and returns a color for the stripe that will be drawn behind the folding markers. * Currently only code cells are supported. */ fun getCellStripeColor(editor: EditorImpl, interval: NotebookCellLines.Interval): Color? = null fun getCellStripeHoverColor(editor: EditorImpl, interval: NotebookCellLines.Interval): Color? = null fun shouldShowCellLineNumbers(): Boolean } object DefaultNotebookEditorAppearanceSizes: NotebookEditorAppearanceSizes { // TODO it's hardcoded, but it should be equal to distance between a folding line and an editor. override val CODE_CELL_LEFT_LINE_PADDING = 5 // TODO it's hardcoded, but it should be EditorGutterComponentImpl.getLineNumberAreaWidth() override val LINE_NUMBERS_MARGIN = 10 // TODO Do the pixel constants need JBUI.scale? override val COMMAND_MODE_CELL_LEFT_LINE_WIDTH = 4 override val EDIT_MODE_CELL_LEFT_LINE_WIDTH = 2 override val CODE_AND_CODE_TOP_GRAY_HEIGHT = 6 override val CODE_AND_CODE_BOTTOM_GRAY_HEIGHT = 6 override val INNER_CELL_TOOLBAR_HEIGHT = 25 override val CELL_BORDER_HEIGHT = 20 override val SPACE_BELOW_CELL_TOOLBAR = 12 override val CELL_TOOLBAR_TOTAL_HEIGHT = INNER_CELL_TOOLBAR_HEIGHT + SPACE_BELOW_CELL_TOOLBAR override val PROGRESS_STATUS_HEIGHT = 2 override val JUPYTER_CELL_SPACERS_INLAY_PRIORITY = EditorInlaysManager.INLAY_PRIORITY + 10 override val JUPYTER_BELOW_OUTPUT_CELL_SPACERS_INLAY_PRIORITY = EditorInlaysManager.INLAY_PRIORITY - 10 override val JUPYTER_CELL_TOOLBAR_INLAY_PRIORITY = JUPYTER_CELL_SPACERS_INLAY_PRIORITY + 10 override val NOTEBOOK_OUTPUT_INLAY_PRIORITY: Int = EditorInlaysManager.INLAY_PRIORITY + 5 override val EXTRA_PADDING_EXECUTION_COUNT = 25 override val EXTRA_GUTTER_AREA_WIDTH_EXECUTION_COUNT = 40 override fun getCellLeftLineWidth(): Int = EDIT_MODE_CELL_LEFT_LINE_WIDTH override fun getCellLeftLineHoverWidth(): Int = COMMAND_MODE_CELL_LEFT_LINE_WIDTH override fun getLeftBorderWidth(): Int = Integer.max(COMMAND_MODE_CELL_LEFT_LINE_WIDTH, EDIT_MODE_CELL_LEFT_LINE_WIDTH) + CODE_CELL_LEFT_LINE_PADDING }
apache-2.0
450c9f54c056991c45a8b4365fef1014
42.435644
112
0.790698
4.08
false
false
false
false
BenWoodworth/FastCraft
fastcraft-core/src/main/kotlin/net/benwoodworth/fastcraft/crafting/view/buttons/CustomButtonView.kt
1
1904
package net.benwoodworth.fastcraft.crafting.view.buttons import net.benwoodworth.fastcraft.Config import net.benwoodworth.fastcraft.platform.gui.FcGui import net.benwoodworth.fastcraft.platform.gui.FcGuiButton import net.benwoodworth.fastcraft.platform.gui.FcGuiClick import net.benwoodworth.fastcraft.platform.player.FcPlayer import net.benwoodworth.fastcraft.platform.player.FcSound import javax.inject.Inject class CustomButtonView( private val button: FcGuiButton, private val command: String?, private val fcSoundFactory: FcSound.Factory, fcPlayerOperations: FcPlayer.Operations, ) : FcPlayer.Operations by fcPlayerOperations { var listener: Listener = Listener.Default init { button.listener = ButtonListener() } fun update() { // button.copyItem(customButton.item) } interface Listener { object Default : Listener fun onClick(command: String?) {} } private inner class ButtonListener : FcGuiButton.Listener { override fun onClick(gui: FcGui<*>, button: FcGuiButton, click: FcGuiClick) { if (click is FcGuiClick.Primary && click.modifiers.isEmpty()) { listener.onClick(command) if (command != null) { gui.player.playSound(fcSoundFactory.uiButtonClick, Config.buttonVolume) } } } } class Factory @Inject constructor( private val fcSoundFactory: FcSound.Factory, private val fcPlayerOperations: FcPlayer.Operations, ) { fun create( button: FcGuiButton, command: String?, ): CustomButtonView { return CustomButtonView( button = button, command = command, fcSoundFactory = fcSoundFactory, fcPlayerOperations = fcPlayerOperations, ) } } }
gpl-3.0
2902b75c151c79fe1b3131ac5deabde1
30.213115
91
0.652836
4.712871
false
false
false
false
ReactiveX/RxKotlin
src/main/kotlin/io/reactivex/rxkotlin/Observables.kt
1
14744
@file:Suppress("unused", "HasPlatformType") package io.reactivex.rxkotlin import io.reactivex.Observable import io.reactivex.ObservableSource import io.reactivex.annotations.CheckReturnValue import io.reactivex.annotations.SchedulerSupport import io.reactivex.functions.* /** * SAM adapters to aid Kotlin lambda support */ object Observables { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, R : Any> combineLatest( source1: Observable<T1>, source2: Observable<T2>, crossinline combineFunction: (T1, T2) -> R ): Observable<R> = Observable.combineLatest(source1, source2, BiFunction<T1, T2, R> { t1, t2 -> combineFunction(t1, t2) }) /** * Emits `Pair<T1,T2>` */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) fun <T1 : Any, T2 : Any> combineLatest(source1: Observable<T1>, source2: Observable<T2>): Observable<Pair<T1, T2>> = Observable.combineLatest(source1, source2, BiFunction<T1, T2, Pair<T1, T2>> { t1, t2 -> t1 to t2 }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, R : Any> combineLatest( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, crossinline combineFunction: (T1, T2, T3) -> R ): Observable<R> = Observable.combineLatest(source1, source2, source3, Function3 { t1: T1, t2: T2, t3: T3 -> combineFunction(t1, t2, t3) }) /** * Emits `Triple<T1,T2,T3>` */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) fun <T1 : Any, T2 : Any, T3 : Any> combineLatest( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3> ): Observable<Triple<T1, T2, T3>> = Observable.combineLatest(source1, source2, source3, Function3<T1, T2, T3, Triple<T1, T2, T3>> { t1, t2, t3 -> Triple(t1, t2, t3) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, R : Any> combineLatest( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, crossinline combineFunction: (T1, T2, T3, T4) -> R ): Observable<R> = Observable.combineLatest(source1, source2, source3, source4, Function4 { t1: T1, t2: T2, t3: T3, t4: T4 -> combineFunction(t1, t2, t3, t4) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, R : Any> combineLatest( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, source5: Observable<T5>, crossinline combineFunction: (T1, T2, T3, T4, T5) -> R ): Observable<R> = Observable.combineLatest(source1, source2, source3, source4, source5, Function5 { t1: T1, t2: T2, t3: T3, t4: T4, t5: T5 -> combineFunction(t1, t2, t3, t4, t5) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, R : Any> combineLatest( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, source5: Observable<T5>, source6: Observable<T6>, crossinline combineFunction: (T1, T2, T3, T4, T5, T6) -> R ): Observable<R> = Observable.combineLatest(source1, source2, source3, source4, source5, source6, Function6 { t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6 -> combineFunction(t1, t2, t3, t4, t5, t6) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, T7 : Any, R : Any> combineLatest( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, source5: Observable<T5>, source6: Observable<T6>, source7: Observable<T7>, crossinline combineFunction: (T1, T2, T3, T4, T5, T6, T7) -> R ): Observable<R> = Observable.combineLatest(source1, source2, source3, source4, source5, source6, source7, Function7 { t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7 -> combineFunction(t1, t2, t3, t4, t5, t6, t7) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, T7 : Any, T8 : Any, R : Any> combineLatest( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, source5: Observable<T5>, source6: Observable<T6>, source7: Observable<T7>, source8: Observable<T8>, crossinline combineFunction: (T1, T2, T3, T4, T5, T6, T7, T8) -> R ): Observable<R> = Observable.combineLatest(source1, source2, source3, source4, source5, source6, source7, source8, Function8 { t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8 -> combineFunction(t1, t2, t3, t4, t5, t6, t7, t8) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, T7 : Any, T8 : Any, T9 : Any, R : Any> combineLatest( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, source5: Observable<T5>, source6: Observable<T6>, source7: Observable<T7>, source8: Observable<T8>, source9: Observable<T9>, crossinline combineFunction: (T1, T2, T3, T4, T5, T6, T7, T8, T9) -> R ): Observable<R> = Observable.combineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, Function9 { t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9 -> combineFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, R : Any> zip( source1: Observable<T1>, source2: Observable<T2>, crossinline combineFunction: (T1, T2) -> R ): Observable<R> = Observable.zip(source1, source2, BiFunction<T1, T2, R> { t1, t2 -> combineFunction(t1, t2) }) /** * Emits `Pair<T1,T2>` */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) fun <T1 : Any, T2 : Any> zip(source1: Observable<T1>, source2: Observable<T2>): Observable<Pair<T1, T2>> = Observable.zip(source1, source2, BiFunction<T1, T2, Pair<T1, T2>> { t1, t2 -> t1 to t2 }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, R : Any> zip( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, crossinline combineFunction: (T1, T2, T3) -> R ): Observable<R> = Observable.zip(source1, source2, source3, Function3 { t1: T1, t2: T2, t3: T3 -> combineFunction(t1, t2, t3) }) /** * Emits `Triple<T1,T2,T3>` */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) fun <T1 : Any, T2 : Any, T3 : Any> zip( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3> ): Observable<Triple<T1, T2, T3>> = Observable.zip(source1, source2, source3, Function3<T1, T2, T3, Triple<T1, T2, T3>> { t1, t2, t3 -> Triple(t1, t2, t3) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, R : Any> zip( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, crossinline combineFunction: (T1, T2, T3, T4) -> R ): Observable<R> = Observable.zip(source1, source2, source3, source4, Function4 { t1: T1, t2: T2, t3: T3, t4: T4 -> combineFunction(t1, t2, t3, t4) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, R : Any> zip( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, source5: Observable<T5>, crossinline combineFunction: (T1, T2, T3, T4, T5) -> R ): Observable<R> = Observable.zip(source1, source2, source3, source4, source5, Function5 { t1: T1, t2: T2, t3: T3, t4: T4, t5: T5 -> combineFunction(t1, t2, t3, t4, t5) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, R : Any> zip( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, source5: Observable<T5>, source6: Observable<T6>, crossinline combineFunction: (T1, T2, T3, T4, T5, T6) -> R ): Observable<R> = Observable.zip(source1, source2, source3, source4, source5, source6, Function6 { t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6 -> combineFunction(t1, t2, t3, t4, t5, t6) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, T7 : Any, R : Any> zip( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, source5: Observable<T5>, source6: Observable<T6>, source7: Observable<T7>, crossinline combineFunction: (T1, T2, T3, T4, T5, T6, T7) -> R ): Observable<R> = Observable.zip(source1, source2, source3, source4, source5, source6, source7, Function7 { t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7 -> combineFunction(t1, t2, t3, t4, t5, t6, t7) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, T7 : Any, T8 : Any, R : Any> zip( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, source5: Observable<T5>, source6: Observable<T6>, source7: Observable<T7>, source8: Observable<T8>, crossinline combineFunction: (T1, T2, T3, T4, T5, T6, T7, T8) -> R ): Observable<R> = Observable.zip(source1, source2, source3, source4, source5, source6, source7, source8, Function8 { t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8 -> combineFunction(t1, t2, t3, t4, t5, t6, t7, t8) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, T7 : Any, T8 : Any, T9 : Any, R : Any> zip( source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, source5: Observable<T5>, source6: Observable<T6>, source7: Observable<T7>, source8: Observable<T8>, source9: Observable<T9>, crossinline combineFunction: (T1, T2, T3, T4, T5, T6, T7, T8, T9) -> R ): Observable<R> = Observable.zip(source1, source2, source3, source4, source5, source6, source7, source8, source9, Function9 { t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9 -> combineFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9) }) } /** * An alias to [Observable.withLatestFrom], but allowing for cleaner lambda syntax. */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T : Any, U : Any, R : Any> Observable<T>.withLatestFrom( other: ObservableSource<U>, crossinline combiner: (T, U) -> R ): Observable<R> = withLatestFrom(other, BiFunction<T, U, R> { t, u -> combiner.invoke(t, u) }) /** * Emits a `Pair` */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) fun <T : Any, U : Any> Observable<T>.withLatestFrom(other: ObservableSource<U>): Observable<Pair<T, U>> = withLatestFrom(other, BiFunction { t, u -> Pair(t, u) }) /** * An alias to [Observable.withLatestFrom], but allowing for cleaner lambda syntax. */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T : Any, T1 : Any, T2 : Any, R : Any> Observable<T>.withLatestFrom( o1: ObservableSource<T1>, o2: ObservableSource<T2>, crossinline combiner: (T, T1, T2) -> R ): Observable<R> = withLatestFrom(o1, o2, Function3<T, T1, T2, R> { t, t1, t2 -> combiner.invoke(t, t1, t2) }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) fun <T : Any, T1 : Any, T2 : Any> Observable<T>.withLatestFrom( o1: ObservableSource<T1>, o2: ObservableSource<T2> ): Observable<Triple<T, T1, T2>> = withLatestFrom(o1, o2, Function3 { t, t1, t2 -> Triple(t, t1, t2) }) /** * An alias to [Observable.withLatestFrom], but allowing for cleaner lambda syntax. */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T : Any, T1 : Any, T2 : Any, T3 : Any, R : Any> Observable<T>.withLatestFrom( o1: ObservableSource<T1>, o2: ObservableSource<T2>, o3: ObservableSource<T3>, crossinline combiner: (T, T1, T2, T3) -> R ): Observable<R> = withLatestFrom(o1, o2, o3, Function4<T, T1, T2, T3, R> { t, t1, t2, t3 -> combiner.invoke(t, t1, t2, t3) }) /** * An alias to [Observable.withLatestFrom], but allowing for cleaner lambda syntax. */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T : Any, T1 : Any, T2 : Any, T3 : Any, T4 : Any, R : Any> Observable<T>.withLatestFrom( o1: ObservableSource<T1>, o2: ObservableSource<T2>, o3: ObservableSource<T3>, o4: ObservableSource<T4>, crossinline combiner: (T, T1, T2, T3, T4) -> R ): Observable<R> = withLatestFrom(o1, o2, o3, o4, Function5<T, T1, T2, T3, T4, R> { t, t1, t2, t3, t4 -> combiner.invoke(t, t1, t2, t3, t4) }) /** * An alias to [Observable.zipWith], but allowing for cleaner lambda syntax. */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) inline fun <T : Any, U : Any, R : Any> Observable<T>.zipWith( other: ObservableSource<U>, crossinline zipper: (T, U) -> R ): Observable<R> = zipWith(other, BiFunction { t, u -> zipper.invoke(t, u) }) /** * Emits a zipped `Pair` */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) fun <T : Any, U : Any> Observable<T>.zipWith(other: ObservableSource<U>): Observable<Pair<T, U>> = zipWith(other, BiFunction { t, u -> Pair(t, u) })
apache-2.0
743750b0cd4196630ce89f565accf4a6
47.660066
152
0.621066
3.014516
false
true
false
false
TachiWeb/TachiWeb-Server
TachiServer/src/main/java/xyz/nulldev/ts/syncdeploy/MainPage.kt
1
8213
package xyz.nulldev.ts.syncdeploy import com.github.salomonbrys.kodein.Kodein import com.github.salomonbrys.kodein.conf.global import com.github.salomonbrys.kodein.instance import kotlinx.html.* import spark.Request import spark.Response import spark.Route import xyz.nulldev.ts.config.ConfigManager class MainPage(private val am: AccountManager, private val mainPagePath: String) : Route { private val syncConfig = Kodein.global.instance<ConfigManager>().module<SyncConfigModule>() //language=html override fun handle(request: Request, response: Response): Any { val username = request.cookie("username") val token = request.cookie("token") // Redirect logged in users if(username != null && token != null && am.authToken(username, token)) { response.redirect("/account") return "" } return SiteTemplate(mainPagePath).build(syncConfig.name, showLogout = false) { script(src = "https://www.google.com/recaptcha/api.js?onload=recaptchaOnload&render=explicit") { async = true defer = true } //language=js script { unsafe { raw(""" function recaptchaOnload() { renderCaptcha('login_captcha', 'finishLogin'); renderCaptcha('register_captcha', 'finishRegister'); } function renderCaptcha(elementId, callback) { grecaptcha.render(elementId, { sitekey: '${syncConfig.recaptchaSiteKey}', callback: callback, size: 'invisible' }); } window.onload = function() { let loginForm = $(".login-form"); let registerForm = $(".register-form"); window.finishLogin = function(token) { grecaptcha.reset(0); loginForm.api({ action: 'auth', method : 'POST', data: { register: false, username: $('[name=l-username]').val(), password: $('[name=l-password]').val(), "g-recaptcha-response": token }, on: 'now', onFailure: function(e) { if(e.error != null) showError(loginForm, e.error); else showError(loginForm, "Failed to connect to server!"); }, onSuccess: function(e) { authClient($('[name="l-username"]').val(), e.data.token); } }); }; window.finishRegister = function(token) { grecaptcha.reset(1); registerForm.api({ action: 'auth', method : 'POST', data: { register: true, username: $('[name=r-username]').val(), password: $('[name=r-password]').val(), "g-recaptcha-response": token }, on: 'now', onFailure: function(e) { if(e.error != null) showError(registerForm, e.error); else showError(registerForm, "Failed to connect to server!"); }, onSuccess: function(e) { authClient($('[name="r-username"]').val(), e.data.token); } }); }; function authClient(name, token) { $('.auth-dimmer').dimmer({ closable: false }).dimmer('show'); Cookies.set('${SiteTemplate.USERNAME_COOKIE}', name); Cookies.set('${SiteTemplate.TOKEN_COOKIE}', token); window.location.href = "/account"; } function showError(form, message) { form.removeClass("success"); form.addClass("error"); form.find(".error.message").text(message); } loginForm.form({ fields: { username: { identifier: "l-username", rules: [ { type: 'empty', prompt: 'Please enter a username' } ] }, password: { identifier: 'l-password', rules: [ { type: 'empty', prompt: 'Please enter a password' } ] } }, onSuccess: function() { grecaptcha.execute(0); return false; } }); registerForm.form({ fields: { username: { identifier: "r-username", rules: [ { type: 'empty', prompt: 'Please enter a username' }, { type: 'maxLength[100]', prompt: 'Please use a shorter username' } ] }, password: { identifier: 'r-password', rules: [ { type: 'empty', prompt: 'Please enter a password' } ] }, confirmPassword: { identifier: 'r-confirm-password', rules: [ { type: 'empty', prompt: 'Please re-enter your password' }, { type: 'match[r-password]', prompt: 'Your confirmed password is different from your password! Please re-type your passwords.' } ] } }, onSuccess: function() { grecaptcha.execute(1); return false; } }); }; """) } } div(classes = "ui two column divided stackable grid") { div(classes = "row") { div ("column") { h1("ui header") { +"Login" } div(classes = "ui form login-form") { div("field") { label { +"Username" } input(InputType.text, name = "l-username") } div("field") { label { +"Password" } input(InputType.password, name = "l-password") } div("ui error message") button(classes = "ui primary submit button") { +"Login" } } } div ("column") { h1("ui header") { +"Create account" } div(classes = "ui form register-form") { div("field") { label { +"Username" } input(InputType.text, name = "r-username") } div("field") { label { +"Password" } input(InputType.password, name = "r-password") } div("field") { label { +"Confirm password" } input(InputType.password, name = "r-confirm-password") } div("ui error message") button(classes = "ui primary submit button") { +"Create account" } } } } } div { id = "login_captcha" } div { id = "register_captcha" } div("ui page dimmer auth-dimmer") { div("ui text huge loader") { +"Loading..." } } } } }
apache-2.0
ce7b98886565795e5242e8bd3792a047
31.462451
121
0.40302
5.340052
false
false
false
false
TachiWeb/TachiWeb-Server
Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/data/sync/protocol/models/IntermediaryApplySyncReport.kt
1
1961
package eu.kanade.tachiyomi.data.sync.protocol.models import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.EntryUpdate import eu.kanade.tachiyomi.data.database.models.UpdatableField import eu.kanade.tachiyomi.data.sync.protocol.models.common.SyncEntity /** * Intermediary data structure with various optimizations used to apply sync report */ class IntermediaryApplySyncReport(val report: SyncReport) { private var lastQueuedId = 0L lateinit var sortedEntities: List<SyncEntity<*>> var queuedTimestampEntries = mutableListOf<QueuedTimestampEntry>() var queuedInsertedIds = mutableListOf<QueuedInsertedId>() fun nextQueuedId() = --lastQueuedId fun setup() { sortedEntities = report.entities.sortedBy { it.syncId } } fun applyQueuedTimestamps(db: DatabaseHelper) { //Prepare queued inserted IDs for binary search queuedInsertedIds.sortBy { it.oldId } queuedTimestampEntries.forEach { val id = if(it.id < 0) { //Find inserted id if entity does not have a valid id queuedInsertedIds[queuedInsertedIds.binarySearchBy(it.id, selector = QueuedInsertedId::oldId).let { if (it < 0) return@forEach //Never inserted, ignore this entity else it }].dbId } else it.id //Entity has valid id, use it val newEntryUpdate = EntryUpdate.create(id, it.time, it.field) //Correct timestamp db.replaceEntryUpdate(newEntryUpdate).executeAsBlocking() } } data class QueuedTimestampEntry(val id: Long, val field: UpdatableField, val time: Long) data class QueuedInsertedId(val oldId: Long, val dbId: Long) }
apache-2.0
3a5ac755dc702052194a5012abd9d871
37.45098
115
0.626721
4.806373
false
false
false
false
TachiWeb/TachiWeb-Server
Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/data/database/queries/HistoryQueries.kt
1
3541
package eu.kanade.tachiyomi.data.database.queries import com.pushtorefresh.storio.sqlite.queries.DeleteQuery import com.pushtorefresh.storio.sqlite.queries.Query import com.pushtorefresh.storio.sqlite.queries.RawQuery import eu.kanade.tachiyomi.data.database.DbProvider import eu.kanade.tachiyomi.data.database.models.History import eu.kanade.tachiyomi.data.database.models.MangaChapterHistory import eu.kanade.tachiyomi.data.database.resolvers.HistoryLastReadPutResolver import eu.kanade.tachiyomi.data.database.resolvers.MangaChapterHistoryGetResolver import eu.kanade.tachiyomi.data.database.tables.HistoryTable import java.util.* interface HistoryQueries : DbProvider { /** * Insert history into database * @param history object containing history information */ fun insertHistory(history: History) = db.put().`object`(history).prepare() /** * Returns history of recent manga containing last read chapter * @param date recent date range */ fun getRecentManga(date: Date) = db.get() .listOfObjects(MangaChapterHistory::class.java) .withQuery(RawQuery.builder() .query(getRecentMangasQuery()) .args(date.time) .observesTables(HistoryTable.TABLE) .build()) .withGetResolver(MangaChapterHistoryGetResolver.INSTANCE) .prepare() fun getHistoryByMangaId(mangaId: Long) = db.get() .listOfObjects(History::class.java) .withQuery(RawQuery.builder() .query(getHistoryByMangaId()) .args(mangaId) .observesTables(HistoryTable.TABLE) .build()) .prepare() fun getHistoryByChapterUrl(chapterUrl: String) = db.get() .`object`(History::class.java) .withQuery(RawQuery.builder() .query(getHistoryByChapterUrl()) .args(chapterUrl) .observesTables(HistoryTable.TABLE) .build()) .prepare() /** * Updates the history last read. * Inserts history object if not yet in database * @param history history object */ fun updateHistoryLastRead(history: History) = db.put() .`object`(history) .withPutResolver(HistoryLastReadPutResolver()) .prepare() /** * Updates the history last read. * Inserts history object if not yet in database * @param historyList history object list */ fun updateHistoryLastRead(historyList: List<History>) = db.put() .objects(historyList) .withPutResolver(HistoryLastReadPutResolver()) .prepare() fun deleteHistory() = db.delete() .byQuery(DeleteQuery.builder() .table(HistoryTable.TABLE) .build()) .prepare() fun deleteHistoryNoLastRead() = db.delete() .byQuery(DeleteQuery.builder() .table(HistoryTable.TABLE) .where("${HistoryTable.COL_LAST_READ} = ?") .whereArgs(0) .build()) .prepare() fun getHistory(id: Long) = db.get() .`object`(History::class.java) .withQuery(Query.builder() .table(HistoryTable.TABLE) .where("${HistoryTable.COL_ID} = ?") .whereArgs(id) .build()) .prepare() }
apache-2.0
d45f053f1a278b6436c795f046bd08c1
35.885417
81
0.597289
4.778677
false
false
false
false
MaTriXy/gradle-play-publisher-1
play/plugin/src/main/kotlin/com/github/triplet/gradle/play/tasks/PublishApk.kt
1
4166
package com.github.triplet.gradle.play.tasks import com.github.triplet.gradle.common.utils.safeCreateNewFile import com.github.triplet.gradle.play.PlayPublisherExtension import com.github.triplet.gradle.play.tasks.internal.PublishableTrackExtensionOptions import com.github.triplet.gradle.play.tasks.internal.UploadArtifactTaskBase import com.github.triplet.gradle.play.tasks.internal.workers.UploadArtifactWorkerBase import com.github.triplet.gradle.play.tasks.internal.workers.copy import com.github.triplet.gradle.play.tasks.internal.workers.paramsForBase import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.SkipWhenEmpty import org.gradle.api.tasks.TaskAction import org.gradle.kotlin.dsl.submit import org.gradle.kotlin.dsl.support.serviceOf import org.gradle.workers.WorkerExecutor import java.io.File import javax.inject.Inject internal abstract class PublishApk @Inject constructor( extension: PlayPublisherExtension, appId: String ) : UploadArtifactTaskBase(extension, appId), PublishableTrackExtensionOptions { @get:PathSensitive(PathSensitivity.RELATIVE) @get:SkipWhenEmpty @get:InputFiles internal abstract val apks: ConfigurableFileCollection // This directory isn't used, but it's needed for up-to-date checks to work @Suppress("MemberVisibilityCanBePrivate", "unused") @get:Optional @get:OutputDirectory protected val outputDir = null @TaskAction fun publishApks() { project.delete(temporaryDir) // Make sure previous executions get cleared out project.serviceOf<WorkerExecutor>().noIsolation().submit(Processor::class) { paramsForBase(this) apkFiles.set(apks) uploadResults.set(temporaryDir) } } abstract class Processor @Inject constructor( private val executor: WorkerExecutor ) : UploadArtifactWorkerBase<Processor.Params>() { override fun upload() { for (apk in parameters.apkFiles.get()) { executor.noIsolation().submit(ApkUploader::class) { parameters.copy(this) apkFile.set(apk) uploadResults.set(parameters.uploadResults) } } executor.await() val versions = parameters.uploadResults.asFileTree.map { it.name.toLong() }.sorted() edits.publishApk( versions, parameters.skippedMarker.get().asFile.exists(), config.track, config.releaseStatus, findReleaseName(config.track), findReleaseNotes(config.track), config.userFraction, config.updatePriority, config.retainArtifacts ) } interface Params : ArtifactUploadingParams { val apkFiles: ListProperty<File> val uploadResults: DirectoryProperty } } abstract class ApkUploader : UploadArtifactWorkerBase<ApkUploader.Params>() { init { commit = false } override fun upload() { val apkFile = parameters.apkFile.get().asFile val versionCode = edits.uploadApk( apkFile, parameters.mappingFile.orNull?.asFile, config.resolutionStrategy, config.retainMainObb, config.retainPatchObb ) ?: return parameters.uploadResults.get().file(versionCode.toString()).asFile.safeCreateNewFile() } interface Params : ArtifactUploadingParams { val apkFile: RegularFileProperty val uploadResults: DirectoryProperty } } }
mit
60fcb66a6a348840066a47299ad3f175
36.196429
98
0.664666
4.9773
false
true
false
false
square/sqldelight
extensions/rxjava2-extensions/src/test/kotlin/com/squareup/sqldelight/runtime/rx/TestDb.kt
1
3971
package com.squareup.sqldelight.runtime.rx import com.squareup.sqldelight.Query import com.squareup.sqldelight.TransacterImpl import com.squareup.sqldelight.db.SqlCursor import com.squareup.sqldelight.db.SqlDriver import com.squareup.sqldelight.internal.copyOnWriteList import com.squareup.sqldelight.runtime.rx.TestDb.Companion.TABLE_EMPLOYEE import com.squareup.sqldelight.runtime.rx.TestDb.Companion.TABLE_MANAGER import com.squareup.sqldelight.sqlite.driver.JdbcSqliteDriver import com.squareup.sqldelight.sqlite.driver.JdbcSqliteDriver.Companion.IN_MEMORY class TestDb( val db: SqlDriver = JdbcSqliteDriver(IN_MEMORY) ) : TransacterImpl(db) { val queries = mutableMapOf<String, MutableList<Query<*>>>() var aliceId: Long = 0 var bobId: Long = 0 var eveId: Long = 0 init { db.execute(null, "PRAGMA foreign_keys=ON", 0) db.execute(null, CREATE_EMPLOYEE, 0) aliceId = employee(Employee("alice", "Alice Allison")) bobId = employee(Employee("bob", "Bob Bobberson")) eveId = employee(Employee("eve", "Eve Evenson")) db.execute(null, CREATE_MANAGER, 0) manager(eveId, aliceId) } fun <T : Any> createQuery(key: String, query: String, mapper: (SqlCursor) -> T): Query<T> { return object : Query<T>(queries.getOrPut(key, { copyOnWriteList() }), mapper) { override fun execute(): SqlCursor { return db.executeQuery(null, query, 0) } } } fun notify(key: String) { queries[key]?.let { notifyQueries(key.hashCode(), { it }) } } fun close() { db.close() } fun employee(employee: Employee): Long { db.execute( 0, """ |INSERT OR FAIL INTO $TABLE_EMPLOYEE (${Employee.USERNAME}, ${Employee.NAME}) |VALUES (?, ?) |""".trimMargin(), 2 ) { bindString(1, employee.username) bindString(2, employee.name) } notify(TABLE_EMPLOYEE) return db.executeQuery(2, "SELECT last_insert_rowid()", 0) .apply { next() } .getLong(0)!! } fun manager( employeeId: Long, managerId: Long ): Long { db.execute( 1, """ |INSERT OR FAIL INTO $TABLE_MANAGER (${Manager.EMPLOYEE_ID}, ${Manager.MANAGER_ID}) |VALUES (?, ?) |""".trimMargin(), 2 ) { bindLong(1, employeeId) bindLong(2, managerId) } notify(TABLE_MANAGER) return db.executeQuery(2, "SELECT last_insert_rowid()", 0) .apply { next() } .getLong(0)!! } companion object { const val TABLE_EMPLOYEE = "employee" const val TABLE_MANAGER = "manager" val CREATE_EMPLOYEE = """ |CREATE TABLE $TABLE_EMPLOYEE ( | ${Employee.ID} INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, | ${Employee.USERNAME} TEXT NOT NULL UNIQUE, | ${Employee.NAME} TEXT NOT NULL |) """.trimMargin() val CREATE_MANAGER = """ |CREATE TABLE $TABLE_MANAGER ( | ${Manager.ID} INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, | ${Manager.EMPLOYEE_ID} INTEGER NOT NULL UNIQUE REFERENCES $TABLE_EMPLOYEE(${Employee.ID}), | ${Manager.MANAGER_ID} INTEGER NOT NULL REFERENCES $TABLE_EMPLOYEE(${Employee.ID}) |) """.trimMargin() } } object Manager { const val ID = "id" const val EMPLOYEE_ID = "employee_id" const val MANAGER_ID = "manager_id" val SELECT_MANAGER_LIST = """ |SELECT e.${Employee.NAME}, m.${Employee.NAME} |FROM $TABLE_MANAGER AS manager |JOIN $TABLE_EMPLOYEE AS e |ON manager.$EMPLOYEE_ID = e.${Employee.ID} |JOIN $TABLE_EMPLOYEE AS m |ON manager.$MANAGER_ID = m.${Employee.ID} |""".trimMargin() } data class Employee(val username: String, val name: String) { companion object { const val ID = "id" const val USERNAME = "username" const val NAME = "name" const val SELECT_EMPLOYEES = "SELECT $USERNAME, $NAME FROM $TABLE_EMPLOYEE" @JvmField val MAPPER = { cursor: SqlCursor -> Employee(cursor.getString(0)!!, cursor.getString(1)!!) } } }
apache-2.0
e5ee81e35f2d2ffae45014ea7ec68508
27.568345
99
0.643918
3.739171
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/app/src/main/java/cx/ring/settings/pluginssettings/PluginsListSettingsFragment.kt
1
7266
package cx.ring.settings.pluginssettings import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.OnBackPressedCallback import androidx.fragment.app.Fragment import com.google.android.material.snackbar.Snackbar import cx.ring.R import cx.ring.account.JamiAccountSummaryFragment import cx.ring.client.HomeActivity import cx.ring.databinding.FragPluginsListSettingsBinding import cx.ring.plugins.PluginUtils.getInstalledPlugins import cx.ring.plugins.PluginUtils.loadPlugin import cx.ring.plugins.PluginUtils.unloadPlugin import cx.ring.settings.pluginssettings.PluginsListAdapter.PluginListItemListener import cx.ring.utils.AndroidFileUtils.getCacheFile import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import net.jami.daemon.JamiService import java.io.File import java.io.IOException class PluginsListSettingsFragment : Fragment(), PluginListItemListener { private val mOnBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(false) { override fun handleOnBackPressed() { this.isEnabled = false val fragment = parentFragment as JamiAccountSummaryFragment? fragment?.popBackStack() } } private var binding: FragPluginsListSettingsBinding? = null private var mAdapter: PluginsListAdapter? = null private val mCompositeDisposable = CompositeDisposable() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = FragPluginsListSettingsBinding.inflate(inflater, container, false) // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView binding!!.pluginsList.setHasFixedSize(true) // specify an adapter (see also next example) mAdapter = PluginsListAdapter(getInstalledPlugins(binding!!.pluginsList.context), this) binding!!.pluginsList.adapter = mAdapter //Fab binding!!.pluginsListSettingsFab.setOnClickListener { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) intent.addCategory(Intent.CATEGORY_OPENABLE) intent.type = "*/*" startActivityForResult(intent, ARCHIVE_REQUEST_CODE) } return binding!!.root } override fun onResume() { mOnBackPressedCallback.isEnabled = true super.onResume() } override fun onAttach(context: Context) { super.onAttach(context) requireActivity().onBackPressedDispatcher.addCallback(this, mOnBackPressedCallback) } /** * Implements PluginListItemListener.onPluginItemClicked which is called when we click on * a plugin list item * @param pluginDetails instance of a plugin details that is sent to PluginSettingsFragment */ override fun onPluginItemClicked(pluginDetails: PluginDetails) { (requireActivity() as HomeActivity).gotToPluginSettings(pluginDetails) } /** * Implements PluginListItemListener.onPluginEnabled which is called when the checkbox * associated with the plugin list item is called * @param pluginDetails instance of a plugin details that is sent to PluginSettingsFragment */ override fun onPluginEnabled(pluginDetails: PluginDetails) { if (pluginDetails.isEnabled) { pluginDetails.isEnabled = loadPlugin(pluginDetails.rootPath) } else { unloadPlugin(pluginDetails.rootPath) } val status = if (pluginDetails.isEnabled) "ON" else "OFF" Toast.makeText( requireContext(), pluginDetails.name + " " + status, Toast.LENGTH_SHORT ).show() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == ARCHIVE_REQUEST_CODE && resultCode == Activity.RESULT_OK) { if (data != null) { val uri = data.data if (uri != null) { installPluginFromUri(uri, false) } } } } @Throws(IOException::class) private fun installPluginFile(pluginFile: File, force: Boolean): String { val i = JamiService.installPlugin(pluginFile.absolutePath, force) if (!pluginFile.delete()) { Log.e(TAG, "Plugin Jpl file in the cache not freed") } return when (i) { 0 -> pluginFile.name 100 -> throw IOException( resources .getString( R.string.plugin_same_version_exception, pluginFile.name ) ) 200 -> throw IOException( resources .getString( R.string.plugin_recent_version_exception, pluginFile.name ) ) else -> throw IOException( resources .getString( R.string.plugin_install_failure, pluginFile.name ) ) } } private fun installPluginFromUri(uri: Uri, force: Boolean) { mCompositeDisposable.add( getCacheFile(requireContext(), uri) .observeOn(AndroidSchedulers.mainThread()) .map { file: File -> installPluginFile(file, force) } .subscribe({ filename: String -> val plugin = filename.split(".jpl".toRegex()).toTypedArray() val availablePlugins = getInstalledPlugins(requireContext()) for (availablePlugin in availablePlugins) { if (availablePlugin.name == plugin[0]) { availablePlugin.isEnabled = true onPluginEnabled(availablePlugin) } } mAdapter!!.updatePluginsList(getInstalledPlugins(requireContext())) Toast.makeText(requireContext(), "Plugin: $filename successfully installed", Toast.LENGTH_LONG) .show() mCompositeDisposable.dispose() }) { e: Throwable -> if (binding != null) { val sb = Snackbar.make(binding!!.listLayout, "" + e.message, Snackbar.LENGTH_LONG) sb.setAction(R.string.plugin_force_install) { v: View? -> installPluginFromUri(uri, true) } sb.show() } }) } override fun onDestroyView() { binding = null super.onDestroyView() } override fun onDestroy() { super.onDestroy() mCompositeDisposable.dispose() } companion object { val TAG = PluginsListSettingsFragment::class.java.simpleName private const val ARCHIVE_REQUEST_CODE = 42 } }
gpl-3.0
f58266928399ee6d8d82f819daf3781e
38.281081
115
0.628682
5.28821
false
false
false
false
pyranid/pyranid
src/main/java/com/pyranid/KotlinDefaultResultSetMapper.kt
1
13378
package com.pyranid import java.math.BigDecimal import java.math.BigInteger import java.sql.ResultSet import java.sql.Timestamp import java.time.* import java.util.* import java.util.concurrent.ConcurrentHashMap import kotlin.reflect.KClass import kotlin.reflect.KFunction import kotlin.reflect.KParameter import kotlin.reflect.full.functions import kotlin.reflect.full.isSuperclassOf import kotlin.reflect.full.primaryConstructor /** * @author Casey Watson * @since 1.0.16 */ /** * Creates a {@code ResultSetMapper} for the given {@code databaseType} and {@code instanceProvider}. * * @param databaseType * the type of database we're working with * @param instanceProvider * instance-creation factory, used to instantiate resultset row objects as needed * @param timeZone * the timezone to use when working with {@link java.sql.Timestamp} and similar values * @since 1.0.16 */ open class KotlinDefaultResultSetMapper(private val javaDefaultResultSetMapper: ResultSetMapper, private val databaseType: DatabaseType, private val instanceProvider: InstanceProvider, private val timeZone: ZoneId) : ResultSetMapper { /** * Creates a {@code ResultSetMapper} for the given {@code databaseType} and {@code instanceProvider}. *@param javaDefaultResultSetMapper * ResultSetMapper to use in the case the requested class is a non-data class, such as a JavaBean * @param databaseType * the type of database we're working with * @param instanceProvider * instance-creation factory, used to instantiate resultset row objects as needed * @since 1.0.16 */ constructor(javaDefaultResultSetMapper: ResultSetMapper, databaseType: DatabaseType, instanceProvider: InstanceProvider) : this(javaDefaultResultSetMapper, databaseType, instanceProvider, ZoneId.systemDefault()) private val timeZoneCalendar = Calendar.getInstance(TimeZone.getTimeZone(timeZone)) private val columnNamesForParameterCache = ConcurrentHashMap<KClass<out Any>, Map<String, Set<String>>>() private val parameterNamesForDataClassCache = ConcurrentHashMap<KClass<out Any>, CtorParameters>() private val kotlinClassForJavaClass = ConcurrentHashMap<Class<out Any>, KClass<out Any>>() data class CtorParameters(val ctor: KFunction<Any>, val ctorParameters: List<ParameterMetadata>) data class ParameterMetadata(val name: String, val parameter: KParameter, val parameterType: KClass<*>) override fun <T : Any> map(resultSet: ResultSet, resultClass: Class<T>): T { val klass = kotlinClassForJavaClass.computeIfAbsent(resultClass) { Class.forName(resultClass.name).kotlin } return if (klass.isData) { mapKotlinDataClass(resultSet, klass) } else { javaDefaultResultSetMapper.map(resultSet, resultClass) } } /** * Attempts to map the current {@code resultSet} row to an instance of {@code resultClass}, which should be a * Data class. * <p> * The {@code resultClass} instance will be created via {@link #callByArgs()}. * * @param <T> * result instance type token * @param resultSet * provides raw row data to pull from * @param resultClass * the type of instance to map to * @return the result of the mapping * @throws Exception * if an error occurs during mapping */ protected fun <T : Any> mapKotlinDataClass(resultSet: ResultSet, resultClass: KClass<out Any>): T { val metadata = resultSet.metaData val columnLabels = (1..metadata.columnCount).map { metadata.getColumnLabel(it) } val columnLabelsToValues = columnLabels .map { normalizeColumnLabel(it) to mapResultSetValueToObject(resultSet, it) } .toMap() val (ctor, ctorParameters) = parameterNamesForDataClassCache.computeIfAbsent(resultClass) { dataClass -> val ctor = dataClass.primaryConstructor ?: throw DatabaseException("Missing primary constructor for class ${resultClass.simpleName}") val parameterNames: List<ParameterMetadata> = ctor.parameters.map { parameter -> if (parameter.name == null) { throw DatabaseException("Parameter was not readable for ${dataClass.simpleName}. Examples of nameless parameters include this instance for member functions, extension receiver for extension functions or properties, parameters of Java methods compiled without the debug information, and others.") } return@map ParameterMetadata(parameter.name!!, parameter, parameter.type.classifier as KClass<*>) }.toList() return@computeIfAbsent CtorParameters(ctor, parameterNames) } val columnNamesForParameters: Map<String, Set<String>> = columnNamesForParameterCache.computeIfAbsent(resultClass) { ctorParameters.map { parameter -> parameter.name to databaseColumnNamesForParameterName(parameter.name) }.toMap() } val callByArgs = ctorParameters .map { ctorParameter -> val possibleColumnNamesForParameter: Set<String> = columnNamesForParameters[ctorParameter.name] ?: throw DatabaseException("Unable to find columns for parameter name ${ctorParameter.name}") return@map ctorParameter.parameter to columnLabelsToValues .filter { columnLabelValues -> possibleColumnNamesForParameter.contains(columnLabelValues.key) && columnLabelValues.value != null }.map { convertResultSetValueToPropertyType(it.value!!, ctorParameter.parameterType) ?: throw DatabaseException("Property ${it.key} of ${resultClass} has a write " + "method of type ${ctorParameter.parameterType.simpleName}, " + "but the ResultSet type ${it.value!!::class.simpleName} does not match. " + "Consider creating your own ${KotlinDefaultResultSetMapper::class.simpleName} and " + "overriding convertResultSetValueToPropertyType() to detect instances of " + "${it.value!!::class.simpleName} and convert them to ${ctorParameter.parameterType.simpleName}") }.firstOrNull() }.filter { it.second != null } .toMap() try { return ctor.callBy(callByArgs) as T } catch (e :Exception){ throw DatabaseException("Unable to instantiate class ${resultClass.simpleName} with parameters and arguments ${callByArgs.map{it.key.name to it.value}.joinToString(separator = ", "){"${it.first}: ${it.second}"}}", e) } } /** * Massages a {@link ResultSet#getObject(String)} value to match the given {@code propertyType}. * <p> * For example, the JDBC driver might give us {@link java.sql.Timestamp} but our corresponding JavaBean field is of * type {@link java.util.Date}, so we need to manually convert that ourselves. * * @param resultSetValue * the value returned by {@link ResultSet#getObject(String)} * @param propertyType * the JavaBean property type we'd like to map {@code resultSetValue} to * @return a representation of {@code resultSetValue} that is of type {@code propertyType} */ protected fun convertResultSetValueToPropertyType(resultSetValue: Any, propertyType: KClass<*>): Any? { if (resultSetValue is BigDecimal) { val bigDecimal = resultSetValue if (BigDecimal::class.isSuperclassOf(propertyType)) return bigDecimal if (BigInteger::class.isSuperclassOf(propertyType)) return bigDecimal.toBigInteger() } if (resultSetValue is BigInteger) { val bigInteger = resultSetValue if (BigDecimal::class.isSuperclassOf(propertyType)) return BigDecimal(bigInteger) if (BigInteger::class.isSuperclassOf(propertyType)) return bigInteger } if (resultSetValue is Number) { val number = resultSetValue if (Byte::class.isSuperclassOf(propertyType)) return number.toByte() if (Short::class.isSuperclassOf(propertyType)) return number.toShort() if (Int::class.isSuperclassOf(propertyType)) return number.toInt() if (Long::class.isSuperclassOf(propertyType)) return number.toLong() if (Float::class.isSuperclassOf(propertyType)) return number.toFloat() if (Double::class.isSuperclassOf(propertyType)) return number.toDouble() if (BigDecimal::class.isSuperclassOf(propertyType)) return BigDecimal(number.toDouble()) if (BigInteger::class.isSuperclassOf(propertyType)) return BigDecimal(number.toDouble()).toBigInteger() } else if (resultSetValue is Timestamp) { val date = resultSetValue if (Date::class.isSuperclassOf(propertyType)) return date if (Instant::class.isSuperclassOf(propertyType)) return date.toInstant() if (LocalDate::class.isSuperclassOf(propertyType)) return date.toInstant().atZone(timeZone).toLocalDate() if (LocalDateTime::class.isSuperclassOf(propertyType)) return date.toLocalDateTime() } else if (resultSetValue is java.sql.Date) { val date = resultSetValue if (Date::class.isSuperclassOf(propertyType)) return date if (Instant::class.isSuperclassOf(propertyType)) return date.toInstant() if (LocalDate::class.isSuperclassOf(propertyType)) return date.toLocalDate() if (LocalDateTime::class.isSuperclassOf(propertyType)) return LocalDateTime.ofInstant(date.toInstant(), timeZone) } else if (resultSetValue is java.sql.Time) { if (LocalTime::class.isSuperclassOf(propertyType)) return resultSetValue.toLocalTime() } else if (ZoneId::class.isSuperclassOf(propertyType)) { return ZoneId.of(resultSetValue.toString()) } else if (TimeZone::class.isSuperclassOf(propertyType)) { return TimeZone.getTimeZone(resultSetValue.toString()) } else if (Locale::class.isSuperclassOf(propertyType)) { return Locale.forLanguageTag(resultSetValue.toString()) } else if (Enum::class.isSuperclassOf(propertyType)) { return propertyType.functions.first { func -> func.name == "valueOf" }.call(resultSetValue) } else if ("org.postgresql.util.PGobject" == resultSetValue.javaClass.name) { val pgObject = resultSetValue as org.postgresql.util.PGobject return pgObject.value } return resultSetValue } /** * Massages a Data Class property name to match standard database column name (camelCase -> camel_case). * <p> * Uses {@link #normalizationLocale()} to perform case-changing. * <p> * There may be multiple database column name mappings, for example property {@code address1} might map to both * {@code address1} and {@code address_1} column names. * * @param propertyName * the Data Class property name to massage * @return the column names that match the Data Class property name */ protected fun databaseColumnNamesForParameterName(propertyName: String): Set<String> { val normalizedPropertyNames: MutableSet<String> = HashSet(2) // Converts camelCase to camel_case val camelCaseRegex = "([a-z])([A-Z]+)" val replacement = "$1_$2" val normalizedPropertyName = propertyName.replace(camelCaseRegex.toRegex(), replacement).toLowerCase(normalizationLocale()) normalizedPropertyNames.add(normalizedPropertyName) // Converts address1 to address_1 val letterFollowedByNumberRegex = "(\\D)(\\d)" val normalizedNumberPropertyName = normalizedPropertyName.replace(letterFollowedByNumberRegex.toRegex(), replacement) normalizedPropertyNames.add(normalizedNumberPropertyName) return normalizedPropertyNames.toSet() } protected fun normalizeColumnLabel(columnLabel: String): String { return columnLabel.toLowerCase(normalizationLocale()) } protected fun normalizationLocale(): Locale { return Locale.ENGLISH } protected fun mapResultSetValueToObject(resultSet: ResultSet, columnLabel: String): Any? { val obj = resultSet.getObject(columnLabel) ?: return null return when (obj) { is java.sql.Timestamp -> resultSet.getTimestamp(columnLabel, timeZoneCalendar) is java.sql.Date -> resultSet.getDate(columnLabel, timeZoneCalendar) is java.sql.Time -> resultSet.getTime(columnLabel, timeZoneCalendar) else -> obj } } }
apache-2.0
ec674dc8468b3595a5b5ecc7d542404c
50.65251
323
0.654134
5.080896
false
false
false
false
alt236/Under-the-Hood---Android
app/src/main/java/aws/apps/underthehood/ui/sharing/SharePayloadFactory.kt
1
2909
package aws.apps.underthehood.ui.sharing import android.content.res.Resources import androidx.annotation.StringRes import aws.apps.underthehood.R import aws.apps.underthehood.time.TimeFormatter import uk.co.alt236.underthehood.commandrunner.model.CommandOutputGroup import uk.co.alt236.underthehood.commandrunner.model.Result class SharePayloadFactory(private val resources: Resources) { private val separator = resources.getString(R.string.seperator_identifier) private val timeFormat = TimeFormatter() fun create(result: Result): SharePayload { val timestamp = timeFormat.getIsoDateTimeFileSafe(result.timestamp) val fileName = "deviceinfo_$timestamp.txt" val subject = "${getString(R.string.text_under_the_hood)} @ $timestamp" val text = createText(subject, result) return SharePayload(fileName = fileName, subject = subject, text = text) } private fun createText(subject: String, result: Result): String { val sb = StringBuilder() sb.appendLn(subject) appendData(sb, R.string.export_section_device_info, result.deviceinfo) sb.append("---------------------------------\n\n") appendData(sb, R.string.export_section_hardware_info, result.hardwareData) appendData(sb, R.string.export_section_ip_route_info, result.ipRouteData) appendData(sb, R.string.export_section_proc_info, result.procData) appendData(sb, R.string.export_section_ps_info, result.psData) appendData(sb, R.string.export_section_netstat_info, result.netstatData) appendData(sb, R.string.export_section_sys_prop, result.sysPropData) appendData(sb, R.string.export_section_other_info, result.otherData) sb.append("\n\n---------------------------------") return sb.toString().trim { it <= ' ' } } private fun appendData(sb: StringBuilder, @StringRes sectionLabel: Int, payload: String) { if (payload.isEmpty()) { return } sb.appendLn(getString(sectionLabel)) sb.appendLn(payload) } private fun appendData(sb: StringBuilder, @StringRes sectionLabel: Int, payload: List<CommandOutputGroup>) { if (payload.isEmpty()) { return } sb.appendLn(getString(sectionLabel)) for (group in payload) { if (group.name.isNotEmpty()) { sb.appendLn(separator + group.name) } for (command in group.commandOutputs) { sb.appendLn(command.commandWithPrompt) sb.appendLn(command.output) } } } private fun getString(@StringRes id: Int): String { return resources.getString(id) } private fun StringBuilder.appendLn(input: String): StringBuilder { this.append(input) this.append('\n') return this } }
apache-2.0
de1a10e6371b5eecb523db6414256aa0
34.925926
112
0.643176
4.16166
false
false
false
false
elect86/modern-jogl-examples
src/main/kotlin/main/tut08/interpolation.kt
2
6682
package main.tut08 import com.jogamp.newt.event.KeyEvent import com.jogamp.opengl.GL.* import com.jogamp.opengl.GL2ES3.GL_COLOR import com.jogamp.opengl.GL2ES3.GL_DEPTH import com.jogamp.opengl.GL3 import glNext.* import glm.* import glm.mat.Mat4 import glm.quat.Quat import main.framework.Framework import main.framework.component.Mesh import uno.glm.MatrixStack import uno.glsl.programOf import uno.time.Timer /** * Created by GBarbieri on 17.03.2017. */ fun main(args: Array<String>) { Interpolation_().setup("Tutorial 08 - Interpolation") } class Interpolation_ : Framework() { lateinit var ship: Mesh var theProgram = 0 var modelToCameraMatrixUnif = 0 var cameraToClipMatrixUnif = 0 var baseColorUnif = 0 val frustumScale = calcFrustumScale(20f) fun calcFrustumScale(fovDeg: Float) = 1.0f / glm.tan(fovDeg.rad / 2.0f) val cameraToClipMatrix = Mat4(0.0f) val orient = Orientation() override fun init(gl: GL3) = with(gl) { initializeProgram(gl) ship = Mesh(gl, javaClass, "tut08/Ship.xml") glEnable(GL_CULL_FACE) glCullFace(GL_BACK) glFrontFace(GL_CW) glEnable(GL_DEPTH_TEST) glDepthMask(true) glDepthFunc(GL_LEQUAL) glDepthRangef(0.0f, 1.0f) } fun initializeProgram(gl: GL3) = with(gl) { theProgram = programOf(gl, javaClass, "tut08", "pos-color-local-transform.vert", "color-mult-uniform.frag") modelToCameraMatrixUnif = glGetUniformLocation(theProgram, "modelToCameraMatrix") cameraToClipMatrixUnif = glGetUniformLocation(theProgram, "cameraToClipMatrix") baseColorUnif = glGetUniformLocation(theProgram, "baseColor") val zNear = 1.0f val zFar = 600.0f cameraToClipMatrix[0].x = frustumScale cameraToClipMatrix[1].y = frustumScale cameraToClipMatrix[2].z = (zFar + zNear) / (zNear - zFar) cameraToClipMatrix[2].w = -1.0f cameraToClipMatrix[3].z = (2 * zFar * zNear) / (zNear - zFar) glUseProgram(theProgram) glUniformMatrix4f(cameraToClipMatrixUnif, cameraToClipMatrix) glUseProgram() } override fun display(gl: GL3) = with(gl) { orient.updateTime() glClearBufferf(GL_COLOR, 0) glClearBufferf(GL_DEPTH) val matrixStack = MatrixStack() .translate(0.0f, 0.0f, -200.0f) .applyMatrix(orient.getOrient().toMat4()) glUseProgram(theProgram) matrixStack .scale(3.0f, 3.0f, 3.0f) .rotateX(-90.0f) //Set the base color for this object. glUniform4f(baseColorUnif, 1.0f) glUniformMatrix4f(modelToCameraMatrixUnif, matrixStack.top()) ship.render(gl, "tint") glUseProgram() } override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) { cameraToClipMatrix[0].x = frustumScale * (h / w.f) cameraToClipMatrix[1].y = frustumScale glUseProgram(theProgram) glUniformMatrix4f(cameraToClipMatrixUnif, cameraToClipMatrix) glUseProgram() glViewport(w, h) } override fun keyPressed(e: KeyEvent) { when (e.keyCode) { KeyEvent.VK_ESCAPE -> quit() KeyEvent.VK_SPACE -> { val slerp = orient.toggleSlerp() println(if (slerp) "Slerp" else "Lerp") } } orientKeys.indices.filter { e.keyCode == orientKeys[it] }.forEach { applyOrientation(it) } } fun applyOrientation(index: Int) { if (!orient.isAnimating) orient.animateToOrient(index) } val orientKeys = shortArrayOf( KeyEvent.VK_Q, KeyEvent.VK_W, KeyEvent.VK_E, KeyEvent.VK_R, KeyEvent.VK_T, KeyEvent.VK_Y, KeyEvent.VK_U) override fun end(gl: GL3) =with(gl){ glDeleteProgram(theProgram) ship.dispose(gl) } inner class Orientation { var isAnimating = false var currentOrient = 0 var slerp = false val anim = Animation() fun toggleSlerp(): Boolean { slerp = !slerp return slerp } fun getOrient() = if (isAnimating) anim.getOrient(orients[currentOrient], slerp) else orients[currentOrient] fun updateTime() { if (isAnimating) { val isFinished = anim.updateTime() if (isFinished) { isAnimating = false currentOrient = anim.finalX } } } fun animateToOrient(destination: Int) { if (currentOrient == destination) { return } anim.startAnimation(destination, 1.0f) isAnimating = true } inner class Animation { var finalX = 0 private set lateinit var currTimer: Timer fun updateTime() = currTimer.update() fun getOrient(initial: Quat, slerp: Boolean) = if (slerp) slerp(initial, orients[finalX], currTimer.getAlpha()) else lerp(initial, orients[finalX], currTimer.getAlpha()) fun startAnimation(destination: Int, duration: Float) { finalX = destination currTimer = Timer(Timer.Type.Single, duration) } } } fun slerp(v0: Quat, v1: Quat, alpha: Float): Quat { var dot = v0 dot v1 val DOT_THRESHOLD = 0.9995f if (dot > DOT_THRESHOLD) return lerp(v0, v1, alpha) dot = glm.clamp(dot, -1.0f, 1.0f) val theta0 = glm.acos(dot) val theta = theta0 * alpha val v2 = v1 - v0 * dot v2.normalize_() return v0 * theta.cos + v2 * theta.sin } // TODO check lerp thinkness fun lerp(v0: Quat, v1: Quat, alpha: Float): Quat { val start = v0.vectorize() val end = v1.vectorize() val interp = glm.mix(start, end, alpha) println("alpha: $alpha, $interp") interp.normalize_() return Quat(interp) } val orients = arrayOf( Quat(0.7071f, 0.7071f, 0.0f, 0.0f), Quat(0.5f, 0.5f, -0.5f, 0.5f), Quat(-0.4895f, -0.7892f, -0.3700f, -0.02514f), Quat(0.4895f, 0.7892f, 0.3700f, 0.02514f), Quat(0.3840f, -0.1591f, -0.7991f, -0.4344f), Quat(0.5537f, 0.5208f, 0.6483f, 0.0410f), Quat(0.0f, 0.0f, 1.0f, 0.0f)) }
mit
5c8b8b563fac2810a6f5873f9a4eaa96
25.728
115
0.567794
3.869137
false
false
false
false
universum-studios/gradle_github_plugin
plugin/src/labels/kotlin/universum/studios/gradle/github/label/task/CreateLabelsTask.kt
1
4115
/* * ************************************************************************************************* * Copyright 2017 Universum Studios * ************************************************************************************************* * 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 universum.studios.gradle.github.label.task import universum.studios.gradle.github.label.data.model.Label import universum.studios.gradle.github.label.data.model.LabelModelMappers import universum.studios.gradle.github.label.extension.LabelItemExtension import universum.studios.gradle.github.task.specification.TaskSpecification /** * A [LabelsTask] implementation which creates a collection of specified labels on the GitHub * server for the specified [repository]. * * @author Martin Albedinsky * @since 1.0 */ open class CreateLabelsTask : LabelsTask() { /* * Companion =================================================================================== */ /** */ companion object { /** * Specification for [CreateLabelsTask]. */ val SPECIFICATION = TaskSpecification( type = CreateLabelsTask::class.java, name = "githubCreateLabels", description = "Creates specified issue labels for the project's GitHub repository." ) } /* * Interface =================================================================================== */ /* * Members ===================================================================================== */ /** * Collection of labels that should be created. */ var labels = emptyList<Label>() /* * Constructors ================================================================================ */ /* * Methods ===================================================================================== */ /* */ override fun onPerform() { val repository = getRepository() if (labels.isNotEmpty()) { project.logger.info("Creating labels for '${repository.path()}' ...") val result = getLabelManager().createLabels(labels) project.logger.quiet("Successfully created labels for '${repository.path()}' in count '$result'.") } else { project.logger.quiet("No labels specified for '${repository.path()}' to be created.") } } /* * Inner classes =============================================================================== */ /** * A [LabelsTask.BasicConfigurator] implementation that may be used for configuration of * [CreateLabelsTask]s based on the supplied collection of *label* items. * * @author Martin Albedinsky * @since 1.0 * * @property labels Collection of label items for which to create issue labels. * @constructor Creates a new instance of Configurator with the specified *labels*. */ class Configurator(val labels: Collection<LabelItemExtension>) : BasicConfigurator<CreateLabelsTask>() { /* */ override fun configureTask(task: CreateLabelsTask): CreateLabelsTask { super.configureTask(task) task.labels = labels.map { LabelModelMappers.LABEL_ITEM_TO_LABEL.map(it) } return task } } }
apache-2.0
b566a767843ba82bf96f336fbd227d39
36.081081
110
0.496962
5.803949
false
true
false
false
ethauvin/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/internal/JUnitRunner.kt
2
1214
package com.beust.kobalt.internal import com.beust.kobalt.TestConfig import com.beust.kobalt.api.IClasspathDependency import com.beust.kobalt.api.KobaltContext import com.beust.kobalt.api.Project import com.beust.kobalt.maven.DependencyManager import com.google.inject.Inject import java.lang.reflect.Modifier import java.net.URLClassLoader open class JUnitRunner() : GenericTestRunner() { override val mainClass = "org.junit.runner.JUnitCore" override val annotationPackage = "org.junit" override val dependencyName = "junit" override val runnerName = "JUnit 4" override fun args(project: Project, context: KobaltContext, classpath: List<IClasspathDependency>, testConfig: TestConfig) = findTestClasses(project, context, testConfig) @Inject lateinit var dependencyManager: DependencyManager override fun filterTestClasses(project: Project, context: KobaltContext, classes: List<String>) : List<String> { val deps = dependencyManager.testDependencies(project, context) val cl = URLClassLoader(deps.map { it.jarFile.get().toURI().toURL() }.toTypedArray()) return classes.filter { !Modifier.isAbstract(cl.loadClass(it).modifiers) } } }
apache-2.0
9c7015ee695972241d059a920819eff1
36.9375
116
0.757825
4.304965
false
true
false
false
Geobert/Efficio
app/src/main/kotlin/fr/geobert/efficio/ItemEditorActivity.kt
1
7876
package fr.geobert.efficio import android.app.* import android.content.* import android.database.Cursor import android.os.Bundle import android.support.design.widget.Snackbar import android.util.Log import android.view.* import android.view.animation.AnimationUtils import android.widget.* import fr.geobert.efficio.data.* import fr.geobert.efficio.db.TaskTable import fr.geobert.efficio.dialog.DeleteConfirmationDialog import fr.geobert.efficio.misc.* import kotlinx.android.synthetic.main.item_editor.* import kotlin.properties.Delegates class ItemEditorActivity : BaseActivity(), DepartmentManager.DepartmentChoiceListener, LoaderManager.LoaderCallbacks<Cursor>, EditorToolbarTrait, DeleteDialogInterface { private var task: Task by Delegates.notNull() private var origTask: Task by Delegates.notNull() private var depManager: DepartmentManager by Delegates.notNull() private var cursorLoader: CursorLoader? = null companion object { val NEED_WEIGHT_UPDATE = "needUpdateWeight" fun callMe(ctx: Fragment, storeId: Long, task: Task) { val i = Intent(ctx.activity, ItemEditorActivity::class.java) i.putExtra("storeId", storeId) i.putExtra("taskId", task.id) ctx.startActivityForResult(i, 0) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.item_editor) initToolbar(this) setTitle(R.string.change_item_name_and_dep) val extras = intent.extras depManager = DepartmentManager(this, findViewById(R.id.department_layout)!!, extras.getLong("storeId"), this) depManager.request() delete_task_btn.setOnClickListener { onDeleteClicked() } initPeriodWidgets() fetchTask() } private fun initPeriodWidgets() { val adapter = ArrayAdapter.createFromResource(this, R.array.periodicity_choices, android.R.layout.simple_spinner_item) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) period_spinner.adapter = adapter val adapterUnit = ArrayAdapter.createFromResource(this, R.array.periodicity_units, android.R.layout.simple_spinner_item) adapterUnit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) period_unit_spinner.adapter = adapterUnit cancel_custom_period.setOnClickListener { setCustomPeriodContVisibility(false) period_spinner.setSelection(if (task.periodicity != Period.CUSTOM) // avoid being stuck in custom period mode task.periodicity.ordinal else Period.NONE.ordinal) } period_spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) { setCustomPeriodContVisibility(pos == (period_spinner.adapter.count - 1)) } override fun onNothingSelected(arg0: AdapterView<*>) { // nothing } } } private fun setCustomPeriodContVisibility(visible: Boolean) { val fadeIn = AnimationUtils.makeInAnimation(this, false) val fadeOut = AnimationUtils.makeOutAnimation(this, true) if (visible && custom_periodicity_cont.visibility == View.GONE) { period_spinner.startAnimation(fadeOut) period_spinner.visibility = View.GONE custom_periodicity_cont.visibility = View.VISIBLE custom_periodicity_cont.startAnimation(fadeIn) } else if (period_spinner.visibility == View.GONE) { custom_periodicity_cont.startAnimation(fadeOut) custom_periodicity_cont.visibility = View.GONE period_spinner.visibility = View.VISIBLE period_spinner.startAnimation(fadeIn) } } override fun onDeletedConfirmed() { TaskTable.deleteTask(this, task.id) setResult(Activity.RESULT_OK) finish() } private fun onDeleteClicked() { val d = DeleteConfirmationDialog.newInstance(getString(R.string.confirm_delete_task), getString(R.string.delete_task), DELETE_TASK) d.show(fragmentManager, "DeleteConfirmDialog") } private fun fetchTask() { if (cursorLoader == null) loaderManager.initLoader(GET_TASK, intent.extras, this) else loaderManager.restartLoader(GET_TASK, intent.extras, this) } private fun onOkClicked() { if (!fillTask()) { Snackbar.make(my_toolbar, R.string.need_valid_period, Snackbar.LENGTH_SHORT).show() return } if (!task.isEquals(origTask)) { // change department, the item's weight is not relevant anymore val data = Intent() if (task.item.department.id != origTask.item.department.id) { data.putExtra(NEED_WEIGHT_UPDATE, true) data.putExtra("taskId", task.id) } else { data.putExtra(NEED_WEIGHT_UPDATE, false) } TaskTable.updateTask(this, task) setResult(Activity.RESULT_OK, data) } else setResult(Activity.RESULT_CANCELED) finish() } private fun fillTask(): Boolean { task.item.name = item_name_edt.text.trim().toString() when (Period.fromInt(period_spinner.selectedItemPosition)) { Period.NONE -> { task.periodUnit = PeriodUnit.NONE task.period = 0 } Period.CUSTOM -> { task.periodUnit = PeriodUnit.fromInt(period_unit_spinner.selectedItemPosition + 1) try { task.period = period_edt.text.trim().toString().toInt() } catch (e: NumberFormatException) { Log.e("ItemEditorActivity", "error converting toInt: ${period_edt.text}") return false } if (task.period == 1) { period_spinner.setSelection(task.periodUnit.ordinal) setCustomPeriodContVisibility(false) } } else -> { task.periodUnit = PeriodUnit.fromInt(period_spinner.selectedItemPosition) task.period = 1 } } return true } override fun onDepartmentChosen(d: Department) { task.item.department = d setDepName() } private fun setDepName() { dep_name.text = getString(R.string.current_department).format(task.item.department.name) } override fun onMenuItemClick(item: MenuItem): Boolean = when (item.itemId) { R.id.confirm -> consume { onOkClicked() } else -> super.onOptionsItemSelected(item) } override fun onCreateLoader(p0: Int, b: Bundle): Loader<Cursor>? { cursorLoader = TaskTable.getTaskByIdLoader(this, b.getLong("taskId")) return cursorLoader } override fun onLoadFinished(p0: Loader<Cursor>?, data: Cursor) { if (data.count > 0) { data.moveToFirst() task = Task(data) origTask = Task(data) updateUI() } else { // todo should not happen } } private fun updateUI() { item_name_edt.setText(task.item.name) setDepName() period_spinner.setSelection(task.periodicity.ordinal, true) if (task.periodicity == Period.CUSTOM) { period_edt.setText(task.period.toString()) period_unit_spinner.setSelection(task.periodUnit.ordinal) } else { period_edt.setText("2") } } override fun onLoaderReset(p0: Loader<Cursor>?) { // todo } }
gpl-2.0
2185ec842a0a52e320227c4421868c54
37.05314
121
0.627603
4.597782
false
false
false
false
luhaoaimama1/AndroidZone
JavaTest_Zone/src/kotlinHolder扩展/test.kt
2
1933
package kotlinHolder扩展 /** * Created by fuzhipeng on 2019/2/19. */ /** *[2018/8/24] by Zone */ object MathUtils { enum class Linear { OverMax, OverOver; } fun <T : Number, R : Number> linear(srcNow: T, src1: T, src2: T, dst1: R, dst2: R, type: Linear? = Linear.OverMax): R { val radio: Float = when (srcNow) { is Float -> (srcNow.toFloat() - src1.toFloat()) / (src2.toFloat() - src1.toFloat()) is Double -> ((srcNow.toDouble() - src1.toDouble()) / (src2.toDouble() - src1.toDouble())).toFloat() is Int -> ((srcNow.toInt() - src1.toInt()) / (src2.toInt() - src1.toInt())).toFloat() is Long -> ((srcNow.toLong() - src1.toLong()) / (src2.toLong() - src1.toLong())).toFloat() else -> throw IllegalStateException("状态异常") } val result: Float = when (dst1) { is Double -> (radio * (dst2.toDouble() - dst1.toDouble()) + dst1).toFloat() is Float -> radio * (dst2.toFloat() - dst1.toFloat()) + dst1 is Int -> radio * (dst2.toInt() - dst1.toInt()).toFloat() + dst1.toFloat() is Long -> radio * (dst2.toLong() - dst1.toLong()) + dst1 else -> throw IllegalStateException("状态异常") } val realResult = if (type == Linear.OverMax) { if (dst2.toFloat() > dst1.toFloat()) getOverMax(result, dst1, dst2) else getOverMax(result, dst2, dst1) } else result return realResult as R } /** * dst2>dst1 */ private fun <R : Number> getOverMax(result: Float, dst1: R, dst2: R): Float { var realResult1 = result if (result > dst2.toFloat()) realResult1 = dst2.toFloat() if (result < dst1.toFloat()) realResult1 = dst1.toFloat() return realResult1 } @JvmStatic fun main(args: Array<String>) { println(linear(0F, 1F, 0F, 0.5F, 0F)) } }
epl-1.0
b819311e91748299a696707eaae87b18
33.178571
123
0.55149
3.373898
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/ide/structure/RustTraitTreeElement.kt
1
929
package org.rust.ide.structure import com.intellij.ide.structureView.StructureViewTreeElement import com.intellij.ide.structureView.impl.common.PsiTreeElementBase import org.rust.lang.core.psi.RustTraitItemElement class RustTraitTreeElement(element: RustTraitItemElement) : PsiTreeElementBase<RustTraitItemElement>(element) { override fun getPresentableText(): String { var text = element?.identifier?.text ?: return "<unknown>" val generics = element?.genericParams?.text if (generics != null) text += generics val typeBounds = element?.typeParamBounds?.polyboundList?.map { it.text }?.joinToString(" + ") if (typeBounds != null) text += ": $typeBounds" return text } override fun getChildrenBase(): Collection<StructureViewTreeElement> = element?.traitMethodMemberList.orEmpty() .map(::RustTraitMethodTreeElement) }
mit
1daae422a1df6d7e472089fbfa3dee6d
34.730769
111
0.705059
4.915344
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/ide/annotator/RustRecursiveCallLineMarkerProvider.kt
1
2444
package org.rust.ide.annotator import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.util.FunctionUtil import org.rust.ide.icons.RustIcons import org.rust.lang.core.psi.* import org.rust.lang.core.psi.util.parentOfType import java.util.* /** * Line marker provider that annotates recursive funciton and method calls with * an icon on the gutter. */ class RustRecursiveCallLineMarkerProvider : LineMarkerProvider { override fun getLineMarkerInfo(element: PsiElement) = null override fun collectSlowLineMarkers(elements: List<PsiElement>, result: MutableCollection<LineMarkerInfo<PsiElement>>) { val lines = HashSet<Int>() // To prevent several markers on one line for (el in elements.filter { it.isRecursive }) { val doc = PsiDocumentManager.getInstance(el.project).getDocument(el.containingFile) ?: continue val lineNumber = doc.getLineNumber(el.textOffset) if (lineNumber !in lines) { lines.add(lineNumber) result.add(LineMarkerInfo( el, el.textRange, RustIcons.RECURSIVE_CALL, // Pass.UPDATE_OVERRIDEN_MARKERS in IDEA 15 // Pass.UPDATE_OVERRIDDEN_MARKERS in IDEA 2016.x // TODO: change to Pass.LINE_MARKERS, when it // does not create duplicate icons. 6, // :( FunctionUtil.constant("Recursive call"), null, GutterIconRenderer.Alignment.RIGHT)) } } } private val RustCallExprElement.pathExpr: RustPathExprElement? get() = expr as? RustPathExprElement private val PsiElement.isRecursive: Boolean get() { val def = when (this) { is RustCallExprElement -> pathExpr?.path?.reference?.resolve() is RustMethodCallExprElement -> reference.resolve() else -> null } ?: return false return parentOfType<RustImplMethodMemberElement>() == def // Methods and associated functions || parentOfType<RustFnItemElement>() == def // Pure functions } }
mit
fec31af725ef91ae18f7c0516b405aac
39.733333
107
0.635843
5.081081
false
false
false
false
etesync/android
app/src/main/java/com/etesync/syncadapter/syncadapter/TasksSyncAdapterService.kt
1
7248
/* * Copyright © Ricki Hirner (bitfire web engineering). * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html */ package com.etesync.syncadapter.syncadapter import android.accounts.Account import android.accounts.AccountManager import android.content.ContentProviderClient import android.content.ContentResolver import android.content.Context import android.content.SyncResult import android.os.Build import android.os.Bundle import at.bitfire.ical4android.AndroidTaskList import at.bitfire.ical4android.TaskProvider import at.bitfire.ical4android.TaskProvider.ProviderName import com.etesync.syncadapter.* import com.etesync.syncadapter.log.Logger import com.etesync.syncadapter.model.CollectionInfo import com.etesync.syncadapter.model.JournalEntity import com.etesync.syncadapter.model.JournalModel import com.etesync.syncadapter.resource.LocalTaskList import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import org.dmfs.tasks.contract.TaskContract import java.util.* /** * Synchronization manager for CalDAV collections; handles tasks ({@code VTODO}). */ class TasksSyncAdapterService: SyncAdapterService() { override fun syncAdapter() = TasksSyncAdapter(this, ProviderName.OpenTasks) class TasksSyncAdapter( context: Context, private val name: ProviderName ): SyncAdapter(context) { override fun onPerformSyncDo(account: Account, extras: Bundle, authority: String, provider: ContentProviderClient, syncResult: SyncResult) { val taskProvider = TaskProvider.fromProviderClient(context, name, provider) // make sure account can be seen by OpenTasks if (Build.VERSION.SDK_INT >= 26) AccountManager.get(context).setAccountVisibility(account, taskProvider.name.packageName, AccountManager.VISIBILITY_VISIBLE) val accountSettings = AccountSettings(context, account) /* don't run sync if - sync conditions (e.g. "sync only in WiFi") are not met AND - this is is an automatic sync (i.e. manual syncs are run regardless of sync conditions) */ if (!extras.containsKey(ContentResolver.SYNC_EXTRAS_MANUAL) && !checkSyncConditions(accountSettings)) return RefreshCollections(account, CollectionInfo.Type.TASKS).run() if (accountSettings.isLegacy) { legacyUpdateLocalTaskLists(taskProvider, account, accountSettings) } else { updateLocalTaskLists(taskProvider, account, accountSettings) } val principal = accountSettings.uri?.toHttpUrlOrNull()!! for (taskList in AndroidTaskList.find(account, taskProvider, LocalTaskList.Factory, "${TaskContract.TaskLists.SYNC_ENABLED}!=0", null)) { Logger.log.info("Synchronizing task list #${taskList.id} [${taskList.syncId}]") TasksSyncManager(context, account, accountSettings, extras, authority, syncResult, taskList, principal).use { it.performSync() } } Logger.log.info("Task sync complete") } private fun updateLocalTaskLists(provider: TaskProvider, account: Account, settings: AccountSettings) { val remote = HashMap<String, CachedCollection>() val etebaseLocalCache = EtebaseLocalCache.getInstance(context, account.name) val collections: List<CachedCollection> synchronized(etebaseLocalCache) { val httpClient = HttpClient.Builder(context, settings).setForeground(false).build() val etebase = EtebaseLocalCache.getEtebase(context, httpClient.okHttpClient, settings) val colMgr = etebase.collectionManager collections = etebaseLocalCache.collectionList(colMgr).filter { it.collectionType == Constants.ETEBASE_TYPE_TASKS } } for (collection in collections) { remote[collection.col.uid] = collection } val local = AndroidTaskList.find(account, provider, LocalTaskList.Factory, null, null) val updateColors = settings.manageCalendarColors // delete obsolete local calendar for (taskList in local) { val url = taskList.syncId val collection = remote[url] if (collection == null) { Logger.log.fine("Deleting obsolete local taskList $url") taskList.delete() } else { // remote CollectionInfo found for this local collection, update data Logger.log.fine("Updating local taskList $url") taskList.update(collection, updateColors) // we already have a local taskList for this remote collection, don't take into consideration anymore remote.remove(url) } } // create new local calendars for (url in remote.keys) { val cachedCollection = remote[url]!! Logger.log.info("Adding local calendar list $cachedCollection") LocalTaskList.create(account, provider, cachedCollection) } } private fun legacyUpdateLocalTaskLists(provider: TaskProvider, account: Account, settings: AccountSettings) { val data = (context.applicationContext as App).data var service = JournalModel.Service.fetchOrCreate(data, account.name, CollectionInfo.Type.TASKS) val remote = HashMap<String, JournalEntity>() val remoteJournals = JournalEntity.getJournals(data, service) for (journalEntity in remoteJournals) { remote[journalEntity.uid] = journalEntity } val local = AndroidTaskList.find(account, provider, LocalTaskList.Factory, null, null) val updateColors = settings.manageCalendarColors // delete obsolete local TaskList for (taskList in local) { val url = taskList.url val journalEntity = remote[url] if (journalEntity == null) { Logger.log.fine("Deleting obsolete local task list $url") taskList.delete() } else { // remote CollectionInfo found for this local collection, update data Logger.log.fine("Updating local task list $url with $journalEntity") taskList.update(journalEntity, updateColors) // we already have a local tasks for this remote collection, don't take into consideration anymore remote.remove(url) } } // create new local taskss for (url in remote.keys) { val journalEntity = remote[url]!! Logger.log.info("Adding local task list $journalEntity") LocalTaskList.create(account, provider, journalEntity) } } } }
gpl-3.0
534f86c18d8fc45878dc00c1772ec945
44.012422
149
0.64537
5.085614
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/administration/QuickPunishmentCommand.kt
1
1816
package net.perfectdreams.loritta.morenitta.commands.vanilla.administration import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.common.utils.Emotes import net.perfectdreams.loritta.morenitta.LorittaBot class QuickPunishmentCommand(loritta: LorittaBot) : AbstractCommand(loritta, "quickpunishment", category = net.perfectdreams.loritta.common.commands.CommandCategory.MODERATION) { override fun getDescriptionKey() = LocaleKeyData("commands.command.quickpunishment.description") override fun canUseInPrivateChannel(): Boolean { return false } override suspend fun run(context: CommandContext,locale: BaseLocale) { val userData = context.config.getUserData(loritta, context.userHandle.idLong) if (userData.quickPunishment) { context.reply( LorittaReply( message = locale["commands.command.quickpunishment.disabled"] ), LorittaReply( message = locale["commands.command.quickpunishment.howEnable"], prefix = Emotes.LORI_BAN_HAMMER, mentionUser = false ) ) } else { context.reply( LorittaReply( message = locale["commands.command.quickpunishment.enabled"] ), LorittaReply( message = locale["commands.command.quickpunishment.howDisable"], prefix = Emotes.LORI_BAN_HAMMER, mentionUser = false ) ) } loritta.newSuspendedTransaction { userData.quickPunishment = !userData.quickPunishment } } }
agpl-3.0
9d3a14a6f2ac80083e41436908980040
36.081633
178
0.725771
4.313539
false
false
false
false
ashdavies/brlo-hopfen
feature/src/main/kotlin/de/brlo/hopfen/feature/home/HomeViewModel.kt
1
2254
package de.brlo.hopfen.feature.home import android.databinding.ObservableField import android.view.View import de.brlo.hopfen.feature.android.ViewModel import de.brlo.hopfen.feature.data.Hop import de.brlo.hopfen.feature.data.HopsRepository import de.brlo.hopfen.feature.data.Listing import de.brlo.hopfen.feature.data.Profile import de.brlo.hopfen.feature.extensions.plusAssign import de.brlo.hopfen.feature.network.SchedulingStrategy import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject internal class HomeViewModel @Inject constructor( private val listings: ListingsRepository, profiles: ProfileRepository, hops: HopsRepository, private val navigation: HomeNavigation, strategy: SchedulingStrategy ) : ViewModel<MutableList<Listing>>(State.idle(mutableListOf())) { private val disposables = CompositeDisposable() val header = ObservableField<State<Profile>>(State.idle(Profile.empty())) val hopsList = ObservableField<State<MutableList<Hop>>>(State.idle(MutableList(0, { _ -> Hop.empty() }))) init { disposables += listings.getAll() .map { state.get().data.apply { add(it) } } .compose(strategy.observable()) .subscribe( { state.set(State.idle(it)) }, { navigation.showListingsError() state.set(state.get().toError(it)) } ) disposables += profiles.get("fGo29hRp2BMhHFkkmziAP3fBGbf2") .subscribe( { header.set(State.idle(it)) }, { navigation.showProfileError() header.set(header.get().toError(it)) } ) disposables += hops.getAll() .map { hopsList.get().data.apply { add(it) } } .compose(strategy.observable()) .subscribe( { hopsList.set(State.idle(it)) }, { navigation.showHopsError() hopsList.set(hopsList.get().toError(it)) } ) } override fun onCleared() = disposables.clear() fun onActionClicked(view: View) = navigation.showAddListingDialog( hopsList.get().data, header.get().data, { listing: Listing -> listings.put(listing, { _ -> "" }).subscribe() }) }
apache-2.0
2e2ae79569f1f14983b19f63591afd19
32.147059
107
0.645963
4.061261
false
false
false
false
danrien/projectBlue
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/GivenAPlayingPlaybackEngine/WhenChangingTracks.kt
1
3873
package com.lasthopesoftware.bluewater.client.playback.engine.GivenAPlayingPlaybackEngine import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.browsing.library.access.PassThroughLibraryStorage import com.lasthopesoftware.bluewater.client.browsing.library.access.PassThroughSpecificLibraryProvider import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library import com.lasthopesoftware.bluewater.client.playback.engine.PlaybackEngine.Companion.createEngine import com.lasthopesoftware.bluewater.client.playback.engine.bootstrap.PlaylistPlaybackBootstrapper import com.lasthopesoftware.bluewater.client.playback.engine.preparation.PreparedPlaybackQueueResourceManagement import com.lasthopesoftware.bluewater.client.playback.file.PositionedFile import com.lasthopesoftware.bluewater.client.playback.file.PositionedPlayingFile import com.lasthopesoftware.bluewater.client.playback.file.preparation.FakeDeferredPlayableFilePreparationSourceProvider import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CompletingFileQueueProvider import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlayingRepository import com.lasthopesoftware.bluewater.client.playback.volume.PlaylistVolumeManager import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise import org.assertj.core.api.Assertions.assertThat import org.joda.time.Duration import org.junit.BeforeClass import org.junit.Test import java.util.* import java.util.concurrent.CountDownLatch class WhenChangingTracks { @Test fun thenTheNextFileChangeIsTheSwitchedToTheCorrectTrackPosition() { assertThat(nextSwitchedFile!!.playlistPosition).isEqualTo(3) } @Test fun thenTheLatestObservedFileIsAtTheCorrectTrackPosition() { assertThat(latestFile!!.playlistPosition).isEqualTo(3) } @Test fun thenTheFirstStartedFileIsCorrect() { assertThat(startedFiles[0].asPositionedFile()) .isEqualTo(PositionedFile(0, ServiceFile(1))) } @Test fun thenTheChangedStartedFileIsCorrect() { assertThat(startedFiles[1].asPositionedFile()) .isEqualTo(PositionedFile(3, ServiceFile(4))) } @Test fun thenThePlaylistIsStartedTwice() { assertThat(startedFiles).hasSize(2) } companion object { private var nextSwitchedFile: PositionedFile? = null private var latestFile: PositionedPlayingFile? = null private val startedFiles: MutableList<PositionedPlayingFile> = ArrayList() @BeforeClass @JvmStatic fun before() { val fakePlaybackPreparerProvider = FakeDeferredPlayableFilePreparationSourceProvider() val library = Library() library.setId(1) val libraryProvider = PassThroughSpecificLibraryProvider(library) val libraryStorage = PassThroughLibraryStorage() val playbackEngine = FuturePromise( createEngine( PreparedPlaybackQueueResourceManagement( fakePlaybackPreparerProvider ) { 1 }, listOf(CompletingFileQueueProvider()), NowPlayingRepository(libraryProvider, libraryStorage), PlaylistPlaybackBootstrapper(PlaylistVolumeManager(1.0f)) ) ).get() val countDownLatch = CountDownLatch(2) playbackEngine ?.setOnPlayingFileChanged { p -> startedFiles.add(p) latestFile = p countDownLatch.countDown() } ?.startPlaylist( listOf( ServiceFile(1), ServiceFile(2), ServiceFile(3), ServiceFile(4), ServiceFile(5) ), 0, Duration.ZERO ) val playingPlaybackHandler = fakePlaybackPreparerProvider.deferredResolution.resolve() playbackEngine!!.changePosition(3, Duration.ZERO).then<Any?> { p: PositionedFile? -> nextSwitchedFile = p countDownLatch.countDown() null } fakePlaybackPreparerProvider.deferredResolution.resolve() playingPlaybackHandler.resolve() countDownLatch.await() } } }
lgpl-3.0
03a3c5ab80aec76be02aa770b0b9e0af
37.346535
120
0.808675
4.446613
false
true
false
false
yongce/DevTools
app/src/main/java/me/ycdev/android/devtools/root/RootJarExecutor.kt
1
1592
package me.ycdev.android.devtools.root import me.ycdev.android.lib.common.internalapi.android.app.ActivityManagerIA import timber.log.Timber class RootJarExecutor private constructor(private val args: Array<String>) { private fun execute() { val cmd = args[0] if (cmd == CMD_FORCE_STOP_PACKAGE) { if (args.size > 1) { val filePath = args[1] forceStopPackage(filePath) } else { Timber.tag(TAG).e("Usage: RootJarExecutor amForceStop <file path>") } } } companion object { private const val TAG = "RootJarExecutor" const val CMD_FORCE_STOP_PACKAGE = "amForceStop" @JvmStatic fun main(args: Array<String>) { Timber.tag(TAG).d( "Received params: %s", args.contentToString() ) if (args.isEmpty()) { Timber.tag(TAG).e("Usage: RootJarExecutor <command> [command parameters]") return } RootJarExecutor(args).execute() } fun forceStopPackage(params: String) { val pkgNames = params.split("#").toTypedArray() val service = ActivityManagerIA.getIActivityManager() if (service != null) { Timber.tag(TAG).d( "to kill apps: %s", pkgNames.contentToString() ) for (pkg in pkgNames) { ActivityManagerIA.forceStopPackage(service, pkg) } } } } }
apache-2.0
6a6338a4f94285e2a5a542daa97c42b8
30.84
90
0.52701
4.535613
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/config/Config.kt
2
12608
package com.cout970.magneticraft.systems.config /** * Created by cout970 on 16/05/2016. */ const val CATEGORY_GENERAL = "general" const val CATEGORY_ORES = "$CATEGORY_GENERAL.ores" const val CATEGORY_INSERTERS = "$CATEGORY_GENERAL.inserters" const val CATEGORY_ENERGY = "$CATEGORY_GENERAL.energy" const val CATEGORY_GUI = "$CATEGORY_GENERAL.gui" const val CATEGORY_PC = "$CATEGORY_GENERAL.pc" const val CATEGORY_MACHINES = "$CATEGORY_GENERAL.machines" object Config { @ConfigValue(category = CATEGORY_ORES, comment = "Copper ore") var copperOre = OreConfig(11, 8, 70, 10) @ConfigValue(category = CATEGORY_ORES, comment = "Lead ore") var leadOre = OreConfig(10, 8, 80, 2) @ConfigValue(category = CATEGORY_ORES, comment = "Tungsten ore") var tungstenOre = OreConfig(8, 8, 60, 20) @ConfigValue(category = CATEGORY_ORES, comment = "Pyrite ore") var pyriteOre = OreConfig(9, 9, 100, 30) @ConfigValue(category = CATEGORY_ORES, comment = "Limestone") var limestone = GaussOreConfig(0, 5, 0.9f, 3, 32, 64, 16) @ConfigValue(category = CATEGORY_ORES, comment = "Oil source") var oil = OilGenConfig(1 / 50f, 10, true) @ConfigValue(category = CATEGORY_GENERAL, comment = "Allow to power machines directly with RF") var enableDirectRFUsage = false @ConfigValue(category = CATEGORY_INSERTERS, comment = "Ignore stack upgrades in inserters, they will be always applied") var infiniteInserterStackUpgrades = false @ConfigValue(category = CATEGORY_INSERTERS, comment = "Ignore speed upgrades in inserters, they will be always applied") var infiniteInserterSpeedUpgrades = false @ConfigValue(category = CATEGORY_INSERTERS, comment = "Default: delay between inserter animations in ticks") var inserterDefaultDelay = 10f @ConfigValue(category = CATEGORY_INSERTERS, comment = "Upgraded: delay between inserter animations in ticks") var inserterUpgradedDelay = 5f @ConfigValue(category = CATEGORY_INSERTERS, comment = "Default: amount of items to take with an inserter on each operation") var inserterDefaultStackSize = 8 @ConfigValue(category = CATEGORY_INSERTERS, comment = "Upgraded: amount of items to take with an inserter on each operation") var inserterUpgradedStackSize = 64 @ConfigValue(category = CATEGORY_GENERAL, comment = "Set players on fire when processing blaze" + " rods in the crushing table") var crushingTableCausesFire = true @ConfigValue(category = CATEGORY_GENERAL, comment = "Automatically focus the search bar in the shelving unit when you enter the GUI") var autoSelectSearchBar = true @ConfigValue(category = CATEGORY_GUI, comment = "Unit of Heat to display, Celsius or Fahrenheit") var heatUnitCelsius = true @ConfigValue(category = CATEGORY_GUI, comment = "Character used to separate number like , in 1,000,000. Only one character will be used") var thousandsSeparator: String = "," @ConfigValue(category = CATEGORY_GUI, comment = "Allow players to use the gui of the combustion generator") var allowCombustionChamberGui = true @ConfigValue(category = CATEGORY_GUI, comment = "Scale of the gui with respect of the background image") var guideBookScale: Double = 1.5 @ConfigValue(category = CATEGORY_GUI, comment = "When you search something in the shelving unit the JEI search bar will update with the same search text") var syncShelvingUnitSearchWithJei: Boolean = false @ConfigValue(category = CATEGORY_GUI, comment = "Max distance the player can be from the conveyor belt to render its items, setting this value lower increases FPS") var conveyorBeltItemRenderLimit: Float = 128f @ConfigValue(category = CATEGORY_ENERGY, comment = "Conversion ratio between Watts and Forge Energy, " + "NOTE: all the values in the config about energy are in Watts") var wattsToFE = 1.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Conversion speed for the RF transformer in RF/t") var rfConversionSpeed = 100 @ConfigValue(category = CATEGORY_ENERGY, comment = "Conversion speed for the electric engine in RF/t") var electricEngineSpeed = 1000 @ConfigValue(category = CATEGORY_ENERGY, comment = "Max energy transmitted by the tesla tower per player/receiver (in joules), warning: if you put a high value the the machine may get negative voltages") var teslaTowerTransmissionRate = 500.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Electric Heater Max Production (in joules)") var electricHeaterMaxProduction = 80.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Combustion chamber max speed in Fuel per tick") var combustionChamberMaxSpeed = 4.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Combustion chamber fuel multiplier, bigger value makes fuel last longer") var combustionChamberFuelMultiplier = 1.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Combustion chamber use only coal or coal-like fuels") var combustionChamberOnlyCoal = true @ConfigValue(category = CATEGORY_ENERGY, comment = "Big combustion chamber max speed in Fuel per tick") var bigCombustionChamberMaxSpeed = 40.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Big combustion chamber liquid fuel energy multiplier") var bigCombustionChamberLiquidFuelMultiplier = 1.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Hydraulic Press crafting time multiplier, doesn't affect energy usage per tick") var hydraulicPressCraftingTimeMultiplier = 1.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Electric Furnace Max Consumption") var electricFurnaceMaxConsumption = 20.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Big Electric Furnace Max Consumption") var bigElectricFurnaceMaxConsumption = 200.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Oil Heater Max Consumption") var oilHeaterMaxConsumption = 120.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Refinery Max Consumption in Steam mB") var refineryMaxConsumption = 20.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Gasification Unit Max Consumption") var gasificationUnitConsumption = 40.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Small boiler max steam production in mB") var boilerMaxProduction = 20 @ConfigValue(category = CATEGORY_ENERGY, comment = "Multiblock boiler max steam production in mB") var multiblockBoilerMaxProduction = 600 @ConfigValue(category = CATEGORY_ENERGY, comment = "Steam engine max production in W (J/t)") var steamEngineMaxProduction = 240 @ConfigValue(category = CATEGORY_ENERGY, comment = "Steam turbine max production in W (J/t)") var steamTurbineMaxProduction = 1200 @ConfigValue(category = CATEGORY_ENERGY, comment = "Airlock: maintenance cost per Air Bubble every " + "40 ticks (2 sec)") var airlockBubbleCost = 1.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Airlock: cost of removing a water block") var airlockAirCost = 2.0 @ConfigValue(category = CATEGORY_ORES, comment = "Oil per stage in a oil source block, every block has 10 stages") var oilPerStage = 1000 @ConfigValue(category = CATEGORY_ENERGY, comment = "Hydraulic Press Max Consumption") var hydraulicPressMaxConsumption = 60.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Grinder Max Consumption") var grinderMaxConsumption = 40.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Sieve Max Consumption") var sieveMaxConsumption = 40.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Solar Panel Production") var solarPanelMaxProduction = 100.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Wind Turbine Production") var windTurbineMaxProduction = 200.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Thermopile production (approximated)") var thermopileProduction = 20.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Solar power heat generation per tick (in Joules)") var solarMirrorHeatProduction = 16 @ConfigValue(category = CATEGORY_ENERGY, comment = "Pumpjack Max Consumption") var pumpjackConsumption = 80.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Pumpjack Scan tries per tick, every scan checks 8 blocks") var pumpjackScanSpeed = 80 @ConfigValue(category = CATEGORY_ENERGY, comment = "Capacity of electric tools") var electricToolCapacity: Int = 512_000 @ConfigValue(category = CATEGORY_ENERGY, comment = "Energy used per attack with this tool") var electricToolAttackConsumption: Int = 2000 @ConfigValue(category = CATEGORY_ENERGY, comment = "Energy used per block mined with this tool") var electricToolBreakConsumption: Int = 1000 @ConfigValue(category = CATEGORY_ENERGY, comment = "Energy used per jump") var electricToolPistonConsumption: Int = 4000 @ConfigValue(category = CATEGORY_ENERGY, comment = "Item Low Battery Capacity") var batteryItemLowCapacity: Int = 250_000 @ConfigValue(category = CATEGORY_ENERGY, comment = "Item Medium Battery Capacity") var batteryItemMediumCapacity: Int = 2_500_000 @ConfigValue(category = CATEGORY_ENERGY, comment = "Battery Block Capacity") var blockBatteryCapacity: Int = 1_000_000 @ConfigValue(category = CATEGORY_ENERGY, comment = "Battery Block Item charge and discharge " + "speed in Joules/tick (Watts)") var blockBatteryTransferRate: Int = 500 @ConfigValue(category = CATEGORY_ENERGY, comment = "Conversion rate water to steam, by default 1mB Water = 10mB Steam") var waterToSteam: Double = 10.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Conversion rate steam to joules, by default 1mB = 2.0J") var steamToJoules: Double = 2.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Conversion rate fuel to joules, by default 1fuel = 10J") var fuelToJoules: Double = 10.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Energy dissipated per tick for generators that are not working") var heatDissipationSpeed: Double = -10.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Iron pipe max rate in mb") var ironPipeMaxRate: Int = 160 @ConfigValue(category = CATEGORY_ENERGY, comment = "FE to J conversion rate") var forgeEnergyToJoules: Double = 1.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Buildcraft MJ to FE conversion rate") var minecraftJoulesToForgeEnergy: Int = 10 @ConfigValue(category = CATEGORY_ENERGY, comment = "Energy storage multiplier for internal buffers") var machineEnergyStorageMultiplier = 1.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Max charge speed multiplier for internal buffers") var maxChargeSpeedMultiplier = 1.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Upper voltage charge limit offset") var upperVoltageLimitOffset = 0.0 @ConfigValue(category = CATEGORY_ENERGY, comment = "Lower voltage charge limit offset") var lowerVoltageLimitOffset = 0.0 @ConfigValue(category = CATEGORY_MACHINES, comment = "Amount of water generated by a Water generator every tick") var waterGeneratorPerTickWater: Int = 20 @ConfigValue(category = CATEGORY_MACHINES, comment = "Max amount of items that a container can drop when mined, it will delete the rest of items") var containerMaxItemDrops: Int = 128 * 64 @ConfigValue(category = CATEGORY_MACHINES, comment = "Max amount of items that a container can store") var containerMaxItemStorage: Int = 1024 * 64 @ConfigValue(category = CATEGORY_MACHINES, comment = "Enable/disable (1/0) particles in machine animations ") var enableMachineParticles: Int = 1 @ConfigValue(category = CATEGORY_MACHINES, comment = "Enable/disable solar tower meltdown at 4000C") var allowSolarTowerMeltdown: Boolean = false @ConfigValue(category = CATEGORY_PC, comment = "Allow TCP connections in PCs") var allowTcpConnections: Boolean = true @ConfigValue(category = CATEGORY_PC, comment = "Max TCP connections in all PCs") var maxTcpConnections: Int = 8 @ConfigValue(category = CATEGORY_PC, comment = "Energy consumed every tick by the mining robot") var miningRobotPassiveConsumption: Double = 1.0 @ConfigValue(category = CATEGORY_PC, comment = "Color of text, valid values: 0 => amber 1, 1 => amber 2, 2 => white, 3 => green 1, 4 => apple 2, 5 => green 2, 6 => apple 2c, 7 => green 3, 8 => green 4") var computerTextColor: Int = 0 }
gpl-2.0
42b853a014a288913f86cbba3f0494a8
46.939163
207
0.733582
4.139199
false
true
false
false
world-federation-of-advertisers/common-jvm
src/test/kotlin/org/wfanet/measurement/storage/testing/InMemoryStorageClientTest.kt
1
1529
/* * Copyright 2021 The Cross-Media Measurement 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.wfanet.measurement.storage.testing import com.google.common.truth.Truth.assertThat import com.google.protobuf.kotlin.toByteStringUtf8 import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.wfanet.measurement.common.flatten class InMemoryStorageClientTest : AbstractStorageClientTest<InMemoryStorageClient>() { @Before fun initStorageClient() { storageClient = InMemoryStorageClient() } @Test fun contents() = runBlocking { val client = InMemoryStorageClient() assertThat(client.contents).isEmpty() val blobKey = "some-blob-key" val contents = "some-contents".toByteStringUtf8() client.writeBlob(blobKey, contents) assertThat(client.contents.mapValues { it.value.read().flatten() }) .containsExactly(blobKey, contents) client.getBlob(blobKey)?.delete() assertThat(client.contents).isEmpty() } }
apache-2.0
e82414b568620d0474a23e24238e9a32
30.204082
86
0.751472
4.331445
false
true
false
false
toastkidjp/Jitte
lib/src/main/java/jp/toastkid/lib/view/text/SingleLineTextInputLayoutFactory.kt
1
1642
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.lib.view.text import android.content.Context import android.text.InputType import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.EditText import com.google.android.material.textfield.TextInputLayout /** * * @param factory For injecting test dependencies. * @author toastkidjp */ class SingleLineTextInputLayoutFactory( private val factory: (Context) -> TextInputLayout = { TextInputLayout(it) } ) { /** * Make [TextInputLayout] instance. * * @param context [Context] Use for make instance. */ operator fun invoke(context: Context): TextInputLayout = factory(context) .also { layout -> layout.addView( EditText(context).also { it.maxLines = 1 it.inputType = InputType.TYPE_CLASS_TEXT it.imeOptions = EditorInfo.IME_ACTION_SEARCH }, 0, LAYOUT_PARAMS ) } companion object { /** * EditText's layout params. */ private val LAYOUT_PARAMS = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) } }
epl-1.0
3969417b26e2d3981a284c199fe6df17
27.824561
88
0.616322
4.815249
false
false
false
false
Kiskae/Twitch-Archiver
ui/src/main/kotlin/net/serverpeon/twitcharchiver/network/download/ForkJoinDownloader.kt
1
3110
package net.serverpeon.twitcharchiver.network.download import com.google.common.collect.ImmutableList import com.google.common.io.Files import okhttp3.Call import okhttp3.Response import java.nio.file.Path import java.util.concurrent.ForkJoinTask object ForkJoinDownloader { data class DownloadEntry<T>(val source: Call, val sink: Path, val ident: T) { internal fun doDownload( bufSize: Int = 64 * 1024, onStart: (Response) -> Unit, onUpdate: (Int) -> Unit, onEnd: (Response, Long) -> Unit ) { val file = sink.toFile() try { if (!file.exists()) { check(file.createNewFile()) //File needs to exist to stream into it } val response = source.execute() response.body().byteStream().use { input -> Files.asByteSink(file).openStream().use { output -> onStart(response) val buf = ByteArray(bufSize) var bytesCopied: Long = 0 var bytes = input.read(buf) while (bytes >= 0) { output.write(buf, 0, bytes) onUpdate(bytes) bytesCopied += bytes bytes = input.read(buf) } onEnd(response, bytesCopied) } } } catch (ex: Exception) { file.delete() //Delete if an exception occurs throw ex } } } fun <T> create(downloads: List<DownloadEntry<T>>, updater: DownloadSteward<T>): ForkJoinTask<*> { return ForkJoinTask.adapt(Main( ImmutableList.copyOf(downloads), updater )) } private class Main<T>( val entries: List<DownloadEntry<T>>, val updater: DownloadSteward<T> ) : Runnable { override fun run() { ForkJoinTask.invokeAll(entries.map { ForkJoinTask.adapt(Part(it, updater)) }) } } private class Part<T>( val entry: DownloadEntry<T>, val updater: DownloadSteward<T> ) : Runnable { override fun run() { updater.onBegin(entry) try { entry.doDownload(DEFAULT_BUFFER_SIZE, { response -> check(response.isSuccessful) { "Non-success response code ${response.message()} for ${response.request().url()}" } updater.validatePre(entry, response) }, { updater.onUpdate(it) }, { response, bytes -> updater.validatePost(entry, response, bytes) }) updater.onEnd(entry) } catch (ex: Exception) { updater.onException(entry, ex) } } } }
mit
abc265da33bea0735390274a68e851f7
33.186813
105
0.473312
5.166113
false
false
false
false
approov/shipfast-api-protection
app/android/kotlin/ShipFast/app/src/main/java/com/criticalblue/shipfast/SummaryActivity.kt
1
6495
/* Copyright (C) 2020 CriticalBlue Ltd. 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.criticalblue.shipfast import android.content.Context import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ListView import android.widget.ProgressBar import android.widget.TextView import com.criticalblue.shipfast.api.RestAPI import com.criticalblue.shipfast.config.API_REQUEST_ATTEMPTS import com.criticalblue.shipfast.config.API_REQUEST_RETRY_SLEEP_MILLESECONDS import com.criticalblue.shipfast.dto.Shipment import com.criticalblue.shipfast.utils.ViewShow /** * The Summary activity class. */ class SummaryActivity : BaseActivity() { /** The progress bar */ private lateinit var updateSummaryProgressBar: ProgressBar /** The 'delivered shipments' list view */ private lateinit var deliveredShipmentsListView: ListView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_summary) title = "Delivered Shipments" updateSummaryProgressBar = findViewById(R.id.updateSummaryProgressBar) deliveredShipmentsListView = findViewById(R.id.deliveredShipmentsListView) updateDeliveredShipments(API_REQUEST_ATTEMPTS) } /** * Update the current delivered shipments list view by requesting data from the server. */ private fun updateDeliveredShipments(remainingRetries: Int) { if (remainingRetries <= 0) { stopProgress() runOnUiThread { ViewShow.warning(findViewById(R.id.shipmentState), "Unable to fetch the delivered shipments.") } return } else { Thread.sleep(API_REQUEST_RETRY_SLEEP_MILLESECONDS.toLong()) } startProgress() RestAPI.requestDeliveredShipments(this@SummaryActivity) { shipmentsResponse -> stopProgress() if (shipmentsResponse.isOk()) { if (shipmentsResponse.hasNoData()) { runOnUiThread { ViewShow.warning(findViewById(R.id.shipmentState), "No Delivered Shipments Available!") } } runOnUiThread { deliveredShipmentsListView.adapter = DeliveredShipmentsAdapter(this@SummaryActivity, R.layout.listview_shipment, shipmentsResponse.get()) } return@requestDeliveredShipments } if (shipmentsResponse.hasApproovTransientError()) { Log.i(TAG, shipmentsResponse.errorMessage()) runOnUiThread { ViewShow.error(findViewById(R.id.shipmentState), shipmentsResponse.errorMessage()) } updateDeliveredShipments(remainingRetries - 1) return@requestDeliveredShipments } if (shipmentsResponse.hasApproovFatalError()) { Log.i(TAG, shipmentsResponse.errorMessage()) runOnUiThread { ViewShow.error(findViewById(R.id.shipmentState), shipmentsResponse.errorMessage()) } return@requestDeliveredShipments } if (shipmentsResponse.isNotOk()) { Log.i(TAG, shipmentsResponse.errorMessage()) runOnUiThread { ViewShow.info(findViewById(R.id.shipmentState), "Retrying to fetch the delivered shipments.") } updateDeliveredShipments(remainingRetries - 1) return@requestDeliveredShipments } } } /** * Start showing progress. */ private fun startProgress() { runOnUiThread { updateSummaryProgressBar.visibility = View.VISIBLE } } /** * Stop showing progress. */ private fun stopProgress() { runOnUiThread { updateSummaryProgressBar.visibility = View.INVISIBLE } } } /** * The adapter for the Delivered Shipments list view. */ class DeliveredShipmentsAdapter(context: Context, resource: Int, private val shipments: List<Shipment>) : ArrayAdapter<Shipment>(context, resource, shipments) { override fun getView(position: Int, convertView: android.view.View?, parent: ViewGroup): android.view.View { // Get the shipment for the list view row index val shipment = shipments[position] // Get the various list view row views val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val rowView = inflater.inflate(R.layout.listview_shipment, parent, false) val descriptionTextView = rowView.findViewById<TextView>(R.id.delShipDescriptionTextView) val gratuityTextView = rowView.findViewById<TextView>(R.id.delShipGratuityTextView) val pickupTextView = rowView.findViewById<TextView>(R.id.delShipPickupTextView) val deliverTextView = rowView.findViewById<TextView>(R.id.delShipDeliverTextView) // Update the text for the list view row views descriptionTextView.text = shipment.description gratuityTextView.text = "${shipment.gratuity}" pickupTextView.text = shipment.pickupName deliverTextView.text = shipment.deliveryName return rowView } }
mit
965a4f538f72e61d2ad3efcf1c060baa
35.488764
113
0.679908
4.828996
false
false
false
false
NordicSemiconductor/Android-nRF-Toolbox
profile_hts/src/main/java/no/nordicsemi/android/hts/view/HTSMapper.kt
1
3227
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder 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 * HOLDER 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 no.nordicsemi.android.hts.view import no.nordicsemi.android.theme.RadioButtonItem import no.nordicsemi.android.theme.RadioGroupViewEntity private const val DISPLAY_FAHRENHEIT = "°F" private const val DISPLAY_CELSIUS = "°C" private const val DISPLAY_KELVIN = "°K" internal fun displayTemperature(value: Float, temperatureUnit: TemperatureUnit): String { return when (temperatureUnit) { TemperatureUnit.CELSIUS -> String.format("%.1f °C", value) TemperatureUnit.FAHRENHEIT -> String.format("%.1f °F", value * 1.8f + 32f) TemperatureUnit.KELVIN -> String.format("%.1f °K", value + 273.15f) } } internal fun String.toTemperatureUnit(): TemperatureUnit { return when (this) { DISPLAY_CELSIUS -> TemperatureUnit.CELSIUS DISPLAY_FAHRENHEIT -> TemperatureUnit.FAHRENHEIT DISPLAY_KELVIN -> TemperatureUnit.KELVIN else -> throw IllegalArgumentException("Can't create TemperatureUnit from this label: $this") } } internal fun TemperatureUnit.temperatureSettingsItems(): RadioGroupViewEntity { return RadioGroupViewEntity( TemperatureUnit.values().map { createRadioButtonItem(it, this) } ) } private fun createRadioButtonItem(unit: TemperatureUnit, selectedTemperatureUnit: TemperatureUnit): RadioButtonItem { return RadioButtonItem(displayTemperature(unit), unit == selectedTemperatureUnit) } private fun displayTemperature(unit: TemperatureUnit): String { return when (unit) { TemperatureUnit.CELSIUS -> DISPLAY_CELSIUS TemperatureUnit.FAHRENHEIT -> DISPLAY_FAHRENHEIT TemperatureUnit.KELVIN -> DISPLAY_KELVIN } }
bsd-3-clause
cd890089ade58f13a5a12346110d719f
42.527027
117
0.754114
4.530239
false
false
false
false
SimpleTimeTracking/StandaloneClient
src/test/kotlin/org/stt/command/ActivitiesTest.kt
1
6799
package org.stt.command import org.junit.Before import org.junit.Test import org.mockito.BDDMockito.given import org.mockito.Mock import org.mockito.Mockito.verify import org.mockito.Mockito.verifyNoMoreInteractions import org.mockito.MockitoAnnotations import org.stt.Matchers.any import org.stt.model.TimeTrackingItem import org.stt.persistence.ItemPersister import org.stt.query.TimeTrackingItemQueries import java.time.LocalDateTime import java.util.* import java.util.stream.Stream class ActivitiesTest { private var sut: Activities? = null @Mock private lateinit var persister: ItemPersister @Mock private lateinit var queries: TimeTrackingItemQueries @Before fun setup() { MockitoAnnotations.initMocks(this) sut = Activities(persister, queries, Optional.empty()) } @Test fun shouldFillGapOnDeleteIfPreviousAndNextMatch() { // GIVEN val before = TimeTrackingItem("expected", LocalDateTime.of(2000, 10, 10, 10, 9), LocalDateTime.of(2000, 10, 10, 10, 10)) val itemToDelete = TimeTrackingItem("toDelete", LocalDateTime.of(2000, 10, 10, 10, 10), LocalDateTime.of(2000, 10, 10, 10, 12)) val after = TimeTrackingItem("expected", LocalDateTime.of(2000, 10, 10, 10, 12), LocalDateTime.of(2000, 10, 10, 10, 13)) val expected = TimeTrackingItem("expected", LocalDateTime.of(2000, 10, 10, 10, 9), LocalDateTime.of(2000, 10, 10, 10, 13)) given<TimeTrackingItemQueries.AdjacentItems>(queries.getAdjacentItems(itemToDelete)).willReturn(TimeTrackingItemQueries.AdjacentItems(before, after)) val removeActivity = RemoveActivity(itemToDelete) // WHEN sut!!.removeActivityAndCloseGap(removeActivity) // THEN verify<ItemPersister>(persister).persist(expected) verifyNoMoreInteractions(persister) } @Test fun shouldNotFillGapOnDeleteIfPreviousAndNextDiffer() { // GIVEN val before = TimeTrackingItem("before", LocalDateTime.of(2000, 10, 10, 10, 9), LocalDateTime.of(2000, 10, 10, 10, 10)) val itemToDelete = TimeTrackingItem("toDelete", LocalDateTime.of(2000, 10, 10, 10, 10), LocalDateTime.of(2000, 10, 10, 10, 12)) val after = TimeTrackingItem("after", LocalDateTime.of(2000, 10, 10, 10, 12), LocalDateTime.of(2000, 10, 10, 10, 13)) given<TimeTrackingItemQueries.AdjacentItems>(queries.getAdjacentItems(itemToDelete)).willReturn(TimeTrackingItemQueries.AdjacentItems(before, after)) val removeActivity = RemoveActivity(itemToDelete) // WHEN sut!!.removeActivityAndCloseGap(removeActivity) // THEN verify<ItemPersister>(persister).delete(itemToDelete) verifyNoMoreInteractions(persister) } @Test fun shouldFillGapOnDeletedIsOngoing() { // GIVEN val before = TimeTrackingItem("expected", LocalDateTime.of(2000, 10, 10, 10, 9), LocalDateTime.of(2000, 10, 10, 10, 10)) val itemToDelete = TimeTrackingItem("toDelete", LocalDateTime.of(2000, 10, 10, 10, 10)) val expected = TimeTrackingItem("expected", LocalDateTime.of(2000, 10, 10, 10, 9)) given<TimeTrackingItemQueries.AdjacentItems>(queries.getAdjacentItems(itemToDelete)).willReturn(TimeTrackingItemQueries.AdjacentItems(before, null)) val removeActivity = RemoveActivity(itemToDelete) // WHEN sut!!.removeActivityAndCloseGap(removeActivity) // THEN verify<ItemPersister>(persister).persist(expected) verifyNoMoreInteractions(persister) } @Test fun shouldNotFillGapIfPreviousItemStartsOnDifferentDay() { // GIVEN val before = TimeTrackingItem("expected", LocalDateTime.of(2000, 10, 9, 10, 9), LocalDateTime.of(2000, 10, 10, 10, 10)) val itemToDelete = TimeTrackingItem("toDelete", LocalDateTime.of(2000, 10, 10, 10, 10)) given(queries.getAdjacentItems(itemToDelete)).willReturn(TimeTrackingItemQueries.AdjacentItems(before, null)) val removeActivity = RemoveActivity(itemToDelete) // WHEN sut!!.removeActivityAndCloseGap(removeActivity) // THEN verify<ItemPersister>(persister).delete(itemToDelete) verifyNoMoreInteractions(persister) } @Test fun shouldDeletedWithoutPrevious() { // GIVEN val itemToDelete = TimeTrackingItem("toDelete", LocalDateTime.of(2000, 10, 10, 10, 10), LocalDateTime.of(2000, 10, 10, 10, 12)) val after = TimeTrackingItem("after", LocalDateTime.of(2000, 10, 10, 10, 12), LocalDateTime.of(2000, 10, 10, 10, 13)) given<TimeTrackingItemQueries.AdjacentItems>(queries.getAdjacentItems(itemToDelete)).willReturn(TimeTrackingItemQueries.AdjacentItems(null, after)) val removeActivity = RemoveActivity(itemToDelete) // WHEN sut!!.removeActivityAndCloseGap(removeActivity) // THEN verify<ItemPersister>(persister).delete(itemToDelete) verifyNoMoreInteractions(persister) } @Test fun shouldEndOngoingItemIfItemWithSameActivityAndStartIsGiven() { // GIVEN val ongoing = TimeTrackingItem("ongoing", LocalDateTime.of(2000, 10, 10, 10, 10)) val expected = TimeTrackingItem("ongoing", LocalDateTime.of(2000, 10, 10, 10, 12), LocalDateTime.of(2000, 10, 10, 10, 13)) val newActivity = NewActivity(expected) given(queries.queryItems(any())).willReturn(Stream.of(ongoing)) given<TimeTrackingItem>(queries.lastItem).willReturn(ongoing) // WHEN sut!!.addNewActivity(newActivity) // THEN verify<ItemPersister>(persister).replace(ongoing, expected) verifyNoMoreInteractions(persister) } @Test fun shouldNotEndOngoingItemIfItemWithDifferentActivityWithSameStartIsGiven() { // GIVEN val expected = TimeTrackingItem("different", LocalDateTime.of(2000, 10, 10, 10, 12), LocalDateTime.of(2000, 10, 10, 10, 13)) val newActivity = NewActivity(expected) given(queries.queryItems(any())).willReturn(Stream.empty()) given<TimeTrackingItem>(queries.lastItem).willReturn(expected) // WHEN sut!!.addNewActivity(newActivity) // THEN verify<ItemPersister>(persister).persist(expected) verifyNoMoreInteractions(persister) } }
gpl-3.0
11ef57420ac55ca14dc089a3ae5d87f8
34.416667
157
0.651125
4.701936
false
false
false
false
NordicSemiconductor/Android-nRF-Toolbox
profile_rscs/src/main/java/no/nordicsemi/android/rscs/viewmodel/RSCSViewModel.kt
1
4108
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder 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 * HOLDER 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 no.nordicsemi.android.rscs.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import no.nordicsemi.android.analytics.AppAnalytics import no.nordicsemi.android.analytics.Profile import no.nordicsemi.android.analytics.ProfileConnectedEvent import no.nordicsemi.android.navigation.* import no.nordicsemi.android.rscs.data.RSCS_SERVICE_UUID import no.nordicsemi.android.rscs.repository.RSCSRepository import no.nordicsemi.android.rscs.view.* import no.nordicsemi.android.service.ConnectedResult import no.nordicsemi.android.utils.exhaustive import no.nordicsemi.android.utils.getDevice import no.nordicsemi.ui.scanner.ScannerDestinationId import javax.inject.Inject @HiltViewModel internal class RSCSViewModel @Inject constructor( private val repository: RSCSRepository, private val navigationManager: NavigationManager, private val analytics: AppAnalytics ) : ViewModel() { private val _state = MutableStateFlow<RSCSViewState>(NoDeviceState) val state = _state.asStateFlow() init { viewModelScope.launch { if (repository.isRunning.firstOrNull() == false) { requestBluetoothDevice() } } repository.data.onEach { _state.value = WorkingState(it) (it as? ConnectedResult)?.let { analytics.logEvent(ProfileConnectedEvent(Profile.RSCS)) } }.launchIn(viewModelScope) } private fun requestBluetoothDevice() { navigationManager.navigateTo(ScannerDestinationId, UUIDArgument(RSCS_SERVICE_UUID)) navigationManager.recentResult.onEach { if (it.destinationId == ScannerDestinationId) { handleArgs(it) } }.launchIn(viewModelScope) } private fun handleArgs(args: DestinationResult) { when (args) { is CancelDestinationResult -> navigationManager.navigateUp() is SuccessDestinationResult -> repository.launch(args.getDevice()) }.exhaustive } fun onEvent(event: RSCScreenViewEvent) { when (event) { DisconnectEvent -> disconnect() NavigateUpEvent -> navigationManager.navigateUp() OpenLoggerEvent -> repository.openLogger() }.exhaustive } private fun disconnect() { repository.release() navigationManager.navigateUp() } }
bsd-3-clause
817a868f51aa0e42b44c97d3f5eddeeb
37.392523
91
0.731986
4.793466
false
false
false
false
yawkat/javap
server/src/main/kotlin/at/yawk/javap/ExactResourceManager.kt
1
1755
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package at.yawk.javap import io.undertow.server.handlers.resource.Resource import io.undertow.server.handlers.resource.ResourceChangeEvent import io.undertow.server.handlers.resource.ResourceChangeListener import io.undertow.server.handlers.resource.ResourceManager class ExactResourceManager(path: String, private val next: ResourceManager) : ResourceManager { private val path = if (path.startsWith('/')) path.substring(1) else path private val listeners = mutableMapOf<ResourceChangeListener, ResourceChangeListener>() override fun isResourceChangeListenerSupported() = next.isResourceChangeListenerSupported override fun getResource(path: String): Resource? = if (path == "" || path == "/") { next.getResource(this.path) } else { null } override fun registerResourceChangeListener(listener: ResourceChangeListener) { val wrapped = ResourceChangeListener { evts -> for (evt in evts) { if (evt.resource == path || evt.resource == "/$path") { listener.handleChanges(listOf(ResourceChangeEvent("", evt.type))) } } } listeners[listener] = wrapped next.registerResourceChangeListener(wrapped) } override fun removeResourceChangeListener(listener: ResourceChangeListener) { next.removeResourceChangeListener(listeners.remove(listener)!!) } override fun close() { next.close() } }
mpl-2.0
7898c93248721b80d7dcdd0a39482c05
36.361702
93
0.664387
4.848066
false
false
false
false
Bodo1981/swapi.co
app/src/main/java/com/christianbahl/swapico/base/loadmore/LoadMoreScrollListener.kt
1
844
package com.christianbahl.swapico.base.loadmore import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView /** * @author Christian Bahl */ class LoadMoreScrollListener(val layoutManager: LinearLayoutManager, val onLoadMore: () -> Unit) : RecyclerView.OnScrollListener() { companion object { private val ITEMS_BEFORE_LAST_ITEM = 3 } public var isLoading: Boolean = false override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val lastVisibleItem = layoutManager.findLastVisibleItemPosition() + 1 // +1 because position starts at 0 val totalItemCount = layoutManager.itemCount if (!isLoading && totalItemCount <= (lastVisibleItem + ITEMS_BEFORE_LAST_ITEM)) { isLoading = true onLoadMore() } } }
apache-2.0
21142b0be5e126e762a0f8563b7e3aed
29.178571
132
0.735782
4.612022
false
false
false
false
GlimpseFramework/glimpse-framework
api/src/main/kotlin/glimpse/lights/LightBuilder.kt
1
2762
package glimpse.lights import glimpse.* /** * Light source builder. */ sealed class LightBuilder { protected var color: () -> Color = { Color.WHITE } internal abstract fun build(): Light /** * Sets color lambda. */ fun color(color: () -> Color) { this.color = color } /** * Direction light source builder. */ class DirectionLightBuilder : LightBuilder() { private var direction: () -> Vector = { -Vector.Z_UNIT } /** * Sets light direction lambda. */ fun direction(direction: () -> Vector) { this.direction = direction } override fun build() = Light.DirectionLight(direction, color) } /** * Point light source builder. */ class PointLightBuilder : LightBuilder() { private var position: () -> Point = { Point.ORIGIN } private var distance: () -> Float = { 100f } /** * Sets light position lambda. */ fun position(position: () -> Point) { this.position = position } /** * Sets light maximum distance lambda. */ fun distance(distance: () -> Float) { this.distance = distance } override fun build() = Light.PointLight(position, distance, color) } /** * Spotlight source builder. */ class SpotlightBuilder : LightBuilder() { private var position: () -> Point = { Vector.Z_UNIT.toPoint() } private var target: () -> Point = { Point.ORIGIN } private var angle: () -> Angle = { 60.degrees } private var distance: () -> Float = { 100f } /** * Sets light position lambda. */ fun position(position: () -> Point) { this.position = position } /** * Sets light cone target lambda. */ fun target(target: () -> Point) { this.target = target } /** * Sets light cone angle lambda. */ fun angle(angle: () -> Angle) { this.angle = angle } /** * Sets light maximum distance lambda. */ fun distance(distance: () -> Float) { this.distance = distance } override fun build() = Light.Spotlight(position, target, angle, distance, color) } } /** * Builds a direction light source initialized with an [init] function. */ fun directionLight(init: LightBuilder.DirectionLightBuilder.() -> Unit): Light.DirectionLight { val builder = LightBuilder.DirectionLightBuilder() builder.init() return builder.build() } /** * Builds a point light source initialized with an [init] function. */ fun pointLight(init: LightBuilder.PointLightBuilder.() -> Unit): Light.PointLight { val builder = LightBuilder.PointLightBuilder() builder.init() return builder.build() } /** * Builds a spotlight source initialized with an [init] function. */ fun spotlight(init: LightBuilder.SpotlightBuilder.() -> Unit): Light.Spotlight { val builder = LightBuilder.SpotlightBuilder() builder.init() return builder.build() }
apache-2.0
bd2002834f2eb7e5587a1a3535b0b0c9
20.246154
95
0.648081
3.587013
false
false
false
false
cfig/Nexus_boot_image_editor
bbootimg/src/main/kotlin/bootimg/cpio/AndroidCpioEntry.kt
2
5730
// Copyright 2021 [email protected] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cfig.bootimg.cpio import cfig.helper.Helper import com.fasterxml.jackson.annotation.JsonIgnore import org.apache.commons.compress.archivers.cpio.CpioArchiveEntry import org.apache.commons.compress.archivers.cpio.CpioArchiveOutputStream import org.apache.commons.compress.archivers.cpio.CpioConstants import org.slf4j.LoggerFactory import java.io.ByteArrayOutputStream class AndroidCpioEntry( var name: String = "", var statMode: Long = 0,// stat.st_mode @JsonIgnore val data: ByteArray = byteArrayOf(), var ino: Long = 0, var note: String = "" ) { fun encode(): ByteArray { //new ascii cpio var header = Helper.join( NewAsciiCpio( c_ino = ino, c_mode = statMode, c_filesize = data.size, c_namesize = name.length + 1 ).encode(), name.toByteArray(), ByteArray(1) ) //NULL terminated c-string //padding header if necessary Helper.round_to_multiple(header.size, 4).let { roundedSize -> if (roundedSize != header.size) { log.debug("header: meta ${header.size - 1 - name.length}, name ${name.length}, null 1, pad ${roundedSize - header.size} -> $roundedSize") header = Helper.join(header, ByteArray(roundedSize - header.size)) } } var payload = data //padding data if necessary Helper.round_to_multiple(payload.size, 4).let { roundedSize -> if (roundedSize != payload.size) { log.debug("data : payload ${payload.size}, pad ${roundedSize - payload.size} -> $roundedSize") payload = Helper.join(payload, ByteArray(roundedSize - payload.size)) } } log.debug("entry($name): header ${header.size} + data ${payload.size} = ${header.size + payload.size}") return Helper.join(header, payload) } fun encode2(): ByteArray { val baos = ByteArrayOutputStream() val cpio = CpioArchiveOutputStream(baos) val entry = CpioArchiveEntry(CpioConstants.FORMAT_NEW, name).apply { inode = ino uid = 0 gid = 0 mode = statMode numberOfLinks = 1 time = 0 size = data.size.toLong() deviceMaj = 0 deviceMin = 0 remoteDeviceMaj = 0 remoteDeviceMin = 0 chksum = 0 } cpio.putArchiveEntry(entry) cpio.write(data) cpio.closeArchiveEntry() return baos.toByteArray() } data class FileMode( var type: String = "", var sbits: String = "", //suid, sgid, sticky var perm: String = "" ) companion object { private val log = LoggerFactory.getLogger(AndroidCpioEntry::class.java) private val S_IFDIR = java.lang.Long.valueOf("040000", 8) private val S_IFCHR = java.lang.Long.valueOf("020000", 8) private val S_IFBLK = java.lang.Long.valueOf("060000", 8) private val S_IFREG = java.lang.Long.valueOf("100000", 8) private val S_IFIFO = java.lang.Long.valueOf("010000", 8) private val S_IFLNK = java.lang.Long.valueOf("120000", 8) private val S_IFSOCK = java.lang.Long.valueOf("140000", 8) private val S_ISUID = java.lang.Long.valueOf("4000", 8) private val S_ISGID = java.lang.Long.valueOf("2000", 8) private val S_ISVTX = java.lang.Long.valueOf("1000", 8) private val S_IREAD = java.lang.Long.valueOf("400", 8) private val S_IWRITE = java.lang.Long.valueOf("200", 8) private val S_IEXEC = java.lang.Long.valueOf("100", 8) private val MASK_S_IRWXU = S_IREAD or S_IWRITE or S_IEXEC private val MASK_S_IRWXG = MASK_S_IRWXU shr 3 private val MASK_S_IRWXO = MASK_S_IRWXG shr 3 private val MASK_ACCESSPERMS = MASK_S_IRWXU or MASK_S_IRWXG or MASK_S_IRWXO fun interpretMode(mode: Long): FileMode { return FileMode().let { fm -> val m = mode and java.lang.Long.valueOf("0170000", 8) // S_IFMT fm.type = when (m) { S_IFREG -> "REG" S_IFCHR -> "CHR" S_IFBLK -> "BLK" S_IFDIR -> "DIR" S_IFIFO -> "FIFO" S_IFLNK -> "LNK" S_IFSOCK -> "SOCK" else -> throw IllegalArgumentException("unknown file type " + java.lang.Long.toOctalString(m)) } if ((mode and S_ISUID) != 0L) { fm.sbits += if (fm.sbits.isEmpty()) "suid" else "|suid" } if ((mode and S_ISGID) != 0L) { fm.sbits += if (fm.sbits.isEmpty()) "sgid" else "|sgid" } if ((mode and S_ISVTX) != 0L) { fm.sbits += if (fm.sbits.isEmpty()) "sticky" else "|sticky" } fm.perm = java.lang.Long.toOctalString(mode and MASK_ACCESSPERMS) fm } } } }
apache-2.0
b1d80b939b155b25844808028376f96b
39.076923
153
0.572251
3.884746
false
false
false
false
Kotlin/kotlinx.serialization
benchmark/src/jmh/kotlin/kotlinx/benchmarks/json/ContextualOverheadBenchmark.kt
1
2339
package kotlinx.benchmarks.json import kotlinx.serialization.* import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.descriptors.buildClassSerialDescriptor import kotlinx.serialization.descriptors.element import kotlinx.serialization.encoding.* import kotlinx.serialization.json.* import kotlinx.serialization.modules.* import org.openjdk.jmh.annotations.* import java.util.concurrent.* @Warmup(iterations = 7, time = 1) @Measurement(iterations = 5, time = 1) @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MILLISECONDS) @State(Scope.Benchmark) @Fork(1) open class ContextualOverheadBenchmark { @Serializable data class Holder(val data: @Contextual Data) class Data(val a: Int, val b: String) object DataSerializer: KSerializer<Data> { override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Serializer") { element<Int>("a") element<String>("b") } override fun deserialize(decoder: Decoder): Data { return decoder.decodeStructure(descriptor) { var a = 0 var b = "" while (true) { when (val index = decodeElementIndex(descriptor)) { 0 -> a = decodeIntElement(descriptor, 0) 1 -> b = decodeStringElement(descriptor, 1) CompositeDecoder.DECODE_DONE -> break else -> error("Unexpected index: $index") } } Data(a, b) } } override fun serialize(encoder: Encoder, value: Data) { encoder.encodeStructure(descriptor) { encodeIntElement(descriptor, 0, value.a) encodeStringElement(descriptor, 1, value.b) } } } private val module = SerializersModule { contextual(DataSerializer) } private val json = Json { serializersModule = module } private val holder = Holder(Data(1, "abc")) private val holderString = json.encodeToString(holder) private val holderSerializer = serializer<Holder>() @Benchmark fun decode() = json.decodeFromString(holderSerializer, holderString) @Benchmark fun encode() = json.encodeToString(holderSerializer, holder) }
apache-2.0
e2c9c3c9b18eaf57ceec9b389e43f3c3
31.486111
94
0.636597
4.913866
false
false
false
false
sabi0/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/util/scenarios/RunConfigurationModel.kt
1
9294
// 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.testGuiFramework.util.scenarios import com.intellij.testGuiFramework.util.FinderPredicate import com.intellij.testGuiFramework.fixtures.JDialogFixture import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.impl.* import com.intellij.testGuiFramework.util.Predicate import com.intellij.testGuiFramework.util.logTestStep import com.intellij.testGuiFramework.utils.TestUtilsClass import com.intellij.testGuiFramework.utils.TestUtilsClassCompanion import org.fest.swing.exception.ComponentLookupException class RunConfigurationModel(testCase: GuiTestCase) : TestUtilsClass(testCase) { companion object : TestUtilsClassCompanion<RunConfigurationModel>( { RunConfigurationModel(it) } ) object Constants { const val runConfigTitle = "Run/Debug Configurations" const val buttonCancel = "Cancel" const val buttonOK = "OK" } enum class FieldKind { Text, Check, Choice, List, Tree, Combo, Custom } data class CustomConfigurationField( val actionIsPresent: (RunConfigurationModel, String) -> Boolean, val actionGetValue: (RunConfigurationModel, String) -> String?, val actionSetValue: (RunConfigurationModel, String, String) -> Unit) { companion object { val envVarsField = CustomConfigurationField( actionIsPresent = { model: RunConfigurationModel, title: String -> with(model.connectDialog()) { model.guiTestCase.exists { textfield(title, timeout = Timeouts.noTimeout) } } }, actionSetValue = { model, title: String, value: String -> with(model.connectDialog()) { val field = componentWithBrowseButton(title) field.clickAnyExtensionButton() if (value.isNotEmpty()) model.guiTestCase.envVarsModel.paste(value) else { model.guiTestCase.envVarsModel.removeAll(textfield(title).text() ?: "") } } }, actionGetValue = { model, title: String -> with(model.connectDialog()) { textfield(title).text() } } ) } } data class ConfigurationField( val title: String, val kind: FieldKind, val custom: CustomConfigurationField? = null, val predicate: FinderPredicate = Predicate.equality) { init { if (kind == FieldKind.Custom && custom == null) throw IllegalStateException("Handler for custom field '$title' must be set") } override fun toString() = "$title : $kind" fun RunConfigurationModel.isFieldPresent(): Boolean { with(connectDialog()) { return when (kind) { RunConfigurationModel.FieldKind.Text -> guiTestCase.exists { textfield(title, timeout = Timeouts.noTimeout) } RunConfigurationModel.FieldKind.Check -> guiTestCase.exists { checkbox(title, timeout = Timeouts.noTimeout) } RunConfigurationModel.FieldKind.Choice -> TODO() RunConfigurationModel.FieldKind.List -> TODO() RunConfigurationModel.FieldKind.Tree -> TODO() RunConfigurationModel.FieldKind.Combo -> guiTestCase.exists { combobox(title, timeout = Timeouts.noTimeout) } RunConfigurationModel.FieldKind.Custom -> custom?.actionIsPresent?.invoke(this@isFieldPresent, title) ?: throw IllegalStateException( "Handler for field '$title' not set") } } } fun RunConfigurationModel.getFieldValue(): String { with(connectDialog()) { val actualValue = when (kind) { FieldKind.Text -> textfield(title).text() FieldKind.Check -> checkbox(title).isSelected.toString() FieldKind.Choice -> TODO() FieldKind.List -> TODO() FieldKind.Tree -> TODO() FieldKind.Combo -> combobox(title).selectedItem() FieldKind.Custom -> custom?.actionGetValue?.invoke(this@getFieldValue, title) ?: throw IllegalStateException( "Handler for field '$title' not set") } return actualValue ?: throw ComponentLookupException("Cannot find component with label `$title`") } } fun RunConfigurationModel.setFieldValue(value: String) { with(connectDialog()) { when (kind) { FieldKind.Text -> textfield(title).setText(value) FieldKind.Check -> checkbox(title).isSelected = value.toBoolean() FieldKind.Choice -> TODO() FieldKind.List -> TODO() FieldKind.Tree -> TODO() FieldKind.Combo -> { val combo = combobox(title) val newValue = combo.listItems().firstOrNull { predicate(it, value) } combo.selectItem(newValue) } FieldKind.Custom -> custom?.actionSetValue?.invoke(this@setFieldValue, title, value) ?: throw IllegalStateException( "Handler for field '$title' not set") } } } } enum class ApplicationFields(val conf: ConfigurationField) { MainClass(ConfigurationField("Main class:", FieldKind.Text)), VMOptions(ConfigurationField("VM options:", FieldKind.Text)), ProgramArgs(ConfigurationField("Program arguments:", FieldKind.Text)), WorkingDir(ConfigurationField("Working directory:", FieldKind.Text)), EnvVars(ConfigurationField("Environment variables:", FieldKind.Custom, custom = CustomConfigurationField.envVarsField)), UseModule(ConfigurationField("Use classpath of module:", FieldKind.Combo)), ProvidedScope(ConfigurationField("Include dependencies with \"Provided\" scope", FieldKind.Check)), JRE(ConfigurationField("JRE:", FieldKind.Combo, predicate = Predicate.startWith)), ShortenCmdLine(ConfigurationField("Shorten command line:", FieldKind.Combo, predicate = Predicate.startWith)), CapturingSnapshots(ConfigurationField("Enable capturing form snapshots", FieldKind.Check)), BeforeLaunch(ConfigurationField("Before launch:", FieldKind.List)) } enum class GlassfishFields(val conf: ConfigurationField) { AppServer(ConfigurationField("Application server:", FieldKind.Combo)), URL(ConfigurationField("URL:", FieldKind.Text)), AfterLaunchCheck(ConfigurationField("After launch", FieldKind.Check)), AfterLaunchCombo(ConfigurationField("After launch", FieldKind.Combo)), WithJavaScriptDebugger(ConfigurationField("with JavaScript debugger", FieldKind.Check)), VMOptions(ConfigurationField("VM options:", FieldKind.Text)), OnUpdateAction(ConfigurationField("On 'Update' action:", FieldKind.Combo)), ShowDialog(ConfigurationField("Show dialog", FieldKind.Check)), OnFrameDeactivation(ConfigurationField("On frame deactivation:", FieldKind.Combo)), JRE(ConfigurationField("JRE:", FieldKind.Combo, predicate = Predicate.startWith)), ServerDomain(ConfigurationField("Server Domain:", FieldKind.Combo)), Username(ConfigurationField("Username:", FieldKind.Text)), Password(ConfigurationField("Password:", FieldKind.Text)), PreserveSessions(ConfigurationField("Preserve Sessions Across Redeployment", FieldKind.Check)), JavaEE5Compat(ConfigurationField("Java EE 5 compatibility", FieldKind.Check)), } } val GuiTestCase.runConfigModel by RunConfigurationModel fun RunConfigurationModel.connectDialog(): JDialogFixture = guiTestCase.dialog(RunConfigurationModel.Constants.runConfigTitle, true, Timeouts.defaultTimeout) fun RunConfigurationModel.checkConfigurationExistsAndSelect(vararg configuration: String) { with(connectDialog()) { guiTestCase.logTestStep("Going to check that configuration '${configuration.joinToString()}' exists") assert(guiTestCase.exists { jTree(*configuration) }) jTree(*configuration).clickPath() } } fun RunConfigurationModel.closeWithCancel() { with(connectDialog()) { button(RunConfigurationModel.Constants.buttonCancel).click() } } fun RunConfigurationModel.closeWithOK() { with(connectDialog()) { button(RunConfigurationModel.Constants.buttonOK).click() } } fun RunConfigurationModel.checkOneValue(expectedField: RunConfigurationModel.ConfigurationField, expectedValue: String) { with(expectedField) { if (!isFieldPresent()) throw ComponentLookupException("Cannot find component with label `$title`") val actualValue = getFieldValue() guiTestCase.logTestStep("Field `$title`: actual value = `$actualValue`, expected value = `$expectedValue`") assert(predicate(actualValue, expectedValue)) { "Field `$title`: actual value = `$actualValue`, expected value = `$expectedValue`" } } } fun RunConfigurationModel.changeOneValue(expectedField: RunConfigurationModel.ConfigurationField, newValue: String) { with(expectedField) { if (!isFieldPresent()) throw ComponentLookupException("Cannot find component with label `$title`") guiTestCase.logTestStep("Going to set field `${expectedField.title}`to a value = `$newValue`") setFieldValue(newValue) } } fun RunConfigurationModel.printHierarchy() { with(connectDialog()) { println(ScreenshotOnFailure.getHierarchy()) } }
apache-2.0
211631b2920d8dcf5269302b8af14dfe
43.261905
140
0.701205
4.883868
false
true
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/service/internal/testing/ModelProvidersServiceTest.kt
1
3717
// Copyright 2021 The Cross-Media Measurement 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.wfanet.measurement.kingdom.service.internal.testing import com.google.common.truth.Truth.assertThat import com.google.common.truth.extensions.proto.ProtoTruth.assertThat import io.grpc.Status import io.grpc.StatusRuntimeException import kotlin.test.assertFailsWith import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.common.identity.ExternalId import org.wfanet.measurement.common.identity.IdGenerator import org.wfanet.measurement.common.identity.InternalId import org.wfanet.measurement.common.identity.testing.FixedIdGenerator import org.wfanet.measurement.internal.kingdom.GetModelProviderRequest import org.wfanet.measurement.internal.kingdom.ModelProvider import org.wfanet.measurement.internal.kingdom.ModelProvidersGrpcKt.ModelProvidersCoroutineImplBase import org.wfanet.measurement.internal.kingdom.getModelProviderRequest private const val EXTERNAL_MODEL_PROVIDER_ID = 123L private const val FIXED_GENERATED_INTERNAL_ID = 2345L private const val FIXED_GENERATED_EXTERNAL_ID = 6789L @RunWith(JUnit4::class) abstract class ModelProvidersServiceTest { protected val idGenerator = FixedIdGenerator( InternalId(FIXED_GENERATED_INTERNAL_ID), ExternalId(FIXED_GENERATED_EXTERNAL_ID) ) protected lateinit var modelProvidersService: ModelProvidersCoroutineImplBase /** Creates a /ModelProviders service implementation using [idGenerator]. */ protected abstract fun newService(idGenerator: IdGenerator): ModelProvidersCoroutineImplBase @Before fun initService() { modelProvidersService = newService(idGenerator) } @Test fun `getModelProvider fails for missing ModelProvider`() = runBlocking { val exception = assertFailsWith<StatusRuntimeException> { modelProvidersService.getModelProvider( getModelProviderRequest { externalModelProviderId = EXTERNAL_MODEL_PROVIDER_ID } ) } assertThat(exception.status.code).isEqualTo(Status.Code.NOT_FOUND) assertThat(exception).hasMessageThat().contains("NOT_FOUND: ModelProvider not found") } @Test fun `createModelProvider succeeds`() = runBlocking { val modelProvider = ModelProvider.getDefaultInstance() val createdModelProvider = modelProvidersService.createModelProvider(modelProvider) assertThat(createdModelProvider) .isEqualTo( modelProvider .toBuilder() .apply { externalModelProviderId = FIXED_GENERATED_EXTERNAL_ID } .build() ) } @Test fun `getModelProvider succeeds`() = runBlocking { val modelProvider = ModelProvider.getDefaultInstance() val createdModelProvider = modelProvidersService.createModelProvider(modelProvider) val modelProviderRead = modelProvidersService.getModelProvider( GetModelProviderRequest.newBuilder() .setExternalModelProviderId(createdModelProvider.externalModelProviderId) .build() ) assertThat(modelProviderRead).isEqualTo(createdModelProvider) } }
apache-2.0
a9836eea3c76f885f38fa6eb20b08739
36.17
99
0.779661
4.821012
false
true
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/action/wizard/table/TableCreationEditColumnDialog.kt
1
2493
package nl.hannahsten.texifyidea.action.wizard.table import com.intellij.openapi.ui.DialogBuilder import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.components.JBTextField import com.intellij.ui.components.panels.VerticalLayout import nl.hannahsten.texifyidea.util.addLabeledComponent import javax.swing.JComboBox import javax.swing.JPanel /** * Dialog to add a new column to the table. * * @author Abby Berkers */ class TableCreationEditColumnDialog( /** * The function to execute when clicking the OK button. */ private val onOkFunction: (title: String, columnType: ColumnType, columnIndex: Int) -> Unit, /** * The index of the column being edited. */ private val editingColumn: Int, /** * The name of the column that is being edited. Default is the empty string, the title of a column that does * not yet exist. */ private val columnName: String = "", /** * The [ColumnType] of the column that is being edited. Default is a text column. */ private val columnType: ColumnType = ColumnType.TEXT_COLUMN ) { init { DialogBuilder().apply { // Text field for the name of the column, with the old name of the editing column filled in. val txtColumnName = JBTextField(columnName) // A combobox to select the column type. val cboxColumnType = JComboBox(ColumnType.values().map { it.displayName }.toTypedArray()) cboxColumnType.selectedIndex = ColumnType.values().indexOf(columnType) // Add UI elements. val panel = JPanel(VerticalLayout(8)).apply { addLabeledComponent(txtColumnName, "Column title:", labelWidth = 96, leftPadding = 0) addLabeledComponent(cboxColumnType, "Column type:", labelWidth = 96, leftPadding = 0) } setCenterPanel(panel) setPreferredFocusComponent(txtColumnName) addOkAction() setOkOperation { dialogWrapper.close(0) } if (columnName.isBlank()) { title("Add column") } else { title("Edit column") } if (show() == DialogWrapper.OK_EXIT_CODE) { onOkFunction(txtColumnName.text, ColumnType.values()[cboxColumnType.selectedIndex], editingColumn) } } } }
mit
c1ca5e7ba1234b68432a4a1e938465e0
32.702703
116
0.614521
4.936634
false
false
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/cryptography/encryptors.kt
1
3259
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ @file:JvmName("encryptors") package debop4k.core.cryptography import debop4k.core.collections.emptyByteArray import debop4k.core.collections.isNullOrEmpty import debop4k.core.utils.* import debop4k.core.utils.codecs.decodeHex import debop4k.core.utils.codecs.encodeHexAsString import org.jasypt.encryption.pbe.PooledPBEByteEncryptor import org.jasypt.salt.SaltGenerator abstract class AbstractSymmetricEncryptor @JvmOverloads protected constructor(override val algorithm: String, override val saltGenerator: SaltGenerator = ZERO_SALTGENERATOR) : Encryptor { override var password = DEFAULT_PASSWORD val encryptor: PooledPBEByteEncryptor = newEncryptor() private fun newEncryptor(): PooledPBEByteEncryptor { val encryptor = PooledPBEByteEncryptor() encryptor.setPoolSize(4) encryptor.setAlgorithm(algorithm) encryptor.setSaltGenerator(saltGenerator) encryptor.setPassword(password) return encryptor } override fun encrypt(message: ByteArray?): ByteArray { if (message.isNullOrEmpty) return emptyByteArray return encryptor.encrypt(message) } override fun encryptString(message: String?): String { if (message.isNullOrBlank()) return EMPTY_STRING return encryptor.encrypt(message.toUtf8Bytes()).encodeHexAsString() } override fun decrypt(encrypted: ByteArray?): ByteArray { if (encrypted.isNullOrEmpty) return emptyByteArray return encryptor.decrypt(encrypted) } override fun decryptString(encrypted: String?): String { if (encrypted.isNullOrBlank()) return EMPTY_STRING return encryptor.decrypt(encrypted.decodeHex()).toUtf8String() } companion object { @JvmStatic private val DEFAULT_PASSWORD = "@kesti21" } } /** * RC2 대칭형 알고리즘을 이용한 암호기 */ class RC2Encryptor @JvmOverloads constructor(saltGenerator: SaltGenerator = ZERO_SALTGENERATOR) : AbstractSymmetricEncryptor("PBEwithSHA1andRC2_40", saltGenerator) { } /** * DES 대칭형 알고리즘을 이용한 암호기 */ class DESEncryptor @JvmOverloads constructor(saltGenerator: SaltGenerator = ZERO_SALTGENERATOR) : AbstractSymmetricEncryptor("PBEwithMD5andDES", saltGenerator) { } /** * TripleDES 대칭형 알고리즘을 이용한 암호기 */ class TripleDESEncryptor @JvmOverloads constructor(saltGenerator: SaltGenerator = ZERO_SALTGENERATOR) : AbstractSymmetricEncryptor("PBEwithSHA1andDESEDE", saltGenerator) { // NOTE: "PBEWithMD5AndTripleDES" 는 JCE 를 설치해야만 가능합니다. (Oracle 사이트에서 따로 다운받아 JRE에 추가해야 합니다.) }
apache-2.0
50435aa567a4b7dff0943dd43790b1be
28.367925
99
0.755541
3.955527
false
false
false
false
ageery/kwicket
kwicket-kotlinx-html/src/main/kotlin/org/kwicket/kotlinx/html/WicketHtmlTags.kt
1
18499
package org.kwicket.kotlinx.html import kotlinx.html.A import kotlinx.html.BUTTON import kotlinx.html.DIV import kotlinx.html.FORM import kotlinx.html.FlowContent import kotlinx.html.FlowOrHeadingContent import kotlinx.html.FlowOrInteractiveOrPhrasingContent import kotlinx.html.FlowOrPhrasingContent import kotlinx.html.H1 import kotlinx.html.H2 import kotlinx.html.H3 import kotlinx.html.H4 import kotlinx.html.H5 import kotlinx.html.H6 import kotlinx.html.IMG import kotlinx.html.INPUT import kotlinx.html.InputType import kotlinx.html.LABEL import kotlinx.html.LEGEND import kotlinx.html.LI import kotlinx.html.OL import kotlinx.html.P import kotlinx.html.SELECT import kotlinx.html.SPAN import kotlinx.html.TABLE import kotlinx.html.TD import kotlinx.html.TEXTAREA import kotlinx.html.TH import kotlinx.html.TR import kotlinx.html.TagConsumer import kotlinx.html.TextAreaWrap import kotlinx.html.ThScope import kotlinx.html.UL import kotlinx.html.attributes.enumEncode import kotlinx.html.attributesMapOf import kotlinx.html.stream.appendHTML import kotlinx.html.visit import org.apache.wicket.Component import org.apache.wicket.Page import org.apache.wicket.behavior.AttributeAppender import org.apache.wicket.model.IModel import org.apache.wicket.request.mapper.parameter.PageParameters import org.apache.wicket.util.resource.IResourceStream import org.kwicket.behavior.VisibleWhen import org.kwicket.component.init import org.kwicket.toResourceStream import org.kwicket.wicket.core.markup.html.KWebMarkupContainer import org.kwicket.wicket.core.markup.html.basic.KLabel import org.kwicket.wicket.core.markup.html.form.KForm import org.kwicket.wicket.core.markup.html.link.KBookmarkablePageLink import org.kwicket.wicketIdAttr import kotlin.reflect.KClass fun FlowOrPhrasingContent.span( id: String, classes: String? = null, block: SPAN.() -> Unit = {} ): Unit = SPAN(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrPhrasingContent.span( model: IModel<*>, classes: String? = null, block: WICKET_SPAN.() -> Unit = {} ): Unit = WICKET_SPAN( id = null, builder = { KLabel(id = it, model = model) }, initialAttributes = attributesMapOf("class", classes), consumer = consumer ).visit(block) // FIXME: make the builder the first parameter fun FlowOrPhrasingContent.span( id: String? = null, builder: ((String) -> Component), classes: String? = null, block: WICKET_SPAN.() -> Unit = {} ): Unit = WICKET_SPAN( id, builder, attributesMapOf("class", classes, wicketIdAttr, id), consumer ).visit(block) fun FlowOrPhrasingContent.span( id: String? = null, classes: List<String>? = null, visible: (() -> Boolean)? = null, model: IModel<*>, block: WICKET_SPAN.() -> Unit = {} ): Unit = WICKET_SPAN( id, { KLabel(id = it, model = model, behaviors = listOfNotNull( visible?.let { VisibleWhen { visible() } }, classes?.let { AttributeAppender("class", classes.joinToString(" "), " ") } )) }, attributesMapOf(wicketIdAttr, id), consumer ).visit(block) // FIXME: add a function to generate a CSS class behavior -- "row".toCssClass() = Behavior; "row".css() = Behavior fun FlowContent.div( builder: ((String) -> Component) = { KWebMarkupContainer(id = it) }, id: String? = null, classes: String? = null, block: WICKET_DIV.() -> Unit = {} ): Unit = WICKET_DIV( id, builder, attributesMapOf("class", classes, wicketIdAttr, id), consumer ).visit(block) fun FlowContent.div( id: String? = null, classes: List<String>? = null, visible: (() -> Boolean)? = null, block: WICKET_DIV.() -> Unit = {} ): Unit = WICKET_DIV( id, { KWebMarkupContainer(id = it, behaviors = listOfNotNull( visible?.let { VisibleWhen { visible() } }, classes?.let { AttributeAppender("class", classes.joinToString(" "), " ") } )) }, attributesMapOf(wicketIdAttr, id), consumer ).visit(block) fun FlowContent.p(id: String? = null, classes: String? = null, block: P.() -> Unit = {}): Unit = P(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrPhrasingContent.p( model: IModel<*>, classes: List<String>? = null, block: WICKET_P.() -> Unit = {} ): Unit = WICKET_P( id = null, builder = { KLabel(id = it, model = model).init(behaviors = listOfNotNull( classes?.let { AttributeAppender("class", classes.joinToString(" "), " ") })) }, consumer = consumer ).visit(block) fun FlowOrInteractiveOrPhrasingContent.a( id: String? = null, classes: String? = null, block: A.() -> Unit = {} ): Unit = A(attributesMapOf(wicketIdAttr, id, "class", classes), consumer).visit(block) fun FlowContent.ul(id: String? = null, classes: String? = null, block: UL.() -> Unit = {}): Unit = UL(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrPhrasingContent.a( builder: (String) -> Component, classes: List<String>? = null, block: WICKET_A.() -> Unit = {} ): Unit = WICKET_A( id = null, builder = { builder(it).init(behaviors = listOfNotNull( classes?.let { AttributeAppender("class", classes.joinToString(" "), " ") } ))}, consumer = consumer ).visit(block) fun <P: Page> FlowOrPhrasingContent.a( page: KClass<P>, params: PageParameters? = null, classes: List<String>? = null, visible: (() -> Boolean)? = null, block: WICKET_A.() -> Unit = {} ): Unit = WICKET_A( id = null, builder = { KBookmarkablePageLink(id = it, page = page, params = params, behaviors = listOfNotNull( visible?.let { VisibleWhen { visible() } }, classes?.let { AttributeAppender("class", classes.joinToString(" "), " ") } )) }, consumer = consumer ).visit(block) fun FlowOrPhrasingContent.ul( classes: List<String>? = null, block: WICKET_UL.() -> Unit = {} ): Unit = WICKET_UL( id = null, builder = { KWebMarkupContainer(id = it, behaviors = listOfNotNull( classes?.let { AttributeAppender("class", classes.joinToString(" "), " ") } ))}, consumer = consumer ).visit(block) fun FlowOrPhrasingContent.ul( builder: (String) -> Component, block: WICKET_UL.() -> Unit = {} ): Unit = WICKET_UL( id = null, builder = builder, consumer = consumer ).visit(block) fun FlowOrPhrasingContent.li( builder: (String) -> Component, block: WICKET_LI.() -> Unit = {} ): Unit = WICKET_LI( id = null, builder = builder, consumer = consumer ).visit(block) fun FlowOrPhrasingContent.li( classes: List<String>? = null, model: IModel<*>, block: WICKET_LI.() -> Unit = {} ): Unit = WICKET_LI( id = null, builder = { KLabel(id = it, model = model, behaviors = listOfNotNull( classes?.let { AttributeAppender("class", classes.joinToString(" "), " ") } ))}, consumer = consumer ).visit(block) fun FlowOrPhrasingContent.form( builder: (String) -> Component, block: WICKET_FORM.() -> Unit = {} ): Unit = WICKET_FORM( id = null, builder = builder, consumer = consumer ).visit(block) fun FlowOrPhrasingContent.form( classes: List<String>? = null, model: IModel<*>, block: WICKET_FORM.() -> Unit = {} ): Unit = WICKET_FORM( id = null, builder = { KForm(id = it, model = model, behaviors = listOfNotNull( classes?.let { AttributeAppender("class", classes.joinToString(" "), " ") } ))}, consumer = consumer ).visit(block) fun FlowOrPhrasingContent.button( builder: (String) -> Component, block: WICKET_BUTTON.() -> Unit = {} ): Unit = WICKET_BUTTON( id = null, builder = builder, consumer = consumer ).visit(block) fun FlowContent.ol(id: String? = null, classes: String? = null, block: OL.() -> Unit = {}): Unit = OL(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun UL.li(id: String? = null, classes: String? = null, block: LI.() -> Unit = {}): Unit = LI(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowContent.table(id: String? = null, classes: String? = null, block: TABLE.() -> Unit = {}): Unit = TABLE(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrHeadingContent.h1(id: String? = null, classes: String? = null, block: H1.() -> Unit = {}): Unit = H1(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrHeadingContent.h2(id: String? = null, classes: String? = null, block: H2.() -> Unit = {}): Unit = H2(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrHeadingContent.h3(id: String? = null, classes: String? = null, block: H3.() -> Unit = {}): Unit = H3(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrHeadingContent.h4(id: String? = null, classes: String? = null, block: H4.() -> Unit = {}): Unit = H4(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrHeadingContent.h4( id: String? = null, classes: List<String>? = null, visible: (() -> Boolean)? = null, model: IModel<*>, block: WICKET_H4.() -> Unit = {} ): Unit = WICKET_H4( id, { KLabel(id = it, model = model, behaviors = listOfNotNull( visible?.let { VisibleWhen { visible() } }, classes?.let { AttributeAppender("class", classes.joinToString(" "), " ") } )) }, attributesMapOf(wicketIdAttr, id), consumer ).visit(block) fun FlowOrHeadingContent.h5( id: String? = null, classes: String? = null, block: H5.() -> Unit = {} ): Unit = H5(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrHeadingContent.h6(id: String? = null, classes: String? = null, block: H6.() -> Unit = {}): Unit = H6(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrInteractiveOrPhrasingContent.button( id: String? = null, classes: String? = null, block: BUTTON.() -> Unit = {} ): Unit = BUTTON(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrInteractiveOrPhrasingContent.input( id: String? = null, type: InputType? = null, classes: String? = null, block: INPUT.() -> Unit = {} ): Unit = INPUT(attributesMapOf("type", type?.enumEncode(), "class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrInteractiveOrPhrasingContent.img( id: String? = null, classes: String? = null, block: IMG.() -> Unit = {} ): Unit = IMG( attributesMapOf("class", classes, wicketIdAttr, id), consumer ).visit(block) fun FlowOrInteractiveOrPhrasingContent.textArea( id: String? = null, rows: String? = null, cols: String? = null, wrap: TextAreaWrap? = null, classes: String? = null, block: TEXTAREA.() -> Unit = {} ): Unit = TEXTAREA( attributesMapOf( "rows", rows, "cols", cols, "wrap", wrap?.enumEncode(), "class", classes, wicketIdAttr, id ), consumer ).visit(block) fun FlowOrInteractiveOrPhrasingContent.label( id: String? = null, classes: String? = null, block: LABEL.() -> Unit = {} ): Unit = LABEL(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrPhrasingContent.label( id: String? = null, builder: ((String) -> Component), classes: String? = null, block: WICKET_LABEL.() -> Unit = {} ): Unit = WICKET_LABEL( id, builder, attributesMapOf("class", classes, wicketIdAttr, id), consumer ).visit(block) fun FlowOrPhrasingContent.label( id: String? = null, classes: List<String>? = null, visible: (() -> Boolean)? = null, model: IModel<*>, block: WICKET_LABEL.() -> Unit = {} ): Unit = WICKET_LABEL( id, { KLabel(id = it, model = model, behaviors = listOfNotNull( visible?.let { VisibleWhen { visible() } }, classes?.let { AttributeAppender("class", classes.joinToString(" "), " ") } )) }, attributesMapOf(wicketIdAttr, id), consumer ).visit(block) // FIXME: move the model to be the first arg fun FlowOrPhrasingContent.legend( model: IModel<*>, id: String? = null, classes: List<String>? = null, visible: (() -> Boolean)? = null, block: WICKET_LEGEND.() -> Unit = {} ): Unit = WICKET_LEGEND( id, { KLabel(id = it, model = model, behaviors = listOfNotNull( visible?.let { VisibleWhen { visible() } }, classes?.let { AttributeAppender("class", classes.joinToString(" "), " ") } )) }, attributesMapOf(wicketIdAttr, id), consumer ).visit(block) fun FlowOrInteractiveOrPhrasingContent.select( id: String? = null, classes: String? = null, block: SELECT.() -> Unit = {} ): Unit = SELECT(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun FlowOrPhrasingContent.select( id: String? = null, builder: ((String) -> Component), classes: String? = null, block: WICKET_SELECT.() -> Unit = {} ): Unit = WICKET_SELECT( id, builder, attributesMapOf("class", classes, wicketIdAttr, id), consumer ).visit(block) fun TABLE.tr(id: String? = null, classes: String? = null, block: TR.() -> Unit = {}): Unit = TR(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun TR.td(id: String? = null, classes: String? = null, block: TD.() -> Unit = {}): Unit = TD(attributesMapOf("class", classes, wicketIdAttr, id), consumer).visit(block) fun TR.th(id: String? = null, scope: ThScope? = null, classes: String? = null, block: TH.() -> Unit = {}): Unit = TH(attributesMapOf("scope", scope?.enumEncode(), "class", classes, wicketIdAttr, id), consumer).visit(block) fun panel(block: PANEL.() -> Unit = {}): IResourceStream = buildString { appendHTML().panel(block = block) }.toResourceStream() fun border(block: BORDER.() -> Unit = {}): IResourceStream = buildString { appendHTML().border(block = block) }.toResourceStream() fun extend(block: EXTEND.() -> Unit = {}): IResourceStream = buildString { appendHTML().extend(block = block) }.toResourceStream() fun attrs(initialAttributes: Map<String, String>, id: String?) = if (id == null) initialAttributes else initialAttributes + (wicketIdAttr to id) class WICKET_UL( override val id: String? = null, override val builder: (String) -> Component, initialAttributes: Map<String, String> = emptyMap(), consumer: TagConsumer<*> ) : UL(initialAttributes = attrs(initialAttributes, id), consumer = consumer), WicketTag class WICKET_LI( override val id: String? = null, override val builder: (String) -> Component, initialAttributes: Map<String, String> = emptyMap(), consumer: TagConsumer<*> ) : LI(initialAttributes = attrs(initialAttributes, id), consumer = consumer), WicketTag class WICKET_A( override val id: String? = null, override val builder: (String) -> Component, initialAttributes: Map<String, String> = emptyMap(), consumer: TagConsumer<*> ) : A(initialAttributes = attrs(initialAttributes, id), consumer = consumer), WicketTag class WICKET_SPAN( override val id: String? = null, override val builder: (String) -> Component, initialAttributes: Map<String, String>, consumer: TagConsumer<*> ) : SPAN(initialAttributes = attrs(initialAttributes, id), consumer = consumer), WicketTag class WICKET_P( override val id: String? = null, override val builder: (String) -> Component, initialAttributes: Map<String, String> = emptyMap(), consumer: TagConsumer<*> ) : P(initialAttributes = attrs(initialAttributes, id), consumer = consumer), WicketTag class WICKET_LABEL( override val id: String? = null, override val builder: (String) -> Component, initialAttributes: Map<String, String>, consumer: TagConsumer<*> ) : LABEL(initialAttributes = attrs(initialAttributes, id), consumer = consumer), WicketTag class WICKET_DIV( override val id: String? = null, override val builder: (String) -> Component, initialAttributes: Map<String, String>, consumer: TagConsumer<*> ) : DIV(initialAttributes = attrs(initialAttributes, id), consumer = consumer), WicketTag class WICKET_FORM( override val id: String? = null, override val builder: (String) -> Component, initialAttributes: Map<String, String> = emptyMap(), consumer: TagConsumer<*> ) : FORM(initialAttributes = attrs(initialAttributes, id), consumer = consumer), WicketTag class WICKET_BUTTON( override val id: String? = null, override val builder: (String) -> Component, initialAttributes: Map<String, String> = emptyMap(), consumer: TagConsumer<*> ) : BUTTON(initialAttributes = attrs(initialAttributes, id), consumer = consumer), WicketTag class WICKET_H4( override val id: String? = null, override val builder: (String) -> Component, initialAttributes: Map<String, String> = emptyMap(), consumer: TagConsumer<*> ) : H4(initialAttributes = attrs(initialAttributes, id), consumer = consumer), WicketTag class WICKET_SELECT( override val id: String? = null, override val builder: (String) -> Component, initialAttributes: Map<String, String> = emptyMap(), consumer: TagConsumer<*> ) : SELECT(initialAttributes = attrs(initialAttributes, id), consumer = consumer), WicketTag class WICKET_LEGEND( override val id: String? = null, override val builder: (String) -> Component, initialAttributes: Map<String, String> = emptyMap(), consumer: TagConsumer<*> ) : LEGEND(initialAttributes = attrs(initialAttributes, id), consumer = consumer), WicketTag
apache-2.0
4c25512d1dd182dab1bf0c62ae5eaabb
32.154122
119
0.636791
3.884712
false
false
false
false
Mithrandir21/Duopoints
app/src/main/java/com/duopoints/android/logistics/FavouriteManager.kt
1
1359
package com.duopoints.android.logistics import io.reactivex.Observable import io.reactivex.subjects.BehaviorSubject object FavouriteManager { const val key = "FAVOURITE_LIST" private val favouriteList: BehaviorSubject<Set<Short>> = BehaviorSubject.createDefault(hashSetOf()) init { val storedList: Set<Short>? = Pers.get(key) storedList?.let { favouriteList.onNext(it) } } fun clear() { Pers.delete(key) favouriteList.onNext(hashSetOf()) } fun observeFavouriteList(): Observable<List<Short>> { return favouriteList.map { it.toList() }.skip(1) } fun observeFavouriteListWithDefault(): Observable<List<Short>> { return favouriteList.map { it.toList() } } fun contains(pointTypeNumber: Short): Boolean { return favouriteList.value.contains(pointTypeNumber) } fun add(pointTypeNumber: Short) { val newSet: MutableSet<Short> = favouriteList.value.toMutableSet() newSet.add(pointTypeNumber) Pers.put(key, newSet) return favouriteList.onNext(newSet.toHashSet()) } fun remove(pointTypeNumber: Short) { val newSet: MutableSet<Short> = favouriteList.value.toMutableSet() newSet.remove(pointTypeNumber) Pers.put(key, newSet) return favouriteList.onNext(newSet.toHashSet()) } }
gpl-3.0
ef039a112a853b4144c1bc8858276ddc
28.565217
103
0.676968
4.143293
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/SimpleAdapter.kt
1
1560
package org.videolan.vlc.gui import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import org.videolan.medialibrary.media.MediaLibraryItem import org.videolan.tools.dp import org.videolan.vlc.databinding.SimpleItemBinding private val cb = object : DiffUtil.ItemCallback<MediaLibraryItem>() { override fun areItemsTheSame(oldItem: MediaLibraryItem, newItem: MediaLibraryItem) = oldItem == newItem override fun areContentsTheSame(oldItem: MediaLibraryItem, newItem: MediaLibraryItem) = true } class SimpleAdapter(val handler: ClickHandler) : ListAdapter<MediaLibraryItem, SimpleAdapter.ViewHolder>(cb) { interface ClickHandler { fun onClick(item: MediaLibraryItem) } private lateinit var inflater : LayoutInflater override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { if (!this::inflater.isInitialized) inflater = LayoutInflater.from(parent.context) return ViewHolder(handler, SimpleItemBinding.inflate(inflater, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.binding.item = getItem(position) holder.binding.imageWidth = 48.dp } fun isEmpty() = itemCount == 0 class ViewHolder(handler: ClickHandler, val binding: SimpleItemBinding) : RecyclerView.ViewHolder(binding.root) { init { binding.handler = handler } } }
gpl-2.0
54d753e8320b60a1b4670a0cb743d60a
35.302326
117
0.757051
4.952381
false
false
false
false
chrislo27/Baristron
src/chrislo27/discordbot/impl/baristron/goat/Cosmetics.kt
1
9948
/* * 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/>. */ /* * 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/>. */ enum class Backgrounds(val file: String, val nam: String) { DEFAULT("resources/goat/bg/rhythm.png", "Default"), AURORA("resources/goat/bg/aurora.png", "Aurora"), SUNSET("resources/goat/bg/sunset.png", "Sunset"), COSMIC_DANCE("resources/goat/bg/cosmic dance.png", "Cosmic Dance"), WINTER("resources/goat/bg/winter.png", "Winter"), FINAL_DESTINATION("resources/goat/bg/final destination.png", "Final Destination"), BUNNY_HOP("resources/goat/bg/bunny hop.png", "Bunny Hop"), HEY_BABY("resources/goat/bg/hey baby.png", "Hey Baby"), SPACE_DANCE("resources/goat/bg/space dance.png", "Space Dance"), SPACE_DANCE_R3("resources/goat/bg/space dance r3.png", "Space Dance (Remix 3)"), TRAM_AND_PAULINE_R3("resources/goat/bg/tram and pauline r3.png", "Tram and Pauline (Remix 3)"), WIZARD_WALTZ("resources/goat/bg/wizard's waltz.png", "Wizard's Waltz"), MARCHING_ORDERS("resources/goat/bg/marching orders.png", "Marching Orders"), CROP_STOMP("resources/goat/bg/crop stomp.png", "Crop Stomp"), SPACEBALL("resources/goat/bg/spaceball.png", "Spaceball"), BON_ODORI("resources/goat/bg/bon-odori.png", "Bon-Odori"), BUILT_TO_SCALE_FEVER("resources/goat/bg/built to scale fever.png", "Built to Scale Fever"), CAFE("resources/goat/bg/cafe.png", "Cafe"), CHEER_READERS("resources/goat/bg/cheer readers.png", "Cheer Readers"), CLAPPY_TRIO("resources/goat/bg/clappy trio.png", "Clappy Trio"), DJ_SCHOOL("resources/goat/bg/dj school.png", "DJ School"), LIVING_ROOM("resources/goat/bg/living room.png", "Living Room"), NIGHT_WALK_FEVER("resources/goat/bg/night walk fever.png", "Night Walk Fever"), NINJA_BODYGUARD("resources/goat/bg/ninja bodyguard.png", "Ninja Bodyguard"), QUIZ_AUDIENCE("resources/goat/bg/quiz audience.png", "Quiz Audience"), RAP_MEN("resources/goat/bg/Rap Men.png", "Rap Men"), RINGSIDE_BG("resources/goat/bg/ringside.png", "Ringside"), SAMURAI_SLICE_FOGGY("resources/goat/bg/samurai slice foggy.png", "Samurai Slice Foggy"), SAMURAI_SLICE("resources/goat/bg/samurai slice.png", "Samurai Slice"), SNEAKY_SPIRITS("resources/goat/bg/sneaky spirits.png", "Sneaky Spirits"), TAP_TRIAL("resources/goat/bg/tap trial.png", "Tap Trial"), TENGAMI("resources/goat/bg/tengami.png", "Tengami"), TOSS_BOYS("resources/goat/bg/toss boys.png", "Toss Boys"), TRAM_AND_PAULINE("resources/goat/bg/tram and pauline.png", "Tram and Pauline"), BLUE("resources/goat/bg/blue.png", "Blue"), BAR("resources/goat/bg/bar.png", "Bar"), HEY_BABY_2("resources/goat/bg/hey baby 2.png", "Hey Baby 2"), NINJA_REINCARNATE("resources/goat/bg/ninja reincarnate.png", "Ninja Reincarnate"), SNAPPY_TRIO("resources/goat/bg/snappy trio.png", "Snappy Trio"), SNEAKY_SPIRITS_2("resources/goat/bg/sneaky spirits 2.png", "Sneaky Spirits 2"), RAP_WOMEN("resources/goat/bg/rap women.png", "Rap Women"), FLIPPER_FLOP("resources/goat/bg/flipper-flop.png", "Flipper-Flop"), DOG_NINJA("resources/goat/bg/dog ninja.png", "Dog Ninja"), DRUMMER_DUEL("resources/goat/bg/drummer duel.png", "Drummer Duel"), FAN_CLUB_2("resources/goat/bg/fan club 2.png", "Fan Club 2"), FRUIT_BASKET_2("resources/goat/bg/fruit basket 2.png", "Fruit Basket 2"), GLEE_CLUB_2("resources/goat/bg/glee club 2.png", "Glee Club 2"), SNEAKY_SPIRITS_STORY("resources/goat/bg/sneaky spirits story.png", "Sneaky Spirits (Story)"), SPACE_SOCCER("resources/goat/bg/space soccer.png", "Space Soccer"), FILLBOTS_BEE_REMIX("resources/goat/bg/fillbots bee.png", "Fillbots (Bee Remix)"), GLEE_CLUB_STORY("resources/goat/bg/glee club 1.png", "Glee Club 1"), SHOWTIME("resources/goat/bg/showtime.png", "Showtime"), FIREWORKS("resources/goat/bg/fireworks.png", "Fireworks"), FIREWORKS_SMILE("resources/goat/bg/fireworks-smile.png", "Fireworks Smile"); } enum class Faces(val file: String, val nam: String, val isMask: Boolean = false) { DEFAULT("resources/goat/face/smile.png", "Default"), DISAPPOINTED("resources/goat/face/disappointed.png", "Disappointed"), EYES_OPEN_SMILE("resources/goat/face/eyes_open_smile.png", "Smile"), FROWN("resources/goat/face/frown.png", "Frown"), GRIMACE("resources/goat/face/grimace.png", "Grimace"), SMIRK("resources/goat/face/smirk.png", "Smirk"), STARE("resources/goat/face/stare.png", "Stare"), YAWN("resources/goat/face/yawn.png", "Yawn"), PYROVISION("resources/goat/face/pyrovision.png", "Pyrovision Goggles"), MASK_WITH_YELLOW_HORNS("resources/goat/face/mask_with_yellow_horns.png", "Dededemask", isMask = true), LENNY("resources/goat/face/lenny.png", "Lenny"), ANNOYED("resources/goat/face/annoyed.png", "Annoyed"), SHOCK("resources/goat/face/shock.png", "Shock"), BEARD_BURGER("resources/goat/face/beard burger.png", "Beard Burger"), STOMP_FARMER("resources/goat/face/stomp farmer.png", "Stomp Farmer"), CHORUS_KID("resources/goat/face/chorus kid.png", "Chorus Kid"), GNOME("resources/goat/face/gnome.png", "Gnome"), GRAND("resources/goat/face/grand.png", "Grand"), LANKY_VILLAIN("resources/goat/face/lanky villain.png", "Lanky Villain"), SPACE_KICKER("resources/goat/face/space kicker.png", "Space Kicker"), COSMIC_DANCER("resources/goat/face/cosmic dancer.png", "Cosmic Dancer"), MULTIPLE_GRIN("resources/goat/face/multiple grin.png", "Multiple Grin"), SUNGLASSES_1("resources/goat/face/sunglasses 1.png", "Sunglasses 1"), SUNGLASSES_2("resources/goat/face/sunglasses 2.png", "Sunglasses 2"), SQUIRREL("resources/goat/face/squirrel.png", "Squirrel"), KARATE_JOE_SMIRK("resources/goat/face/karate joe smirk.png", "Karate Joe Smirk"), MANNEQUIN("resources/goat/face/mannequin.png", "Mannequin"), MEOW_MIXER("resources/goat/face/meow mixer.png", "Meow Mixer"), MR_UPBEAT("resources/goat/face/mr upbeat.png", "Mr. Upbeat"), O_O("resources/goat/face/o_O.png", "o_O"), RED_RAPPER("resources/goat/face/red rapper.png", "Red Rapper"), GOAT_EXE("resources/goat/face/goatexe.png", "Goat.exe"), DISGUST("resources/goat/face/disgust.png", "Disgust"), PAPRIKA("resources/goat/face/paprika.png", "Paprika", isMask = true), SAFFRON("resources/goat/face/saffron.png", "Saffron", isMask = true), SALTWATER("resources/goat/face/saltwater.png", "Saltwater", isMask = true), STARFY_FACE("resources/goat/face/starfy.png", "Starfy"), OWO("resources/goat/face/OwO.png", "OwO"), PLANETARY_DEER("resources/goat/face/planetary deer.png", "Planetary Deer"), FLOWEY("resources/goat/face/flowey.png", "Flowey"), STEPSWITCHER("resources/goat/face/stepswitcher.png", "Stepswitcher"), SANS("resources/goat/face/sans.png", "Sans"), MIMIKYU("resources/goat/face/mimikyu.png", "Mimikyu"), COLON_CAPITAL_D("resources/goat/face/colon_capital_d.png", ":D"), CAPITAL_X_CAPITAL_D("resources/goat/face/ecksdee.png", "XD"), PERIOD_UNDERSCORE_PERIOD("resources/goat/face/period_underscore_period.png", "._."), COLON_CARAT_RIGHT_PARENTHESE("resources/goat/face/tear smiley.png", ":^)"), YELLOW_RAPPER("resources/goat/face/yellow rapper.png", "Yellow Rapper"), ONE_EYE("resources/goat/face/one eye.png", "One-Eyed"), TIBBY("resources/goat/face/tibby.png", "Tibby"); } enum class Hats(val file: String, val nam: String, val helmet: Boolean = false, val head: Boolean = false) { GHOSTLY_GIBUS("resources/goat/hat/ghostly_gibus.png", "Ghostly Gibus"), STOMP_FARMER("resources/goat/hat/stomp farmer.png", "Stomp Farmer"), CHOWDER("resources/goat/hat/chowder.png", "Chowder"), GRAND("resources/goat/hat/grand.png", "Grand"), LANKY_VILLAIN("resources/goat/hat/lanky villain.png", "Lanky Villain"), MARCHERS("resources/goat/hat/marchers.png", "Marchers", helmet = true), GNOME("resources/goat/hat/gnome.png", "Gnome"), SPACE_KICKER("resources/goat/hat/space kicker.png", "Space Kicker", head = true), FEZ("resources/goat/hat/fez.png", "Fez"), UPSIDE_DOWN_BEARD("resources/goat/hat/upside down beard.png", "Upside-Down Beard"), HEADPHONES("resources/goat/hat/headphones.png", "Headphones"), GBA("resources/goat/hat/gba.png", "GBA", helmet = true), DS("resources/goat/hat/ds.png", "DS", helmet = true), THREE_DS("resources/goat/hat/3ds.png", "3DS", helmet = true), PAPRIKA("resources/goat/hat/paprika.png", "Paprika"), SAFFRON("resources/goat/hat/saffron.png", "Saffron"), SALTWATER("resources/goat/hat/saltwater.png", "Saltwater"), CLAPPY_TRIO("resources/goat/hat/clappy trio.png", "Clappy Trio"), GRAMPS("resources/goat/hat/gramps.png", "Gramps", head = true), HEADPHONES_2("resources/goat/hat/headphones 2.png", "Headphones 2"), SNAPPY_TRIO("resources/goat/hat/snappy trio.png", "Snappy Trio"), STAINLESS_POT("resources/goat/hat/stainless pot.png", "Stainless Pot"), TIBBY("resources/goat/hat/tibby.png", "Tibby"); }
gpl-3.0
a5f0c78538b116e6d07c69ac703e384f
56.172414
108
0.721049
2.769488
false
false
false
false
nemerosa/ontrack
ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/connector/graphql/GraphQLClientException.kt
1
912
package net.nemerosa.ontrack.kdsl.connector.graphql import com.apollographql.apollo.api.Error class GraphQLClientException(message: String) : RuntimeException(message) { companion object { fun errors(errors: List<Error>) = GraphQLClientException( message = errorsMessage(errors) ) private fun errorsMessage(errors: List<Error>): String = errors.map { errorMessage(it) }.joinToString("\n") { "* $it" } private fun errorMessage(error: Error): String { val base = error.message return if (error.locations.isNotEmpty()) { "$base. Locations: ${error.locations.joinToString { location -> locationMessage(location) }}" } else { "$base." } } private fun locationMessage(location: Error.Location) = "${location.line},${location.column}" } }
mit
80274dd56cda848e60b2a2b642e61b35
29.433333
109
0.605263
4.75
false
false
false
false
deadpixelsociety/twodee
src/main/kotlin/com/thedeadpixelsociety/twodee/systems/ContainerSystem.kt
1
1670
package com.thedeadpixelsociety.twodee.systems import com.badlogic.ashley.core.* /** * A container system collects entities of a specific family but does not actually do any processing on them. * @param family The entity family. * @param priority The system priority. */ open class ContainerSystem(val family: Family, priority: Int) : EntitySystem(priority), EntityListener { private val entities = hashSetOf<Entity>() /** * A container system collects entities of a specific family but does not actually do any processing on them. * @param family The entity family. */ constructor(family: Family) : this(family, 0) /** * Gets the entities currently in the system. * @return An immutable list of entities. */ fun entities() = entities.toList() override fun addedToEngine(engine: Engine?) { super.addedToEngine(engine) engine?.addEntityListener(family, this) } override fun removedFromEngine(engine: Engine?) { super.removedFromEngine(engine) engine?.removeEntityListener(this) } override fun entityAdded(entity: Entity?) { if (entity == null) return if (entities.add(entity)) onEntityAdded(entity) } override fun entityRemoved(entity: Entity?) { if (entity == null) return if (entities.remove(entity)) onEntityRemoved(entity) } /** * Called when a new entity has been added to the system. */ protected open fun onEntityAdded(entity: Entity) { } /** * Called when an entity has been removed from the system. */ protected open fun onEntityRemoved(entity: Entity) { } }
mit
bd8e538e3b0cd708d34bfa2cf80bd8e2
28.839286
113
0.67006
4.441489
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mixin/inspection/shadow/ShadowFieldPrefixInspection.kt
1
3370
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.shadow import com.demonwav.mcdev.platform.mixin.inspection.MixinInspection import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.SHADOW import com.demonwav.mcdev.platform.mixin.util.MixinConstants.DEFAULT_SHADOW_PREFIX import com.demonwav.mcdev.util.annotationFromValue import com.demonwav.mcdev.util.constantStringValue import com.demonwav.mcdev.util.findAnnotation import com.intellij.codeInsight.intention.QuickFixFactory import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.project.Project import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiAnnotationMemberValue import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiField import com.intellij.psi.PsiModifierList class ShadowFieldPrefixInspection : MixinInspection() { override fun getStaticDescription() = "Reports @Shadow fields with prefixes" override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitField(field: PsiField) { val shadow = field.findAnnotation(SHADOW) ?: return val prefix = shadow.findDeclaredAttributeValue("prefix") if (prefix != null) { holder.registerProblem(prefix, "Cannot use prefix for @Shadow fields", QuickFix) return } // Check if field name starts with default shadow prefix val fieldName = field.name if (fieldName.startsWith(DEFAULT_SHADOW_PREFIX)) { holder.registerProblem( field.nameIdentifier, "Cannot use prefix for @Shadow fields", QuickFixFactory.getInstance().createRenameElementFix( field, fieldName.removePrefix(DEFAULT_SHADOW_PREFIX) ) ) } } } private object QuickFix : LocalQuickFix { override fun getFamilyName() = "Remove @Shadow prefix" override fun startInWriteAction() = false override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as PsiAnnotationMemberValue // Get current prefix name val prefixName = element.constantStringValue!! // Delete prefix val shadow = element.annotationFromValue!! runWriteAction { shadow.setDeclaredAttributeValue<PsiAnnotationMemberValue>("prefix", null) } // Rename field (if necessary) val field = (shadow.owner as PsiModifierList).parent as PsiField val fieldName = field.name if (fieldName.startsWith(prefixName)) { // Rename field QuickFixFactory.getInstance().createRenameElementFix(field, fieldName.removePrefix(prefixName)) .applyFix() } } } }
mit
9131e67a0eb94ff1319a80b07de045d4
36.865169
111
0.677448
5.426731
false
false
false
false
oboehm/jfachwert
src/main/kotlin/de/jfachwert/bank/Geldbetrag.kt
1
47496
/* * Copyright (c) 2018-2020 by Oliver Boehm * * 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. * * (c)reated 18.07.2018 by oboehm ([email protected]) */ package de.jfachwert.bank import com.fasterxml.jackson.databind.annotation.JsonSerialize import com.fasterxml.jackson.databind.ser.std.ToStringSerializer import de.jfachwert.KFachwert import de.jfachwert.KSimpleValidator import de.jfachwert.bank.Waehrung.Companion.getSymbol import de.jfachwert.bank.Waehrung.Companion.toCurrency import de.jfachwert.bank.internal.GeldbetragFormatter import de.jfachwert.bank.internal.Zahlenwert import de.jfachwert.pruefung.NumberValidator import de.jfachwert.pruefung.exception.InvalidValueException import de.jfachwert.pruefung.exception.LocalizedArithmeticException import de.jfachwert.pruefung.exception.LocalizedMonetaryException import java.math.BigDecimal import java.math.RoundingMode import java.text.DecimalFormat import java.util.* import javax.money.* import javax.money.format.MonetaryAmountFormat import javax.money.format.MonetaryParseException /** * Diese Klasse unterstuetzt den JSR 354 und das [MonetaryAmount] * Interface, das Bestandteil von Java 9 ist. Da in alten Anwendungen * oftmals ein [BigDecimal] verwendet wurde, wird auch diese * Schnittstelle weitgehende unterstützt. Einzige Unterschied ist * die [MonetaryAmount.stripTrailingZeros]-Methode, die einen anderen * Rueckgabewert hat. Deswegen ist diese Klasse auch nicht von * [BigDecimal] abgeleitet... * * Im Gegensatz zur [org.javamoney.moneta.Money]- und * [org.javamoney.moneta.FastMoney]-Klasse kann diese Klasse * ueberschrieben werden, falls anderes Rundungsverhalten oder * eine angepasste Implementierung benoetigt wird. * * @author oboehm * @since 1.0 (18.07.2018) */ @JsonSerialize(using = ToStringSerializer::class) open class Geldbetrag @JvmOverloads constructor(betrag: Number, currency: CurrencyUnit, context: MonetaryContext = FACTORY.getMonetaryContextOf(betrag)) : MonetaryAmount, Comparable<MonetaryAmount>, KFachwert { private val betrag: BigDecimal private val context: MonetaryContext // Eine Umstellung auf 'Waehrung' oder 'Currency' fuehrt leider dazu, dass // dann das TCK zu JSR-354 fehlschlaegt, da Waehrung nicht final und damit // potentiell nicht immutable ist. Daher unterdruecken wir jetzt die // Sonar-Warnung "Make "currency" transient or serializable". @SuppressWarnings("squid:S1948") private val currency: CurrencyUnit /** * Erzeugt einen Geldbetrag in der aktuellen Landeswaehrung. * * @param betrag Geldbetrag, z.B. 1 */ constructor(betrag: Long) : this(BigDecimal.valueOf(betrag)) /** * Erzeugt einen Geldbetrag in der aktuellen Landeswaehrung. * * @param betrag Geldbetrag, z.B. 1.00 */ constructor(betrag: Double) : this(BigDecimal.valueOf(betrag)) /** * Erzeugt einen Geldbetrag in der aktuellen Landeswaehrung. * * @param betrag Geldbetrag, z.B. "1" */ constructor(betrag: String) : this(valueOf(betrag)) /** * Dies ist zum einen der CopyConstructor als Ersatz fuer eine * clone-Methode, zum anderen wandelt es einen [MonetaryAmount] * in ein GeldBetrag-Objekt. * * @param other der andere Geldbetrag */ constructor(other: MonetaryAmount) : this(other.number, Currency.getInstance(other.currency.currencyCode)) /** * Erzeugt einen Geldbetrag in der angegebenen Waehrung. * * @param betrag Geldbetrag, z.B. 1.00 * @param currency Waehrung, z.B. Euro */ @JvmOverloads constructor(betrag: Number, currency: Currency? = Waehrung.DEFAULT_CURRENCY) : this(betrag, Waehrung.of(currency!!)) /** * Liefert einen Geldbetrag mit der neuen gewuenschten Waehrung zurueck. * Dabei findet **keine** Umrechnung statt. * * Anmerkung: Der Prefix "with" kommt von der Namenskonvention in Scala * fuer immutable Objekte. * * @param unit die Waehrungseinheit * @return Geldbetrag mit neuer Waehrung */ fun withCurrency(unit: CurrencyUnit): Geldbetrag { return withCurrency(unit.currencyCode) } /** * Liefert einen Geldbetrag mit der neuen gewuenschten Waehrung zurueck. * Dabei findet **keine** Umrechnung statt. * * Anmerkung: Der Prefix "with" kommt von der Namenskonvention in Scala * fuer immutable Objekte. * * @param waehrung Waehrung * @return Geldbetrag mit neuer Waehrung */ fun withCurrency(waehrung: String): Geldbetrag { var normalized = waehrung.uppercase().trim { it <= ' ' } if ("DM".equals(normalized, ignoreCase = true)) { normalized = "DEM" } return withCurrency(Currency.getInstance(normalized)) } /** * Liefert einen Geldbetrag mit der neuen gewuenschten Waehrung zurueck. * Dabei findet **keine** Umrechnung statt. * * Anmerkung: Der Prefix "with" kommt von der Namenskonvention in Scala * fuer immutable Objekte. * * @param currency Waehrung * @return Geldbetrag mit neuer Waehrung */ fun withCurrency(currency: Currency?): Geldbetrag { return Geldbetrag(this.number, currency) } /** * Gibt den [MonetaryContext] des Geldbetrags zurueck. Der * [MonetaryContext] enthaelt Informationen ueber numerische * Eigenschaften wie Anzahl Nachkommastellen oder Rundungsinformation. * * @return den [MonetaryContext] zum Geldbetrag */ override fun getContext(): MonetaryContext { return context } /** * Erzeugt eine neue @code GeldbetragFactory}, die @link CurrencyUnit}, den * numerischen Werte und den aktuellen [MonetaryContext] verwendet. * * @return eine `GeldbetragFactory`, mit dem ein neuer (gleicher) * Geldbetrag erzeugt werden kann. */ override fun getFactory(): GeldbetragFactory { return GeldbetragFactory().setCurrency(currency).setNumber(betrag).setContext(context) } /** * Vergleicht zwei Instanzen von [MonetaryAmount]. Nicht signifikante * Nachkommastellen werden dabei ignoriert. * * @param amount Betrag eines `MonetaryAmount`, mit dem verglichen werid * @return `true` falls `amount > this`. * @throws MonetaryException bei unterschiedlichen Waehrungen. */ override fun isGreaterThan(amount: MonetaryAmount): Boolean { return this.compareTo(amount) > 0 } /** * Vergleicht zwei Instanzen von [MonetaryAmount]. Nicht signifikante * Nachkommastellen werden dabei ignoriert. * * @param amount Betrag eines `MonetaryAmount`, mit dem verglichen werid * @return `true` falls `amount >= this`. * @throws MonetaryException bei unterschiedlichen Waehrungen. */ override fun isGreaterThanOrEqualTo(amount: MonetaryAmount): Boolean { return this.compareTo(amount) >= 0 } /** * Vergleicht zwei Instanzen von [MonetaryAmount]. Nicht signifikante * Nachkommastellen werden dabei ignoriert. * * @param amount Betrag eines `MonetaryAmount`, mit dem verglichen werid * @return `true` falls `amount < this`. * @throws MonetaryException bei unterschiedlichen Waehrungen. */ override fun isLessThan(amount: MonetaryAmount): Boolean { return this.compareTo(amount) < 0 } /** * Vergleicht zwei Instanzen von [MonetaryAmount]. Nicht signifikante * Nachkommastellen werden dabei ignoriert. * * @param amount Betrag eines `MonetaryAmount`, mit dem verglichen werid * @return `true` falls `amount <= this`. * @throws MonetaryException bei unterschiedlichen Waehrungen. */ override fun isLessThanOrEqualTo(amount: MonetaryAmount): Boolean { return this.compareTo(amount) <= 0 } /** * Zwei Geldbetraege sind nur dann gleich, wenn sie die gleiche Waehrung * und den gleichen Betrag haben. Im Unterschied zu [.equals] * muessen die Betraege exakt gleich sein. * * @param other der andere Geldbetrag oder MonetaryAmount * @return true, falls Waehrung und Betrag gleich ist * @throws MonetaryException wenn die Waehrungen nicht uebereinstimmen */ override fun isEqualTo(other: MonetaryAmount): Boolean { checkCurrency(other) return isNumberEqualTo(other.number) } private fun isNumberEqualTo(value: NumberValue): Boolean { val otherValue = toBigDecimal(value, context) return betrag.compareTo(otherValue) == 0 } /** * Testet, ob der Betrag negativ ist. * * @return true bei negativen Betraegen */ override fun isNegative(): Boolean { return betrag.compareTo(BigDecimal.ZERO) < 0 } /** * Testet, ob der Betrag negativ oder Null ist. * * @return false bei positiven Betraegen */ override fun isNegativeOrZero(): Boolean { return betrag.compareTo(BigDecimal.ZERO) <= 0 } /** * Testet, ob der Betrag positiv ist. * * @return true bei positiven Betraegen */ override fun isPositive(): Boolean { return betrag.compareTo(BigDecimal.ZERO) > 0 } /** * Testet, ob der Betrag positiv oder Null ist. * * @return false bei negativen Betraegen */ override fun isPositiveOrZero(): Boolean { return betrag.compareTo(BigDecimal.ZERO) >= 0 } /** * Tested, ob der Betrag null ist. * * @return true, falls Betrag == 0 */ override fun isZero(): Boolean { return betrag.compareTo(BigDecimal.ZERO) == 0 } /** * Returns the signum function of this `MonetaryAmount`. * * @return -1, 0, or 1 as the value of this `MonetaryAmount` is negative, zero, or * positive. */ override fun signum(): Int { return toBigDecimal(number).signum() } /** * Liefert die Summe mit dem anderen Gelbetrag zurueck. Vorausgesetzt, * beide Betraege haben die gleichen Waehrungen. Einzige Ausnahem davon * ist die Addition von 0, da hier die Waehrung egal ist (neutrale * Operation). * * @param other value to be added to this `MonetaryAmount`. * @return `this + amount` * @throws ArithmeticException if the result exceeds the numeric capabilities * of this implementation class, i.e. the [MonetaryContext] cannot be adapted * as required. */ override fun add(other: MonetaryAmount?): Geldbetrag { if (betrag.compareTo(BigDecimal.ZERO) == 0) { return valueOf(other!!) } val n = toBigDecimal(other!!.number, context) if (n.compareTo(BigDecimal.ZERO) == 0) { return this } checkCurrency(other) return valueOf(betrag.add(n), currency) } /** * Returns a `MonetaryAmount` whose value is `this - * amount`, and whose scale is `max(this.scale(), * subtrahend.scale()`. * * @param amount value to be subtracted from this `MonetaryAmount`. * @return `this - amount` * @throws ArithmeticException if the result exceeds the numeric capabilities of this implementation class, i.e. * the [MonetaryContext] cannot be adapted as required. */ override fun subtract(amount: MonetaryAmount?): Geldbetrag { return add(amount!!.negate()) } /** * Returns a `MonetaryAmount` whose value is <tt>(this * multiplicand)</tt>, and whose scale is `this.scale() + * multiplicand.scale()`. * * @param multiplicand value to be multiplied by this `MonetaryAmount`. * @return `this * multiplicand` * @throws ArithmeticException if the result exceeds the numeric capabilities of this implementation class, i.e. * the [MonetaryContext] cannot be adapted as required. */ override fun multiply(multiplicand: Long): MonetaryAmount { return multiply(BigDecimal.valueOf(multiplicand)) } /** * Liefert einen GeldBetrag, desseen Wert <tt>(this * multiplicand)</tt> und desse Genauigkeit (scale) * `this.scale() + multiplicand.scale()` entspricht. * * @param multiplicand Multiplikant (wird evtl. gerundet, wenn die * Genauigkeit zu hoch ist * @return `this * multiplicand` * @throws ArithmeticException bei "unendlich" oder "NaN" als Mulitiplikant */ override fun multiply(multiplicand: Double): MonetaryAmount { return multiply(toBigDecimal(multiplicand)) } /** * Returns a `MonetaryAmount` whose value is <tt>(this * multiplicand)</tt>, and whose scale is `this.scale() + * multiplicand.scale()`. * * @param multiplicand value to be multiplied by this `MonetaryAmount`. If the multiplicand's scale exceeds * the * capabilities of the implementation, it may be rounded implicitly. * @return `this * multiplicand` * @throws ArithmeticException if the result exceeds the numeric capabilities of this implementation class, i.e. * the [MonetaryContext] cannot be adapted as required. */ override fun multiply(multiplicand: Number?): MonetaryAmount { val d = toBigDecimal(multiplicand!!, context) if (BigDecimal.ONE.compareTo(d) == 0) { return this } val multiplied = betrag.multiply(d) return valueOf(multiplied, currency) } /** * Returns a `MonetaryAmount` whose value is `this / * divisor`, and whose preferred scale is `this.scale() - * divisor.scale()`; if the exact quotient cannot be represented an `ArithmeticException` * is thrown. * * @param divisor value by which this `MonetaryAmount` is to be divided. * @return `this / divisor` * @throws ArithmeticException if the exact quotient does not have a terminating decimal expansion, or if the * result exceeds the numeric capabilities of this implementation class, i.e. the * [MonetaryContext] cannot be adapted as required. */ override fun divide(divisor: Long): Geldbetrag { return divide(BigDecimal.valueOf(divisor)) } /** * Returns a `MonetaryAmount` whose value is `this / * divisor`, and whose preferred scale is `this.scale() - * divisor.scale()`; if the exact quotient cannot be represented an `ArithmeticException` * is thrown. * * @param divisor value by which this `MonetaryAmount` is to be divided. * @return `this / divisor` * @throws ArithmeticException if the exact quotient does not have a terminating decimal expansion, or if the * result exceeds the numeric capabilities of this implementation class, i.e. the * [MonetaryContext] cannot be adapted as required. */ override fun divide(divisor: Double): MonetaryAmount { return if (isInfinite(divisor)) { valueOf(BigDecimal.ZERO, currency) } else divide(BigDecimal.valueOf(divisor)) } /** * Returns a `MonetaryAmount` whose value is `this / * divisor`, and whose preferred scale is `this.scale() - * divisor.scale()`; if the exact quotient cannot be represented an `ArithmeticException` * is thrown. * * @param divisor value by which this `MonetaryAmount` is to be divided. * @return `this / divisor` * @throws ArithmeticException if the exact quotient does not have a terminating decimal expansion, or if the * result exceeds the numeric capabilities of this implementation class, i.e. the * [MonetaryContext] cannot be adapted as required. */ override fun divide(divisor: Number?): Geldbetrag { val d = toBigDecimal(divisor!!, context) return if (BigDecimal.ONE.compareTo(d) == 0) { this } else valueOf(betrag.setScale(4, RoundingMode.HALF_UP).divide(d, RoundingMode.HALF_UP), currency) } /** * Returns a `MonetaryAmount` whose value is `this % divisor`. * * The remainder is given by * `this.subtract(this.divideToIntegralValue(divisor).multiply(divisor)` . Note that this * is not the modulo operation (the result can be negative). * * @param divisor value by which this `MonetaryAmount` is to be divided. * @return `this % divisor`. * @throws ArithmeticException if `divisor==0`, or if the result exceeds the numeric capabilities of this * implementation class, i.e. the [MonetaryContext] cannot be adapted as * required. */ override fun remainder(divisor: Long): Geldbetrag { return remainder(BigDecimal.valueOf(divisor)) } /** * Liefert eine @code Geldbetrag} zurueck, dessen Wert * `this % divisor` entspricht. Der Betrag kann auch * negativ sein (im Gegensatz zur Modulo-Operation). * * @param divisor Wert, durch den der `Geldbetrag` geteilt wird. * @return `this % divisor`. */ override fun remainder(divisor: Double): Geldbetrag { return if (isInfinite(divisor)) { valueOf(0, currency) } else remainder(toBigDecimal(divisor)) } /** * Returns a `MonetaryAmount` whose value is `this % divisor`. * * The remainder is given by * `this.subtract(this.divideToIntegralValue(divisor).multiply(divisor)` . Note that this * is not the modulo operation (the result can be negative). * * @param divisor value by which this `MonetaryAmount` is to be divided. * @return `this % divisor`. * @throws ArithmeticException if `divisor==0`, or if the result exceeds the numeric capabilities of this * implementation class, i.e. the [MonetaryContext] cannot be adapted as * required. */ override fun remainder(divisor: Number?): Geldbetrag { return valueOf(betrag.remainder(toBigDecimal(divisor!!, context)), currency) } /** * Liefert ein zwei-elementiges `Geldbatrag`-Array mit dem Ergebnis * `divideToIntegralValue` und`remainder`. * * @param divisor Teiler * @return ein zwei-elementiges `Geldbatrag`-Array * @throws ArithmeticException bei `divisor==0` * @see .divideToIntegralValue * @see .remainder */ override fun divideAndRemainder(divisor: Long): Array<Geldbetrag> { return divideAndRemainder(BigDecimal.valueOf(divisor)) } /** * Liefert ein zwei-elementiges `Geldbatrag`-Array mit dem Ergebnis * `divideToIntegralValue` und`remainder`. * * @param divisor Teiler * @return ein zwei-elementiges `Geldbatrag`-Array * @throws ArithmeticException bei `divisor==0` * @see .divideToIntegralValue * @see .remainder */ override fun divideAndRemainder(divisor: Double): Array<Geldbetrag> { return if (isInfinite(divisor)) { toGeldbetragArray(BigDecimal.ZERO, BigDecimal.ZERO) } else divideAndRemainder(BigDecimal.valueOf(divisor)) } /** * Liefert ein zwei-elementiges `Geldbetrag`-Array mit dem Ergebnis * `divideToIntegralValue` und`remainder`. * * @param divisor Teiler * @return ein zwei-elementiges `Geldbatrag`-Array * @throws ArithmeticException bei `divisor==0` * @see .divideToIntegralValue * @see .remainder */ override fun divideAndRemainder(divisor: Number?): Array<Geldbetrag> { val numbers = betrag.divideAndRemainder(toBigDecimal(divisor!!, context)) return toGeldbetragArray(*numbers) } private fun toGeldbetragArray(vararg numbers: BigDecimal): Array<Geldbetrag> { val betraege = Array<Geldbetrag>(numbers.size) { i -> valueOf(numbers[i], currency) } return betraege } /** * Liefert den Integer-Teil des Quotienten `this / divisor` * (abgerundet). * * @param divisor Teiler * @return Integer-Teil von `this / divisor`. * @throws ArithmeticException falls `divisor==0` * @see BigDecimal.divideToIntegralValue */ override fun divideToIntegralValue(divisor: Long): Geldbetrag { return divideToIntegralValue(BigDecimal.valueOf(divisor)) } /** * Liefert den Integer-Teil des Quotienten `this / divisor` * (abgerundet). * * @param divisor Teiler * @return Integer-Teil von `this / divisor`. * @throws ArithmeticException falls `divisor==0` * @see BigDecimal.divideToIntegralValue */ override fun divideToIntegralValue(divisor: Double): Geldbetrag { return divideToIntegralValue(BigDecimal.valueOf(divisor)) } /** * Liefert den Integer-Teil des Quotienten `this / divisor` * (abgerundet). * * @param divisor Teiler * @return Integer-Teil von `this / divisor`. * @throws ArithmeticException falls `divisor==0` * @see BigDecimal.divideToIntegralValue */ override fun divideToIntegralValue(divisor: Number): Geldbetrag { return valueOf(betrag.divideToIntegralValue(toBigDecimal(divisor, context)), currency) } /** * Liefert eine `Geldbetrag`, dessen Wert (`this` * 10<sup>n</sup>) * entspricht. * * @param power 10er-Potenz (z.B. 3 fuer 1000) * @return berechneter Geldbetrag */ override fun scaleByPowerOfTen(power: Int): Geldbetrag { //val scaled = betrag.scaleByPowerOfTen(power).setScale(context.maxScale, context.get(RoundingMode::class.java)) val scaled = betrag.scaleByPowerOfTen(power) return roundedValueOf(scaled, getCurrency(), context) } /** * Returns a `MonetaryAmount` whose value is the absolute value of this * `MonetaryAmount`, and whose scale is `this.scale()`. * * @return `abs(this)` */ override fun abs(): Geldbetrag { return if (betrag.compareTo(BigDecimal.ZERO) < 0) { negate() } else { this } } /** * Returns a `MonetaryAmount` whose value is `-this`, and whose scale is * `this.scale()`. * * @return `-this`. */ override fun negate(): Geldbetrag { return valueOf(betrag.negate(), currency) } /** * Liefert immer eine positiven Geldbetrag. * * @return positiver Geldbetrag * @see BigDecimal.plus */ override fun plus(): Geldbetrag { return if (betrag.compareTo(BigDecimal.ZERO) < 0) { negate() } else { this } } /** * Liefert einen `Geldbetrag`, der numerisch dem gleichen Wert * entspricht, aber ohne Nullen in den Nachkommastellen. * * @return im Priip der gleiche `Geldbetrag`, nur wird die Zahl * intern anders repraesentiert. */ override fun stripTrailingZeros(): Geldbetrag { return if (isZero) { valueOf(BigDecimal.ZERO, getCurrency()) } else valueOf(betrag.stripTrailingZeros(), getCurrency(), context) } /** * Vergleicht die Zahlenwerter der beiden Geldbetraege. Aber nur, wenn es * sich um die gleiche Waehrung handelt. Ansonsten wird die Waehrung als * Vergleichswert herangezogen. Dies fuehrt dazu, dass "CHF 1 < GBP 0" ist. * Dies ist leider durch das TCK so vorgegeben :-( * * @param other der andere Geldbetrag * @return 0 bei Gleicheit; negative Zahl, wenn dieser Geldbetrag kleiner * als der andere ist; sonst positive Zahl. */ override fun compareTo(other: MonetaryAmount): Int { val compare = getCurrency().currencyCode.compareTo(other.currency.currencyCode) if (compare == 0) { val n = toBigDecimal(other.number) return betrag.compareTo(n) } return compare } /** * Vergleicht nur den Zahlenwert und ignoriert die Waehrung. Diese Methode * ist aus Kompatibiltaetsgruenden zur BigDecimal-Klasse enthalten. * * @param other der andere Betrag * @return 0 bei Gleicheit; negative Zahl, wenn die Zahle kleiner als die * andere ist, sonst positive Zahl. */ operator fun compareTo(other: Number): Int { return this.compareTo(valueOf(other, currency)) } /** * Liefert die entsprechende Waehrungseinheit ([CurrencyUnit]). * * @return die entsprechende [CurrencyUnit], not null. */ override fun getCurrency(): CurrencyUnit { return currency } /** * Liefert den entsprechenden [NumberValue]. * * @return der entsprechende [NumberValue], not null. */ override fun getNumber(): NumberValue { return Zahlenwert(betrag) } /** * Liefert nur die Zahl als 'double' zurueck. Sie entspricht der * gleichnamigen Methode aus [BigDecimal]. * * @return Zahl als 'double' * @see BigDecimal.toDouble */ fun doubleValue(): Double { return betrag.toDouble() } /** * Hash-Code. * * @return a hash code value for this object. * @see Object.equals * @see System.identityHashCode */ override fun hashCode(): Int { return betrag.hashCode() } /** * Zwei Betraege sind gleich, wenn Betrag und Waehrung gleich sind. Im * Unterschied zu [.isEqualTo] wird hier nur der * sichtbare Teil fuer den Vergleich herangezogen, d.h. Rundungsdifferenzen * spielen beim Vergleich keine Rolle. * * @param other der Geldbetrag, mit dem verglichen wird * @return true, falls (optisch) gleich */ override fun equals(other: Any?): Boolean { if (other !is Geldbetrag) { return false } return if (!hasSameCurrency(other)) { false } else this.toString() == other.toString() } private fun hasSameCurrency(other: MonetaryAmount): Boolean { return getCurrency() == other.currency } private fun checkCurrency(other: MonetaryAmount) { if (!hasSameCurrency(other)) throw LocalizedMonetaryException("different currencies", this, other) } /** * Liefert das Ergebnis des Operator **vom selben Typ**. * * @param operator Operator (nicht null) * @return ein Objekt desselben Typs (nicht null) * @see javax.money.MonetaryAmount.with */ override fun with(operator: MonetaryOperator?): Geldbetrag { Objects.requireNonNull(operator) return try { operator!!.apply(this) as Geldbetrag } catch (ex: MonetaryException) { throw ex } catch (ex: RuntimeException) { throw LocalizedMonetaryException("operator failed", operator, ex) } } /** * Fraegt einen Wert an. * * @param query Anrfage (nicht null) * @return Ergebnis der Anfrage (kann null sein) * @see javax.money.MonetaryAmount.query */ override fun <R> query(query: MonetaryQuery<R>?): R { Objects.requireNonNull(query) return try { query!!.queryFrom(this) } catch (ex: MonetaryException) { throw ex } catch (ex: RuntimeException) { throw LocalizedMonetaryException("query failed", query, ex) } } /** * Gibt den Betrag in Kurz-Format aus: ohne Nachkommastellen und mit dem * Waehrungssymbol. * * @return z.B. "$19" */ fun toShortString(): String { return getSymbol(currency) + betrag.setScale(0, RoundingMode.HALF_UP) } /** * Um anzuzeigen, dass es ein Geldbtrag ist, wird zusaetzlich noch das * Waehrungszeichen (abhaengig von der eingestellten Locale) ausgegeben. * * @return z.B. "19.00 USD" * @see java.math.BigDecimal.toString */ override fun toString(): String { return DEFAULT_FORMATTER.format(this) } /** * Hier wird der Geldbetrag mit voller Genauigkeit ausgegeben. * * @return z.B. "19.0012 USD" */ fun toLongString(): String { val formatter = DecimalFormat.getInstance() formatter.minimumFractionDigits = context.maxScale formatter.minimumFractionDigits = context.maxScale return formatter.format(betrag) + " " + currency } /** * Dieser Validator ist fuer die Ueberpruefung von Geldbetraegen vorgesehen. * * @since 3.0 */ class Validator : KSimpleValidator<String> { /** * Validiert die uebergebene Zahl, ob sie sich als Geldbetrag eignet. * * @param value als String * @return die Zahl zur Weitervarabeitung */ override fun validate(value: String): String { return try { valueOf(value).toString() } catch (ex: IllegalArgumentException) { throw InvalidValueException(value, "money_amount", ex) } } } companion object { private val FACTORY = GeldbetragFactory() private val DEFAULT_FORMATTER = GeldbetragFormatter() private val NUMBER_VALIDATOR = NumberValidator() private val VALIDATOR: KSimpleValidator<String> = Validator() /** Da 0-Betraege relativ haeufig vorkommen, spendieren wir dafuer eine eigene Konstante. */ @JvmField val ZERO = Geldbetrag(BigDecimal.ZERO) /** Der minimale Betrag, den wir unterstuetzen. */ @JvmField val MIN_VALUE = Geldbetrag(BigDecimal.valueOf(Long.MIN_VALUE)) /** Der maximale Betrag, den wir unterstuetzen. */ @JvmField val MAX_VALUE = Geldbetrag(BigDecimal.valueOf(Long.MAX_VALUE)) /** Null-Konstante fuer Initialisierungen. */ @JvmField val NULL = ZERO /** * Hierueber kann eine Geldbetrag ueber die Anzahl an Cents angelegt * werden. * * @param cents Cent-Betrag, z.B. 42 * @return Geldbetrag, z.B. 0.42$ */ @JvmStatic fun fromCent(cents: Long): Geldbetrag { return ofMinor(Waehrung.of("EUR"), cents) } /** * Legt einen Geldbetrag unter Angabe der Unter-Einheit an. So liefert * `ofMinor(EUR, 12345)` die Instanz fuer '123,45 EUR' zurueck. * * Die Methode wurde aus Kompatibitaetsgrunden zur Money-Klasse * hinzugefuegt. * * @param currency Waehrung * @param amountMinor Betrag der Unter-Einzeit (z.B. 12345 Cents) * @param fractionDigits Anzahl der Nachkommastellen * @return Geldbetrag * @since 1.0.1 */ @JvmOverloads @JvmStatic fun ofMinor(currency: CurrencyUnit, amountMinor: Long, fractionDigits: Int = currency.defaultFractionDigits): Geldbetrag { return of(BigDecimal.valueOf(amountMinor, fractionDigits), currency) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * Diese Methode ist identisch mit der entsprechenden valueOf(..)-Methode. * * @param other the other * @return ein Geldbetrag */ @JvmStatic fun of(other: String): Geldbetrag { return valueOf(other) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * In Anlehnung an [BigDecimal] heisst die Methode "valueOf". * * @param other the other * @return ein Geldbetrag */ @JvmStatic fun valueOf(other: String): Geldbetrag { return try { DEFAULT_FORMATTER.parse(other) as Geldbetrag } catch (ex: MonetaryParseException) { throw IllegalArgumentException(other, ex) } } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * Diese Methode ist identisch mit der entsprechenden valueOf(..)-Methode. * * @param value Wert des andere Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun of(value: Long): Geldbetrag { return valueOf(Geldbetrag(value)) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * In Anlehnung an [BigDecimal] heisst die Methode "valueOf". * * @param value Wert des andere Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun valueOf(value: Long): Geldbetrag { return valueOf(Geldbetrag(value)) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * Diese Methode ist identisch mit der entsprechenden valueOf(..)-Methode. * * @param value Wert des andere Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun of(value: Double): Geldbetrag { return valueOf(Geldbetrag(value)) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * In Anlehnung an [BigDecimal] heisst die Methode "valueOf". * * @param value Wert des andere Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun valueOf(value: Double): Geldbetrag { return valueOf(Geldbetrag(value)) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * Diese Methode ist identisch mit der entsprechenden valueOf(..)-Methode. * * @param value Wert des andere Geldbetrags * @param currency Waehrung des anderen Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun of(value: Number, currency: String): Geldbetrag { return valueOf(value, currency) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * In Anlehnung an [BigDecimal] heisst die Methode "valueOf". * * @param value Wert des andere Geldbetrags * @param currency Waehrung des anderen Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun valueOf(value: Number, currency: String): Geldbetrag { return valueOf(value, toCurrency(currency)) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * Diese Methode ist identisch mit der entsprechenden valueOf(..)-Methode. * * @param value Wert des andere Geldbetrags * @param currency Waehrung des anderen Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun of(value: Number, currency: Currency): Geldbetrag { return valueOf(value, currency) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * In Anlehnung an [BigDecimal] heisst die Methode "valueOf". * * @param value Wert des andere Geldbetrags * @param currency Waehrung des anderen Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun valueOf(value: Number, currency: Currency): Geldbetrag { return valueOf(Geldbetrag(value, currency)) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * Diese Methode ist identisch mit der entsprechenden valueOf(..)-Methode. * * @param value Wert des andere Geldbetrags * @param currency Waehrung des anderen Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun of(value: Number, currency: CurrencyUnit): Geldbetrag { return valueOf(value, currency) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * In Anlehnung an [BigDecimal] heisst die Methode "valueOf". * * @param value Wert des andere Geldbetrags * @param currency Waehrung des anderen Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun valueOf(value: Number, currency: CurrencyUnit): Geldbetrag { return valueOf(Geldbetrag(value, currency)) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * Diese Methode ist identisch mit der entsprechenden valueOf(..)-Methode. * * @param value Wert des andere Geldbetrags * @param currency Waehrung des anderen Geldbetrags * @param monetaryContext Kontext des anderen Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun of(value: Number, currency: String, monetaryContext: MonetaryContext): Geldbetrag { return valueOf(value, currency, monetaryContext) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * In Anlehnung an [BigDecimal] heisst die Methode "valueOf". * * @param value Wert des andere Geldbetrags * @param currency Waehrung des anderen Geldbetrags * @param monetaryContext Kontext des anderen Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun valueOf(value: Number, currency: String, monetaryContext: MonetaryContext): Geldbetrag { return valueOf(value, Waehrung.of(currency), monetaryContext) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * Diese Methode ist identisch mit der entsprechenden valueOf(..)-Methode. * * @param value Wert des andere Geldbetrags * @param currency Waehrung des anderen Geldbetrags * @param monetaryContext Kontext des anderen Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun of(value: Number, currency: CurrencyUnit, monetaryContext: MonetaryContext): Geldbetrag { return valueOf(value, currency, monetaryContext) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * In Anlehnung an [BigDecimal] heisst die Methode "valueOf". * * @param value Wert des andere Geldbetrags * @param currency Waehrung des anderen Geldbetrags * @param monetaryContext Kontext des anderen Geldbetrags * @return ein Geldbetrag */ @JvmStatic fun valueOf(value: Number, currency: CurrencyUnit, monetaryContext: MonetaryContext): Geldbetrag { return valueOf(Geldbetrag(value, currency, monetaryContext)) } /** * Im Gegensatz zu valueOf wird hier keine [ArithmeticException] * geworfen, wenn Genauigkeit verloren geht. Stattdessen wird der * Wert gerundet. * * @param value Wert des andere Geldbetrags * @param currency Waehrung des anderen Geldbetrags * @param monetaryContext Kontext des anderen Geldbetrags * @return ein Geldbetrag * @since 4.0 */ @JvmStatic fun roundedValueOf(value: Number, currency: CurrencyUnit, monetaryContext: MonetaryContext): Geldbetrag { val roundedValue = toBigDecimalRounded(value, monetaryContext) return valueOf(Geldbetrag(roundedValue, currency, monetaryContext)) } /** * Erzeugt einen Geldbetrag anhand des uebergebenen Textes und mittels * des uebergebenen Formatters. * * @param text z.B. "12,25 EUR" * @param formatter Formatter * @return Geldbetrag */ @JvmOverloads @JvmStatic fun parse(text: CharSequence?, formatter: MonetaryAmountFormat = DEFAULT_FORMATTER): Geldbetrag { return from(formatter.parse(text)) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * Diese Methode ist identisch mit der entsprechenden of(..)-Methode und * wurde eingefuehrt, um mit der Money-Klasse aus "org.javamoney.moneta" * kompatibel zu sein. * * @param other the other * @return ein Geldbetrag */ @JvmStatic fun from(other: MonetaryAmount): Geldbetrag { return of(other) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * Diese Methode ist identisch mit der entsprechenden valueOf(..)-Methode. * * @param other the other * @return ein Geldbetrag */ @JvmStatic fun of(other: MonetaryAmount): Geldbetrag { return valueOf(other) } /** * Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die * Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine * neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. * * In Anlehnung an [BigDecimal] heisst die Methode "valueOf" . * * @param other the other * @return ein Geldbetrag */ @JvmStatic fun valueOf(other: MonetaryAmount): Geldbetrag { if (other is Geldbetrag) { return other } val value = other.number.numberValue(BigDecimal::class.java) return if (value == BigDecimal.ZERO) { ZERO } else Geldbetrag(value).withCurrency(other.currency) } /** * Validiert die uebergebene Zahl, ob sie sich als Geldbetrag eignet. * * @param zahl als String * @return die Zahl zur Weitervarabeitung */ @JvmStatic fun validate(zahl: String): String { return VALIDATOR.validate(zahl) } private fun toBigDecimal(value: NumberValue): BigDecimal { return value.numberValue(BigDecimal::class.java) } private fun toBigDecimal(value: NumberValue, mc: MonetaryContext): BigDecimal { val n: Number = toBigDecimal(value) return toBigDecimal(n, mc) } private fun toBigDecimal(value: Double): BigDecimal { NUMBER_VALIDATOR.verifyNumber(value) return BigDecimal.valueOf(value) } private fun isInfinite(divisor: Double): Boolean { if (divisor == Double.POSITIVE_INFINITY || divisor == Double.NEGATIVE_INFINITY) { return true } if (java.lang.Double.isNaN(divisor)) { throw ArithmeticException("invalid number: NaN") } return false } private fun toBigDecimal(value: Number, monetaryContext: MonetaryContext): BigDecimal { val n: BigDecimal = toBigDecimal(value) val rounded: BigDecimal = toBigDecimalRounded(value, monetaryContext) if (n.compareTo(rounded) != 0) { throw LocalizedArithmeticException(value, "lost_precision") } return n } private fun toBigDecimalRounded(value: Number, monetaryContext: MonetaryContext): BigDecimal { val n: BigDecimal = toBigDecimal(value) var roundingMode = monetaryContext.get(RoundingMode::class.java) if (roundingMode == null) { roundingMode = RoundingMode.HALF_UP } val scale = monetaryContext.maxScale return if (scale <= 0) { n } else { val scaled = n.setScale(scale, roundingMode) scaled } } private fun toBigDecimal(value: Number): BigDecimal { if (value is BigDecimal) { return value } else if (value is Zahlenwert) { return value.numberValue(BigDecimal::class.java) } return BigDecimal.valueOf(value.toDouble()) } } /** * Erzeugt einen Geldbetrag in der angegebenen Waehrung. */ init { this.betrag = toBigDecimal(betrag, context) this.currency = currency this.context = context } }
apache-2.0
fa321af0c804cb40778a94291a9d560e
35.367534
210
0.63573
3.835191
false
false
false
false
ArdentDiscord/ArdentKotlin
src/main/kotlin/main/Ardent.kt
1
11269
package main import Web import com.adamratzman.spotify.SpotifyApi import com.adamratzman.spotify.SpotifyAppApi import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport import com.google.api.client.http.HttpTransport import com.google.api.client.json.jackson2.JacksonFactory import com.google.api.services.sheets.v4.Sheets import com.google.api.services.youtube.YouTube import com.rethinkdb.RethinkDB import com.rethinkdb.net.Connection import com.sedmelluq.discord.lavaplayer.player.AudioConfiguration import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers import com.sedmelluq.discord.lavaplayer.source.http.HttpAudioSourceManager import com.sedmelluq.discord.lavaplayer.source.soundcloud.SoundCloudAudioSourceManager import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager import commands.`fun`.EightBall import commands.`fun`.FML import commands.`fun`.IsStreaming import commands.`fun`.Meme import commands.`fun`.UnixFortune import commands.`fun`.UrbanDictionary import commands.administrate.AdministrativeDaemon import commands.administrate.AdministratorCommand import commands.administrate.Automessages import commands.administrate.Blacklist import commands.administrate.Clear import commands.administrate.GiveRoleToAll import commands.info.About import commands.info.Donate import commands.info.GetId import commands.info.Help import commands.info.IamCommand import commands.info.IamnotCommand import commands.info.Invite import commands.info.Ping import commands.info.RoleInfo import commands.info.ServerInfo import commands.info.Status import commands.info.Support import commands.info.UserInfo import commands.info.WebsiteCommand import commands.music.ClearQueue import commands.music.GoTo import commands.music.GuildMusicManager import commands.music.MyMusicLibrary import commands.music.Pause import commands.music.Play import commands.music.Playing import commands.music.Playlist import commands.music.Queue import commands.music.RemoveFrom import commands.music.Repeat import commands.music.Resume import commands.music.Skip import commands.music.SongUrl import commands.music.Volume import commands.music.connect import commands.music.getAudioManager import commands.music.load import commands.music.play import commands.rpg.Balance import commands.rpg.Daily import commands.rpg.ProfileCommand import commands.rpg.TopMoney import commands.settings.Prefix import commands.settings.Settings import events.CommandFactory import events.JoinRemoveEvents import events.VoiceUtils import loginRedirect import net.dv8tion.jda.api.JDA import net.dv8tion.jda.api.JDABuilder import net.dv8tion.jda.api.entities.Activity import net.dv8tion.jda.api.entities.Guild import net.dv8tion.jda.api.hooks.AnnotatedEventManager import net.dv8tion.jda.api.requests.GatewayIntent import okhttp3.OkHttpClient import org.apache.commons.io.IOUtils import translation.LanguageCommand import translation.Translate import translation.tr import utils.discord.getGuildById import utils.discord.getTextChannelById import utils.discord.getVoiceChannelById import utils.discord.send import utils.functionality.EventWaiter import utils.functionality.logChannel import utils.functionality.queryAsArrayList import utils.music.LocalTrackObj import utils.music.ServerQueue import java.io.File import java.io.FileReader import java.io.IOException import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit import kotlin.properties.Delegates var test by Delegates.notNull<Boolean>() var beta = true var hangout: Guild? = null var r: RethinkDB = RethinkDB.r var conn: Connection? = null lateinit var config: Config var jdas = mutableListOf<JDA>() lateinit var waiter: EventWaiter lateinit var factory: CommandFactory val playerManager = DefaultAudioPlayerManager() val managers = ConcurrentHashMap<Long, GuildMusicManager>() lateinit var spotifyApi: SpotifyAppApi lateinit var hostname: String var transport: HttpTransport = GoogleNetHttpTransport.newTrustedTransport() var jsonFactory: JacksonFactory = JacksonFactory.getDefaultInstance() val sheets: Sheets = setupDrive() val youtube: YouTube = setupYoutube() val shards = 1 val httpClient = OkHttpClient() fun main(args: Array<String>) { config = Config(args[0]) test = config.getValue("test").toBoolean() hostname = if (test) "http://localhost" else "https://ardentbot.com" loginRedirect = "$hostname/api/oauth/login" /* val spreadsheet = sheets.spreadsheets().values().get("1qm27kGVQ4BdYjvPSlF0zM64j7nkW4HXzALFNcan4fbs", "A2:D").setKey(config.getValue("google")) .execute() spreadsheet.getValues().forEach { if (it.getOrNull(1) != null && it.getOrNull(2) != null) questions.add(TriviaQuestion(it[1] as String, (it[2] as String).split("~"), it[0] as String, (it.getOrNull(3) as String?)?.toIntOrNull() ?: 125)) } */Web() waiter = EventWaiter() factory = CommandFactory() spotifyApi = SpotifyApi.spotifyAppApi("79d455af5aea45c094c5cea04d167ac1", config.getValue("spotifySecret")).build() (1..shards).forEach { sh -> jdas.add(JDABuilder.create(config.getValue("token"), GatewayIntent.values().toList()) .setActivity(Activity.playing("Play music with Ardent. /play")) .addEventListeners(waiter, factory, JoinRemoveEvents(), VoiceUtils()) .setEventManager(AnnotatedEventManager()) // .useSharding(sh - 1, shards) .setToken(config.getValue("token")) .build()) } logChannel = getTextChannelById("351368131639246848") hangout = getGuildById("351220166018727936") playerManager.configuration.resamplingQuality = AudioConfiguration.ResamplingQuality.LOW playerManager.registerSourceManager(YoutubeAudioSourceManager()) playerManager.registerSourceManager(SoundCloudAudioSourceManager.createDefault()) playerManager.registerSourceManager(HttpAudioSourceManager()) AudioSourceManagers.registerRemoteSources(playerManager) AudioSourceManagers.registerLocalSource(playerManager) val administrativeDaemon = AdministrativeDaemon() // administrativeExecutor.scheduleAtFixedRate(administrativeDaemon, 15, 30, TimeUnit.SECONDS) addCommands() waiter.executor.schedule({ checkQueueBackups() }, 45, TimeUnit.SECONDS) waiter.executor.scheduleWithFixedDelay({}, 30, 30, TimeUnit.SECONDS) } /** * Config class represents a text file with the following syntax on each line: KEY :: VALUE */ data class Config(val url: String) { private val keys: MutableMap<String, String> = hashMapOf() init { try { val keysTemp = IOUtils.readLines(FileReader(File(url))) keysTemp.forEach { pair -> val keyPair = pair.split(" :: ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() if (keyPair.size == 2) keys.put(keyPair[0], keyPair[1]) } conn = r.connection().db("ardent_v2").hostname("localhost").connect() insertDbScaffold() } catch (e: IOException) { println("Unable to load Config, exiting now") e.printStackTrace() System.exit(1) } } fun getValue(keyName: String): String { return (keys as Map<String, String>).getOrDefault(keyName, "not_available") } } fun insertDbScaffold() { if (!r.dbList().run<List<String>>(conn).contains("ardent_v2")) r.dbCreate("ardent_v2").run<Any>(conn) val tables = listOf("savedQueues", "staff", "patrons", "musicPlaylists", "musicLibraries", "users", "phrases", "guilds", "music", "derogatoryTerms") tables.forEach { table -> if (!r.db("ardent_v2").tableList().run<List<String>>(conn).contains(table)) r.db("ardent_v2").tableCreate(table).run<Any>(conn) } } fun addCommands() { factory.addCommands(Ping(), Help(), Invite(), About(), Donate(), UserInfo(), ServerInfo(), RoleInfo(), UrbanDictionary(), UnixFortune(), EightBall(), FML(), Translate(), IsStreaming(), Status(), Clear(), Automessages(), AdministratorCommand(), GiveRoleToAll(), WebsiteCommand(), GetId(), Support(), /* IamCommand(), IamnotCommand(), */ LanguageCommand(), Blacklist(), Meme(), IamnotCommand(), IamCommand()) // Game Helper Commands // factory.addCommands(Decline(), InviteToGame(), Gamelist(), LeaveGame(), JoinGame(), Cancel(), Forcestart(), AcceptInvitation()) // Statistics Commands /*factory.addCommands(CommandDistribution(), ServerLanguagesDistribution(), MusicInfo(), AudioAnalysisCommand(), GetGuilds(), ShardInfo(), CalculateCommand(), MutualGuilds())*/ // Settings Commands factory.addCommands(Prefix(), Settings()) // Music Commands factory.addCommands(Playlist(), MyMusicLibrary(), Play(), Skip(), Pause(), Resume(), SongUrl(), Playing(), Queue()) factory.addCommands(ClearQueue(), RemoveFrom(), Volume(), GoTo(), Repeat()) /* factory.addCommands(Play(), Radio(), Stop(), Pause(), Resume(), SongUrl(), Volume(), Playing(), Repeat(), Shuffle(), Queue(), RemoveFrom(), Skip(), Prefix(), Leave(), ClearQueue(), RemoveAt(), ArtistSearch(), FastForward(), Rewind()) */ // Game Commands // factory.addCommands(BlackjackCommand(), Connect4Command(), BetCommand(), TriviaCommand(), TicTacToeCommand()) // RPG Commands factory.addCommands(TopMoney(), ProfileCommand(), Daily(), Balance()) } fun checkQueueBackups() { val queues = r.table("savedQueues").run<Any>(conn).queryAsArrayList(ServerQueue::class.java) queues.forEach { queue -> if (queue == null || queue.tracks.isEmpty()) return val channel = getVoiceChannelById(queue.voiceId) ?: return val textChannel = getTextChannelById(queue.channelId) ?: return if (channel.members.size > 1 || (channel.members.size == 1 && channel.members[0] == channel.guild.selfMember)) { val manager = channel.guild.getAudioManager(textChannel) if (manager.channel != null) { if (channel.guild.selfMember.voiceState?.channel != channel) channel.connect(textChannel) textChannel.send(("**Restarting playback...**... Check out {0} for other cool features we offer in Ardent **Premium**").tr(channel.guild, "<$hostname/premium>")) queue.tracks.forEach { trackUrl -> trackUrl.load(channel.guild.selfMember, textChannel, { audioTrack, id -> play(manager.channel, channel.guild.selfMember, LocalTrackObj(channel.guild.selfMember.user.id, channel.guild.selfMember.user.id, null, null, null, id, audioTrack)) }) } logChannel?.send("Resumed playback in `${channel.guild.name}` - channel `${channel.name}`") } } } r.table("savedQueues").delete().runNoReply(conn) } fun setupDrive(): Sheets { val builder = Sheets.Builder(transport, jsonFactory, null) builder.applicationName = "Ardent" return builder.build() } fun setupYoutube(): YouTube { return YouTube.Builder(transport, jsonFactory, null).setApplicationName("Ardent").build() }
apache-2.0
5eb088f100de41a54d83d4fa028d9dbe
40.583026
242
0.731919
4.108276
false
true
false
false
matejdro/WearMusicCenter
wear/src/main/java/com/matejdro/wearmusiccenter/watch/view/MainActivity.kt
1
25363
package com.matejdro.wearmusiccenter.watch.view import android.annotation.TargetApi import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.content.SharedPreferences import android.graphics.Bitmap import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Build import android.os.Bundle import android.os.Handler import android.os.IBinder import android.os.Looper import android.os.Message import android.os.Vibrator import android.view.KeyEvent import android.view.MotionEvent import android.view.View import android.view.ViewConfiguration import androidx.activity.viewModels import androidx.appcompat.content.res.AppCompatResources import androidx.lifecycle.Lifecycle import androidx.lifecycle.Observer import androidx.lifecycle.coroutineScope import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import androidx.preference.PreferenceManager import androidx.wear.ambient.AmbientModeSupport import androidx.wear.widget.drawer.WearableDrawerLayout import androidx.wear.widget.drawer.WearableDrawerView import com.google.android.gms.common.GoogleApiAvailability import com.google.android.gms.common.GooglePlayServicesRepairableException import com.google.android.wearable.input.RotaryEncoderHelper import com.matejdro.wearmusiccenter.R import com.matejdro.wearmusiccenter.common.CommPaths import com.matejdro.wearmusiccenter.common.MiscPreferences import com.matejdro.wearmusiccenter.common.ScreenQuadrant import com.matejdro.wearmusiccenter.common.buttonconfig.ButtonInfo import com.matejdro.wearmusiccenter.common.buttonconfig.GESTURE_DOUBLE_TAP import com.matejdro.wearmusiccenter.common.buttonconfig.GESTURE_LONG_TAP import com.matejdro.wearmusiccenter.common.buttonconfig.GESTURE_SINGLE_TAP import com.matejdro.wearmusiccenter.common.buttonconfig.SpecialButtonCodes import com.matejdro.wearmusiccenter.common.view.FourWayTouchLayout import com.matejdro.wearmusiccenter.databinding.ActivityMainBinding import com.matejdro.wearmusiccenter.proto.MusicState import com.matejdro.wearmusiccenter.watch.communication.CustomListWithBitmaps import com.matejdro.wearmusiccenter.watch.communication.WatchInfoSender import com.matejdro.wearmusiccenter.watch.communication.WatchMusicService import com.matejdro.wearmusiccenter.watch.config.WatchActionConfigProvider import com.matejdro.wearmusiccenter.watch.model.Notification import com.matejdro.wearutils.companionnotice.WearCompanionWatchActivity import com.matejdro.wearutils.lifecycle.Resource import com.matejdro.wearutils.miscutils.VibratorCompat import com.matejdro.wearutils.preferences.definition.Preferences import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import timber.log.Timber import java.lang.ref.WeakReference import kotlin.random.Random @AndroidEntryPoint class MainActivity : WearCompanionWatchActivity(), FourWayTouchLayout.UserActionListener, AmbientModeSupport.AmbientCallbackProvider { companion object { private const val MESSAGE_HIDE_VOLUME = 10 private const val MESSAGE_UPDATE_CLOCK = 11 private const val MESSAGE_DISMISS_NOTIFICATION = 12 private const val VOLUME_BAR_TIMEOUT = 1000L } private lateinit var timeFormat: java.text.DateFormat private lateinit var binding: ActivityMainBinding private lateinit var drawerContentContainer: View private lateinit var actionsMenuFragment: ActionsMenuFragment private lateinit var vibrator: Vibrator private lateinit var ambientController: AmbientModeSupport.AmbientController private lateinit var stemButtonsManager: StemButtonsManager private val handler = TimeoutsHandler(WeakReference(this)) private lateinit var preferences: SharedPreferences private val viewModel: MusicViewModel by viewModels() private var rotatingInputDisabledUntil = 0L private val serviceConnection = MusicServiceConnection(lifecycle) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) drawerContentContainer = findViewById(R.id.drawer_content) // Hide peek container - we only want full blown drawer without peeks val peekContainer: android.view.ViewGroup = binding.drawerLayout.findViewById( R.id.ws_drawer_view_peek_container ) peekContainer.visibility = View.GONE while (peekContainer.childCount > 0) { peekContainer.removeViewAt(0) } val params = peekContainer.layoutParams params.width = 0 params.height = 0 peekContainer.layoutParams = params binding.fourWayTouch.listener = this binding.drawerLayout.setDrawerStateCallback(drawerStateCallback) binding.notificationPopup.clickableFrame.setOnClickListener { onNotificationTapped() } timeFormat = android.text.format.DateFormat.getTimeFormat(this) preferences = PreferenceManager.getDefaultSharedPreferences(this) ambientController = AmbientModeSupport.attach(this) vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator viewModel.albumArt.observe(this, albumArtObserver) viewModel.currentButtonConfig.observe(this, buttonConfigObserver) viewModel.preferences.observe(this, preferencesChangeObserver) viewModel.volume.observe(this, phoneVolumeListener) viewModel.popupVolumeBar.observe(this, volumeBarPopupListener) viewModel.closeActionsMenu.observe(this, closeDrawerListener) viewModel.openActionsMenu.observe(this, openActionsMenuListener) viewModel.closeApp.observe(this, closeAppListener) viewModel.notification.observe(this, notificationObserver) viewModel.customList.observe(this, customListListener) stemButtonsManager = StemButtonsManager(WatchInfoSender.getAvailableButtonsOnWatch(this), stemButtonListener, lifecycleScope) actionsMenuFragment = supportFragmentManager.findFragmentById(R.id.drawer_content) as ActionsMenuFragment } override fun onStart() { super.onStart() if (Preferences.getBoolean(preferences, MiscPreferences.ALWAYS_SHOW_TIME)) { handler.sendEmptyMessage(MESSAGE_UPDATE_CLOCK) } val crownDisableTime = Preferences.getInt(preferences, MiscPreferences.ROTATING_CROWN_OFF_PERIOD) if (crownDisableTime > 0) { rotatingInputDisabledUntil = System.currentTimeMillis() + crownDisableTime } viewModel.updateTimers() bindService(Intent(this, WatchMusicService::class.java), serviceConnection, BIND_AUTO_CREATE) } override fun onStop() { if (isFinishing) { viewModel.sendManualCloseMessage() } super.onStop() handler.removeMessages(MESSAGE_UPDATE_CLOCK) unbindService(serviceConnection) } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) // onStop will trigger when screen turns off (But app stays in foreground) // and thus disable data transmission // Keep one observer alive as long as app has focus. if (hasFocus) { viewModel.musicState.observeForever(musicStateObserver) } else { viewModel.musicState.removeObserver(musicStateObserver) } } override fun onDestroy() { super.onDestroy() viewModel.musicState.removeObserver(musicStateObserver) } private fun updateClock() { binding.ambientClock.text = timeFormat.format(java.util.Date()) } private val musicStateObserver = Observer<Resource<MusicState>> { Timber.d("GUI Music State %s %s", it?.status, it?.data) if (it == null || it.status == Resource.Status.LOADING) { binding.loadingIndicator.visibility = View.VISIBLE return@Observer } binding.loadingIndicator.visibility = View.GONE if (it.status == Resource.Status.SUCCESS && it.data != null) { if ((it.data as MusicState).playing) { binding.textArtist.text = it.data?.artist } else { binding.textArtist.text = getString(R.string.playback_stopped) } binding.textTitle.text = it.data?.title } else if (it.status == Resource.Status.ERROR) { binding.textArtist.text = getString(R.string.error) binding.textTitle.text = it.message val errorData = it.errorData if (errorData is GooglePlayServicesRepairableException) { GoogleApiAvailability.getInstance().getErrorDialog(this, errorData.connectionStatusCode, 1)?.show() } } else { binding.textArtist.text = "" binding.textTitle.text = getString(R.string.playback_stopped) } binding.textArtist.visibility = if (binding.textArtist.text.isEmpty()) View.GONE else View.VISIBLE } private val albumArtObserver = Observer<Bitmap?> { binding.albumArt.setImageBitmap(it) } private val buttonConfigObserver = Observer<WatchActionConfigProvider> { config -> if (config == null) { return@Observer } val topSingle = config.getAction(ButtonInfo(false, ScreenQuadrant.TOP, GESTURE_SINGLE_TAP)) val bottomSingle = config.getAction(ButtonInfo(false, ScreenQuadrant.BOTTOM, GESTURE_SINGLE_TAP)) val leftSingle = config.getAction(ButtonInfo(false, ScreenQuadrant.LEFT, GESTURE_SINGLE_TAP)) val rightSingle = config.getAction(ButtonInfo(false, ScreenQuadrant.RIGHT, GESTURE_SINGLE_TAP)) binding.iconTop.setImageDrawable(topSingle?.icon) binding.iconBottom.setImageDrawable(bottomSingle?.icon) binding.iconLeft.setImageDrawable(leftSingle?.icon) binding.iconRight.setImageDrawable(rightSingle?.icon) for (i in 0 until 4) { binding.fourWayTouch.enabledDoubleTaps[i] = config.isActionActive(ButtonInfo(false, i, GESTURE_DOUBLE_TAP)) binding.fourWayTouch.enabledLongTaps[i] = config.isActionActive(ButtonInfo(false, i, GESTURE_LONG_TAP)) } with(stemButtonsManager) { for (button in WatchInfoSender.getAvailableButtonsOnWatch(this@MainActivity)) { enabledDoublePressActions[button] = config.isActionActive(ButtonInfo(true, button, GESTURE_DOUBLE_TAP)) enabledLongPressActions[button] = config.isActionActive(ButtonInfo(true, button, GESTURE_LONG_TAP)) } } } private val preferencesChangeObserver = Observer<SharedPreferences> { if (it == null) { return@Observer } preferences = it stemButtonsManager.enableDoublePressInAmbient = !Preferences.getBoolean( preferences, MiscPreferences.DISABLE_PHYSICAL_DOUBLE_CLICK_IN_AMBIENT ) if (!ambientController.isAmbient) { val alwaysDisplayClock = Preferences.getBoolean(preferences, MiscPreferences.ALWAYS_SHOW_TIME) if (alwaysDisplayClock) { binding.ambientClock.visibility = View.VISIBLE binding.iconTop.visibility = View.GONE handler.sendEmptyMessage(MESSAGE_UPDATE_CLOCK) } else { binding.iconTop.visibility = View.VISIBLE binding.ambientClock.visibility = View.GONE } } } private val notificationObserver = Observer<Notification> { if (it == null) { return@Observer } val notificationPopup = binding.notificationPopup notificationPopup.title.text = it.title notificationPopup.body.text = it.description notificationPopup.backgroundImage.setImageBitmap(it.background) showNotification() } private val phoneVolumeListener = Observer<Float> { binding.volumeBar.volume = it!! } private val volumeBarPopupListener = Observer<Unit> { showVolumeBar() } private val closeDrawerListener = Observer<Unit> { closeMenuDrawer() } fun closeMenuDrawer() { binding.actionDrawer.controller.closeDrawer() } private val openActionsMenuListener = Observer<Unit> { actionsMenuFragment.refreshMenu(ActionsMenuFragment.MenuType.Actions) openMenuDrawer() } private val closeAppListener = Observer<Unit> { finish() } private val customListListener = Observer<CustomListWithBitmaps> { val lastListDisplayed = Preferences.getString( preferences, MiscPreferences.LAST_MENU_DISPLAYED ).toLong() if (!binding.actionDrawer.isClosed || lastListDisplayed != it.listTimestamp) { actionsMenuFragment.refreshMenu(ActionsMenuFragment.MenuType.Custom(it)) openMenuDrawer() val editor = preferences.edit() Preferences.putString( editor, MiscPreferences.LAST_MENU_DISPLAYED, it.listTimestamp.toString() ) editor.apply() } } private val stemButtonListener = { buttonKeyCode: Int, gesture: Int -> if (gesture == GESTURE_DOUBLE_TAP) { handler.postDelayed(this::buzz, ViewConfiguration.getDoubleTapTimeout().toLong()) } else if (buttonKeyCode != SpecialButtonCodes.TURN_ROTARY_CW && buttonKeyCode != SpecialButtonCodes.TURN_ROTARY_CCW) { buzz() } viewModel.executeAction(ButtonInfo(true, buttonKeyCode, gesture)) } private fun openMenuDrawer() { binding.actionDrawer.controller.openDrawer() } private val drawerStateCallback = object : WearableDrawerLayout.DrawerStateCallback() { override fun onDrawerClosed(layout: WearableDrawerLayout, drawerView: WearableDrawerView) { binding.fourWayTouch.requestFocus() actionsMenuFragment.scrollToTop() } override fun onDrawerOpened(layout: WearableDrawerLayout, drawerView: WearableDrawerView) { drawerContentContainer.requestFocus() } override fun onDrawerStateChanged(layout: WearableDrawerLayout, newState: Int) { if (newState == WearableDrawerView.STATE_DRAGGING && binding.actionDrawer.isClosed) { openDefaultListInDrawer() } } } private fun openDefaultListInDrawer() { val type = if (Preferences.getBoolean( preferences, MiscPreferences.OPEN_PLAYBACK_QUEUE_ON_SWIPE_UP ) ) { viewModel.openPlaybackQueue() ActionsMenuFragment.MenuType.Custom( CustomListWithBitmaps(-1, "", emptyList()) ) } else { ActionsMenuFragment.MenuType.Actions } actionsMenuFragment.refreshMenu(type) } override fun getAmbientCallback(): AmbientModeSupport.AmbientCallback = object : AmbientModeSupport.AmbientCallback() { override fun onEnterAmbient(ambientDetails: Bundle?) { stemButtonsManager.onEnterAmbient() binding.ambientClock.visibility = View.VISIBLE handler.removeMessages(MESSAGE_UPDATE_CLOCK) updateClock() binding.iconTop.visibility = View.GONE binding.iconBottom.visibility = View.GONE binding.iconLeft.visibility = View.GONE binding.iconRight.visibility = View.GONE binding.albumArt.visibility = View.GONE binding.volumeBar.visibility = View.GONE binding.loadingIndicator.visibility = View.GONE binding.root.background = ColorDrawable(Color.BLACK) binding.notificationPopup.backgroundImage.visibility = View.GONE binding.notificationPopup.solidBackground.background = ColorDrawable(Color.BLACK) binding.textArtist.displayTextOutline = true binding.textTitle.displayTextOutline = true binding.actionDrawer.controller.closeDrawer() } override fun onUpdateAmbient() { updateClock() viewModel.updateTimers() binding.drawerLayout.translationX = Random.nextInt(-5, 6).toFloat() binding.drawerLayout.translationY = Random.nextInt(-5, 6).toFloat() } override fun onExitAmbient() { stemButtonsManager.onExitAmbient() if (Preferences.getBoolean(preferences, MiscPreferences.ALWAYS_SHOW_TIME)) { handler.sendEmptyMessage(MESSAGE_UPDATE_CLOCK) } else { binding.ambientClock.visibility = View.GONE binding.iconTop.visibility = View.VISIBLE } binding.iconBottom.visibility = View.VISIBLE binding.iconLeft.visibility = View.VISIBLE binding.iconRight.visibility = View.VISIBLE binding.albumArt.visibility = View.VISIBLE binding.root.background = null binding.notificationPopup.backgroundImage.visibility = View.VISIBLE binding.notificationPopup.solidBackground.background = AppCompatResources.getDrawable( this@MainActivity, R.drawable.notification_popup_background ) if (viewModel.musicState.value == null || (viewModel.musicState.value as Resource<MusicState>).status == Resource.Status.LOADING) { binding.loadingIndicator.visibility = View.VISIBLE } val crownDisableTime = Preferences.getInt(preferences, MiscPreferences.ROTATING_CROWN_OFF_PERIOD) if (crownDisableTime > 0) { rotatingInputDisabledUntil = System.currentTimeMillis() + crownDisableTime } binding.textArtist.displayTextOutline = false binding.textTitle.displayTextOutline = false binding.root.translationX = 0f binding.root.translationY = 0f } } override fun dispatchGenericMotionEvent(ev: MotionEvent): Boolean { if (binding.actionDrawer.isOpened && actionsMenuFragment.onGenericMotionEvent(ev)) { return true } return super.dispatchGenericMotionEvent(ev) } override fun onGenericMotionEvent(ev: android.view.MotionEvent): Boolean { if (binding.actionDrawer.isOpened) { return false } if (rotatingInputDisabledUntil > System.currentTimeMillis()) { return false } if (ev.action == android.view.MotionEvent.ACTION_SCROLL && RotaryEncoderHelper.isFromRotaryEncoder( ev ) ) { val delta = -RotaryEncoderHelper.getRotaryAxisValue(ev) * RotaryEncoderHelper.getScaledScrollFactor( this ) if (WatchInfoSender.hasDiscreteRotaryInput()) { val keyCode = if (delta > 0) { SpecialButtonCodes.TURN_ROTARY_CW } else { SpecialButtonCodes.TURN_ROTARY_CCW } return stemButtonsManager.simulateKeyPress(keyCode) } val multipler = Preferences.getInt(preferences, MiscPreferences.ROTATING_CROWN_SENSITIVITY) / 100f showVolumeBar() binding.volumeBar.incrementVolume(delta * 0.0025f * multipler) viewModel.updateVolume(binding.volumeBar.volume) return true } return super.onGenericMotionEvent(ev) } @TargetApi(Build.VERSION_CODES.N) override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { return super.onKeyDown(keyCode, event) } if (binding.actionDrawer.isOpened) { return actionsMenuFragment.onKeyDown(keyCode, event) } if (stemButtonsManager.onKeyDown(keyCode, event)) { return true } return super.onKeyDown(keyCode, event) } override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { if (stemButtonsManager.onKeyUp(keyCode)) { return true } return super.onKeyUp(keyCode, event) } private fun onNotificationTapped() { hideNotification() } private fun hideNotification() { val card = binding.notificationPopup.notificationCard card.animate().scaleX(0f).scaleY(0f).setDuration(200).withEndAction { card.visibility = View.GONE }.start() handler.removeMessages(MESSAGE_DISMISS_NOTIFICATION) } private fun showNotification() { val card = binding.notificationPopup.notificationCard card.animate().scaleX(1f).scaleY(1f).setDuration(200).withStartAction { card.visibility = View.VISIBLE }.start() val timeout = Preferences.getInt(preferences, MiscPreferences.NOTIFICATION_TIMEOUT) handler.removeMessages(MESSAGE_DISMISS_NOTIFICATION) if (timeout > 0) { handler.sendEmptyMessageDelayed(MESSAGE_DISMISS_NOTIFICATION, (timeout * 1000).toLong()) } } private fun showVolumeBar() { binding.volumeBar.visibility = View.VISIBLE handler.removeMessages(MESSAGE_HIDE_VOLUME) handler.sendEmptyMessageDelayed(MESSAGE_HIDE_VOLUME, VOLUME_BAR_TIMEOUT) } fun buzz() { if (!Preferences.getBoolean(preferences, MiscPreferences.HAPTIC_FEEDBACK)) { return } VibratorCompat.vibrate(vibrator, 50) } override fun onUpwardsSwipe() { Timber.d("UpwardsSwipe") binding.actionDrawer.controller.openDrawer() openDefaultListInDrawer() } override fun onSingleTap(quadrant: Int) { buzz() viewModel.executeAction(ButtonInfo(false, quadrant, GESTURE_SINGLE_TAP)) } override fun onDoubleTap(quadrant: Int) { // Single tap vibration has delay, because it needs to wait to see if user presses // for the second time. // Introduce similar delay to double tap vibration to make it more apparent to the user // that he double pressed handler.postDelayed(this::buzz, ViewConfiguration.getDoubleTapTimeout().toLong()) viewModel.executeAction(ButtonInfo(false, quadrant, GESTURE_DOUBLE_TAP)) } override fun onLongTap(quadrant: Int) { buzz() viewModel.executeAction(ButtonInfo(false, quadrant, GESTURE_LONG_TAP)) } private class TimeoutsHandler(val activity: WeakReference<MainActivity>) : Handler(Looper.getMainLooper()) { override fun handleMessage(msg: Message) { when (msg.what) { MESSAGE_HIDE_VOLUME -> { activity.get()?.binding?.volumeBar?.visibility = View.GONE } MESSAGE_UPDATE_CLOCK -> { removeMessages(MESSAGE_UPDATE_CLOCK) val activity = activity.get() ?: return activity.updateClock() if (!activity.ambientController.isAmbient && Preferences.getBoolean( activity.preferences, MiscPreferences.ALWAYS_SHOW_TIME ) ) { sendEmptyMessageDelayed(MESSAGE_UPDATE_CLOCK, 60_000) } } MESSAGE_DISMISS_NOTIFICATION -> { activity.get()?.hideNotification() } else -> super.handleMessage(msg) } } } override fun getPhoneAppPresenceCapability(): String = CommPaths.PHONE_APP_CAPABILITY private class MusicServiceConnection(private val lifecycle: Lifecycle) : ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder) { service as WatchMusicService.Binder lifecycle.coroutineScope.launch { service.uiOpenFlow.flowWithLifecycle(lifecycle).collect() } } override fun onServiceDisconnected(name: ComponentName?) { } } }
gpl-3.0
9cfd637b714d88b22095fbbe1a9a51fd
36.298529
151
0.652604
5.199467
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/readinglist/SortReadingListsDialog.kt
1
3277
package org.wikipedia.readinglist import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import org.wikipedia.R import org.wikipedia.activity.FragmentUtil.getCallback import org.wikipedia.databinding.DialogSortReadingListsBinding import org.wikipedia.databinding.ViewReadingListsSortOptionsItemBinding import org.wikipedia.page.ExtendedBottomSheetDialogFragment class SortReadingListsDialog : ExtendedBottomSheetDialogFragment() { fun interface Callback { fun onSortOptionClick(position: Int) } private var _binding: DialogSortReadingListsBinding? = null private val binding get() = _binding!! private lateinit var adapter: ReadingListSortAdapter private lateinit var sortOptions: List<String> private var chosenSortOption = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) chosenSortOption = requireArguments().getInt(SORT_OPTION) sortOptions = resources.getStringArray(R.array.sort_options).asList() adapter = ReadingListSortAdapter() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = DialogSortReadingListsBinding.inflate(inflater, container, false) binding.sortOptionsList.adapter = adapter binding.sortOptionsList.layoutManager = LinearLayoutManager(activity) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } private inner class ReadingListSortAdapter : RecyclerView.Adapter<SortItemHolder>() { override fun getItemCount(): Int { return sortOptions.size } override fun onCreateViewHolder(parent: ViewGroup, pos: Int): SortItemHolder { return SortItemHolder(ViewReadingListsSortOptionsItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)) } override fun onBindViewHolder(holder: SortItemHolder, pos: Int) { holder.bindItem(pos) holder.itemView.setOnClickListener { callback()?.onSortOptionClick(pos) dismiss() } } } private inner class SortItemHolder constructor(val binding: ViewReadingListsSortOptionsItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bindItem(sortOption: Int) { binding.sortType.text = sortOptions[sortOption] if (chosenSortOption == sortOption) { binding.check.visibility = View.VISIBLE } else { binding.check.visibility = View.GONE } } } private fun callback(): Callback? { return getCallback(this, Callback::class.java) } companion object { private const val SORT_OPTION = "sortOption" fun newInstance(sortOption: Int): SortReadingListsDialog { return SortReadingListsDialog().apply { arguments = bundleOf(SORT_OPTION to sortOption) } } } }
apache-2.0
1d0c8472ad30e004b4d16b742eb36ce2
35.411111
145
0.694843
5.152516
false
false
false
false
exponent/exponent
android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/screens/ScreenViewManager.kt
2
6212
package versioned.host.exp.exponent.modules.api.screens import com.facebook.react.bridge.JSApplicationIllegalArgumentException import com.facebook.react.common.MapBuilder import com.facebook.react.module.annotations.ReactModule import com.facebook.react.uimanager.ThemedReactContext import com.facebook.react.uimanager.ViewGroupManager import com.facebook.react.uimanager.annotations.ReactProp import versioned.host.exp.exponent.modules.api.screens.events.HeaderBackButtonClickedEvent import versioned.host.exp.exponent.modules.api.screens.events.ScreenAppearEvent import versioned.host.exp.exponent.modules.api.screens.events.ScreenDisappearEvent import versioned.host.exp.exponent.modules.api.screens.events.ScreenDismissedEvent import versioned.host.exp.exponent.modules.api.screens.events.ScreenTransitionProgressEvent import versioned.host.exp.exponent.modules.api.screens.events.ScreenWillAppearEvent import versioned.host.exp.exponent.modules.api.screens.events.ScreenWillDisappearEvent import versioned.host.exp.exponent.modules.api.screens.events.StackFinishTransitioningEvent @ReactModule(name = ScreenViewManager.REACT_CLASS) class ScreenViewManager : ViewGroupManager<Screen>() { override fun getName(): String { return REACT_CLASS } override fun createViewInstance(reactContext: ThemedReactContext): Screen { return Screen(reactContext) } @ReactProp(name = "activityState") fun setActivityState(view: Screen, activityState: Int?) { if (activityState == null) { // Null will be provided when activityState is set as an animated value and we change // it from JS to be a plain value (non animated). // In case when null is received, we want to ignore such value and not make // any updates as the actual non-null value will follow immediately. return } when (activityState) { 0 -> view.setActivityState(Screen.ActivityState.INACTIVE) 1 -> view.setActivityState(Screen.ActivityState.TRANSITIONING_OR_BELOW_TOP) 2 -> view.setActivityState(Screen.ActivityState.ON_TOP) } } @ReactProp(name = "stackPresentation") fun setStackPresentation(view: Screen, presentation: String) { view.stackPresentation = when (presentation) { "push" -> Screen.StackPresentation.PUSH "modal", "containedModal", "fullScreenModal", "formSheet" -> Screen.StackPresentation.MODAL "transparentModal", "containedTransparentModal" -> Screen.StackPresentation.TRANSPARENT_MODAL else -> throw JSApplicationIllegalArgumentException("Unknown presentation type $presentation") } } @ReactProp(name = "stackAnimation") fun setStackAnimation(view: Screen, animation: String?) { view.stackAnimation = when (animation) { null, "default", "flip", "simple_push" -> Screen.StackAnimation.DEFAULT "none" -> Screen.StackAnimation.NONE "fade" -> Screen.StackAnimation.FADE "slide_from_right" -> Screen.StackAnimation.SLIDE_FROM_RIGHT "slide_from_left" -> Screen.StackAnimation.SLIDE_FROM_LEFT "slide_from_bottom" -> Screen.StackAnimation.SLIDE_FROM_BOTTOM "fade_from_bottom" -> Screen.StackAnimation.FADE_FROM_BOTTOM else -> throw JSApplicationIllegalArgumentException("Unknown animation type $animation") } } @ReactProp(name = "gestureEnabled", defaultBoolean = true) fun setGestureEnabled(view: Screen, gestureEnabled: Boolean) { view.isGestureEnabled = gestureEnabled } @ReactProp(name = "replaceAnimation") fun setReplaceAnimation(view: Screen, animation: String?) { view.replaceAnimation = when (animation) { null, "pop" -> Screen.ReplaceAnimation.POP "push" -> Screen.ReplaceAnimation.PUSH else -> throw JSApplicationIllegalArgumentException("Unknown replace animation type $animation") } } @ReactProp(name = "screenOrientation") fun setScreenOrientation(view: Screen, screenOrientation: String?) { view.setScreenOrientation(screenOrientation) } @ReactProp(name = "statusBarAnimation") fun setStatusBarAnimation(view: Screen, statusBarAnimation: String?) { val animated = statusBarAnimation != null && "none" != statusBarAnimation view.isStatusBarAnimated = animated } @ReactProp(name = "statusBarColor") fun setStatusBarColor(view: Screen, statusBarColor: Int?) { view.statusBarColor = statusBarColor } @ReactProp(name = "statusBarStyle") fun setStatusBarStyle(view: Screen, statusBarStyle: String?) { view.statusBarStyle = statusBarStyle } @ReactProp(name = "statusBarTranslucent") fun setStatusBarTranslucent(view: Screen, statusBarTranslucent: Boolean?) { view.isStatusBarTranslucent = statusBarTranslucent } @ReactProp(name = "statusBarHidden") fun setStatusBarHidden(view: Screen, statusBarHidden: Boolean?) { view.isStatusBarHidden = statusBarHidden } @ReactProp(name = "nativeBackButtonDismissalEnabled") fun setNativeBackButtonDismissalEnabled( view: Screen, nativeBackButtonDismissalEnabled: Boolean ) { view.nativeBackButtonDismissalEnabled = nativeBackButtonDismissalEnabled } override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Any> { val map: MutableMap<String, Any> = MapBuilder.of( ScreenDismissedEvent.EVENT_NAME, MapBuilder.of("registrationName", "onDismissed"), ScreenWillAppearEvent.EVENT_NAME, MapBuilder.of("registrationName", "onWillAppear"), ScreenAppearEvent.EVENT_NAME, MapBuilder.of("registrationName", "onAppear"), ScreenWillDisappearEvent.EVENT_NAME, MapBuilder.of("registrationName", "onWillDisappear"), ScreenDisappearEvent.EVENT_NAME, MapBuilder.of("registrationName", "onDisappear"), StackFinishTransitioningEvent.EVENT_NAME, MapBuilder.of("registrationName", "onFinishTransitioning"), ScreenTransitionProgressEvent.EVENT_NAME, MapBuilder.of("registrationName", "onTransitionProgress") ) // there is no `MapBuilder.of` with more than 7 items map[HeaderBackButtonClickedEvent.EVENT_NAME] = MapBuilder.of("registrationName", "onHeaderBackButtonClicked") return map } companion object { const val REACT_CLASS = "RNSScreen" } }
bsd-3-clause
286938677ebe1d7b480176d0e0cb2fb4
40.972973
113
0.753863
4.567647
false
false
false
false