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
bozaro/git-as-svn
src/main/kotlin/svnserver/ext/gitlfs/server/LfsServer.kt
1
3012
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.ext.gitlfs.server import ru.bozaro.gitlfs.server.ContentManager import ru.bozaro.gitlfs.server.ContentServlet import ru.bozaro.gitlfs.server.LocksServlet import ru.bozaro.gitlfs.server.PointerServlet import svnserver.context.Local import svnserver.context.LocalContext import svnserver.context.Shared import svnserver.ext.gitlfs.LocalLfsConfig import svnserver.ext.gitlfs.storage.LfsStorage import svnserver.ext.web.server.WebServer import kotlin.math.max import kotlin.math.min /** * LFS server. * * @author Artem V. Navrotskiy <[email protected]> */ class LfsServer(private val secretToken: String, tokenExpireSec: Long, tokenEnsureTime: Float) : Shared { private val tokenExpireSec: Long = if (tokenExpireSec > 0) tokenExpireSec else LocalLfsConfig.DEFAULT_TOKEN_EXPIRE_SEC private val tokenEnsureTime: Float = max(0.0f, min(tokenEnsureTime, 1.0f)) fun register(localContext: LocalContext, storage: LfsStorage) { val webServer = localContext.shared.sure(WebServer::class.java) val name = localContext.name val pathSpec = String.format("/%s.git/", name).replace("/+".toRegex(), "/") val pointerManager: ContentManager = LfsContentManager(localContext, storage, tokenExpireSec, tokenEnsureTime) val contentManager = LfsContentManager(localContext, storage, tokenExpireSec, 0.0f) val servletsInfo = webServer.addServlets( mapOf( pathSpec + SERVLET_AUTH to LfsAuthServlet(localContext, pathSpec + SERVLET_BASE, secretToken, tokenExpireSec, tokenEnsureTime), "$pathSpec$SERVLET_POINTER/*" to PointerServlet(pointerManager, pathSpec + SERVLET_CONTENT), "$pathSpec$SERVLET_CONTENT/*" to ContentServlet(contentManager), pathSpec + SERVLET_BASE + "locks/*" to LocksServlet(LfsLockManager(contentManager)), ) ) localContext.add(LfsServerHolder::class.java, LfsServerHolder(webServer, servletsInfo)) } fun unregister(localContext: LocalContext) { val holder = localContext.remove(LfsServerHolder::class.java) holder?.close() } private class LfsServerHolder(private val webServer: WebServer, private val servlets: Collection<WebServer.Holder>) : Local { override fun close() { webServer.removeServlets(servlets) } } companion object { const val SERVLET_BASE = "info/lfs/" const val SERVLET_AUTH = "lfs_authenticate" private const val SERVLET_CONTENT = SERVLET_BASE + "storage" private const val SERVLET_POINTER = SERVLET_BASE + "objects" } }
gpl-2.0
29d056c35c47e284b2c0f22d9d0747a6
45.338462
143
0.720784
3.978864
false
false
false
false
apixandru/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/DefaultWebServerRootsProvider.kt
12
11314
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.builtInWebServer import com.intellij.openapi.application.runReadAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.rootManager import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.DirectoryIndex import com.intellij.openapi.roots.impl.ModuleLibraryOrderEntryImpl import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PlatformUtils import com.intellij.util.containers.computeIfAny internal data class SuitableRoot(val file: VirtualFile, val moduleQualifier: String?) private class DefaultWebServerRootsProvider : WebServerRootsProvider() { override fun resolve(path: String, project: Project, pathQuery: PathQuery): PathInfo? { val pathToFileManager = WebServerPathToFileManager.getInstance(project) var effectivePath = path if (PlatformUtils.isIntelliJ()) { val index = effectivePath.indexOf('/') if (index > 0 && !effectivePath.regionMatches(0, project.name, 0, index, !SystemInfo.isFileSystemCaseSensitive)) { val moduleName = effectivePath.substring(0, index) val module = runReadAction { ModuleManager.getInstance(project).findModuleByName(moduleName) } if (module != null && !module.isDisposed) { effectivePath = effectivePath.substring(index + 1) val resolver = pathToFileManager.getResolver(effectivePath) val result = RootProvider.values().computeIfAny { findByRelativePath(effectivePath, it.getRoots(module.rootManager), resolver, moduleName, pathQuery) } ?: findInModuleLibraries(effectivePath, module, resolver, pathQuery) if (result != null) { return result } } } } val resolver = pathToFileManager.getResolver(effectivePath) val modules = runReadAction { ModuleManager.getInstance(project).modules } if (pathQuery.useVfs) { var oldestParent = path.indexOf("/").let { if (it > 0) path.substring(0, it) else null } if (oldestParent == null && !path.isEmpty() && !path.contains('.')) { // maybe it is top level directory? (in case of dart projects - web) oldestParent = path } if (oldestParent != null) { for ((file, moduleQualifier) in pathToFileManager.parentToSuitableRoot.get(oldestParent)) { file.findFileByRelativePath(path)?.let { return PathInfo(null, it, file, moduleQualifier) } } } } else { for (rootProvider in RootProvider.values()) { for (module in modules) { if (module.isDisposed) { continue } findByRelativePath(path, rootProvider.getRoots(module.rootManager), resolver, null, pathQuery)?.let { it.moduleName = getModuleNameQualifier(project, module) return it } } } } if (!pathQuery.searchInLibs) { // yes, if !searchInLibs, config.json is also not checked return null } fun findByConfigJson(): PathInfo? { // https://youtrack.jetbrains.com/issue/WEB-24283 for (rootProvider in RootProvider.values()) { for (module in modules) { if (module.isDisposed) { continue } for (root in rootProvider.getRoots(module.rootManager)) { if (resolver.resolve("config.json", root, pathQuery = pathQuery) != null) { resolver.resolve("index.html", root, pathQuery = pathQuery)?.let { it.moduleName = getModuleNameQualifier(project, module) return it } } } } } return null } val exists = pathToFileManager.pathToExistShortTermCache.getIfPresent("config.json") if (exists == null || exists) { val result = findByConfigJson() pathToFileManager.pathToExistShortTermCache.put("config.json", result != null) if (result != null) { return result } } return findInLibraries(project, effectivePath, resolver, pathQuery) } override fun getPathInfo(file: VirtualFile, project: Project): PathInfo? { return runReadAction { val directoryIndex = DirectoryIndex.getInstance(project) val info = directoryIndex.getInfoForFile(file) // we serve excluded files if (!info.isExcluded(file) && !info.isInProject(file)) { // javadoc jars is "not under project", but actually is, so, let's check library or SDK if (file.fileSystem == JarFileSystem.getInstance()) getInfoForDocJar(file, project) else null } else { var root = info.sourceRoot val isRootNameOptionalInPath: Boolean val isLibrary: Boolean if (root == null) { isRootNameOptionalInPath = false root = info.contentRoot if (root == null) { root = info.libraryClassRoot if (root == null) { // https://youtrack.jetbrains.com/issue/WEB-20598 return@runReadAction null } isLibrary = true } else { isLibrary = false } } else { isLibrary = info.isInLibrarySource(file) isRootNameOptionalInPath = !isLibrary } var module = info.module if (isLibrary && module == null) { for (entry in directoryIndex.getOrderEntries(info)) { if (entry is ModuleLibraryOrderEntryImpl) { module = entry.ownerModule break } } } PathInfo(null, file, root, getModuleNameQualifier(project, module), isLibrary, isRootNameOptionalInPath = isRootNameOptionalInPath) } } } } internal enum class RootProvider { SOURCE { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.sourceRoots }, CONTENT { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.contentRoots }, EXCLUDED { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.excludeRoots }; abstract fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> } private val ORDER_ROOT_TYPES by lazy { val javaDocRootType = getJavadocOrderRootType() if (javaDocRootType == null) arrayOf(OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES) else arrayOf(javaDocRootType, OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES) } private fun getJavadocOrderRootType(): OrderRootType? { return try { JavadocOrderRootType.getInstance() } catch (e: Throwable) { null } } private fun findInModuleLibraries(path: String, module: Module, resolver: FileResolver, pathQuery: PathQuery): PathInfo? { val index = path.indexOf('/') if (index <= 0) { return null } val libraryFileName = path.substring(0, index) val relativePath = path.substring(index + 1) return ORDER_ROOT_TYPES.computeIfAny { findInModuleLevelLibraries(module, it) { root, _ -> if (StringUtil.equalsIgnoreCase(root.nameSequence, libraryFileName)) resolver.resolve(relativePath, root, isLibrary = true, pathQuery = pathQuery) else null } } } private fun findInLibraries(project: Project, path: String, resolver: FileResolver, pathQuery: PathQuery): PathInfo? { val index = path.indexOf('/') if (index < 0) { return null } val libraryFileName = path.substring(0, index) val relativePath = path.substring(index + 1) return findInLibrariesAndSdk(project, ORDER_ROOT_TYPES) { root, _ -> if (StringUtil.equalsIgnoreCase(root.nameSequence, libraryFileName)) resolver.resolve(relativePath, root, isLibrary = true, pathQuery = pathQuery) else null } } private fun getInfoForDocJar(file: VirtualFile, project: Project): PathInfo? { val javaDocRootType = getJavadocOrderRootType() ?: return null return findInLibrariesAndSdk(project, arrayOf(javaDocRootType)) { root, module -> if (VfsUtilCore.isAncestor(root, file, false)) PathInfo(null, file, root, getModuleNameQualifier(project, module), true) else null } } internal fun getModuleNameQualifier(project: Project, module: Module?): String? { if (module != null && PlatformUtils.isIntelliJ() && !(module.name.equals(project.name, ignoreCase = true) || compareNameAndProjectBasePath(module.name, project))) { return module.name } return null } private fun findByRelativePath(path: String, roots: Array<VirtualFile>, resolver: FileResolver, moduleName: String?, pathQuery: PathQuery) = roots.computeIfAny { resolver.resolve(path, it, moduleName, pathQuery = pathQuery) } private fun findInLibrariesAndSdk(project: Project, rootTypes: Array<OrderRootType>, fileProcessor: (root: VirtualFile, module: Module?) -> PathInfo?): PathInfo? { fun findInLibraryTable(table: LibraryTable, rootType: OrderRootType) = table.libraryIterator.computeIfAny { it.getFiles(rootType).computeIfAny { fileProcessor(it, null) } } fun findInProjectSdkOrInAll(rootType: OrderRootType): PathInfo? { val inSdkFinder = { sdk: Sdk -> sdk.rootProvider.getFiles(rootType).computeIfAny { fileProcessor(it, null) } } val projectSdk = ProjectRootManager.getInstance(project).projectSdk return projectSdk?.let(inSdkFinder) ?: ProjectJdkTable.getInstance().allJdks.computeIfAny { if (it === projectSdk) null else inSdkFinder(it) } } return rootTypes.computeIfAny { rootType -> runReadAction { findInLibraryTable(LibraryTablesRegistrar.getInstance().getLibraryTable(project), rootType) ?: findInProjectSdkOrInAll(rootType) ?: ModuleManager.getInstance(project).modules.computeIfAny { if (it.isDisposed) null else findInModuleLevelLibraries(it, rootType, fileProcessor) } ?: findInLibraryTable(LibraryTablesRegistrar.getInstance().libraryTable, rootType) } } } private fun findInModuleLevelLibraries(module: Module, rootType: OrderRootType, fileProcessor: (root: VirtualFile, module: Module?) -> PathInfo?): PathInfo? { return module.rootManager.orderEntries.computeIfAny { if (it is LibraryOrderEntry && it.isModuleLevel) it.getFiles(rootType).computeIfAny { fileProcessor(it, module) } else null } }
apache-2.0
04fb996491904f72ba3d8428466b76b4
39.266904
225
0.698427
4.75578
false
false
false
false
dna2github/NodeBase
android/app/src/main/kotlin/net/seven/nodebase/Download.kt
1
4492
package net.seven.nodebase // TODO: deprecated, solution ref: // https://stackoverflow.com/questions/45373007/progressdialog-is-deprecated-what-is-the-alternate-one-to-use import android.app.ProgressDialog import android.content.Context import android.os.AsyncTask import android.os.Handler import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.net.HttpURLConnection import java.net.MalformedURLException import java.net.URL class Download(private val context: Context, private val callback: Runnable?) { private val progress: ProgressDialog class DownloadTask(private val downloader: Download) : AsyncTask<String, String, String>() { override fun doInBackground(vararg strings: String): String? { val url = strings[0] val outfile = strings[1] var download_stream: InputStream? = null var output_stream: OutputStream? = null var conn: HttpURLConnection? = null publishProgress("Starting ...") try { val urlobj = URL(url) conn = urlobj.openConnection() as HttpURLConnection if (conn.responseCode / 100 != 2) { throw IOException("server error: " + conn.responseCode) } val file_len = conn.contentLength val buf = ByteArray(1024 * 1024) var read_len = 0 var total_read_len = 0 download_stream = conn.inputStream Storage.unlink(outfile) Storage.touch(outfile) output_stream = FileOutputStream(outfile) read_len = download_stream!!.read(buf) while (read_len >= 0) { if (isCancelled) { throw IOException("user cancelled") } total_read_len += read_len output_stream.write(buf, 0, read_len) var read_size = Storage.readableSize(total_read_len) if (file_len > 0) { read_size += " / " + Storage.readableSize(file_len) } publishProgress(read_size) read_len = download_stream.read(buf) } output_stream.close() download_stream.close() publishProgress("Finishing ...") } catch (e: MalformedURLException) { e.printStackTrace() return e.toString() } catch (e: IOException) { e.printStackTrace() return e.toString() } finally { if (download_stream != null) try { download_stream.close() } catch (e: IOException) { } if (output_stream != null) try { output_stream.close() } catch (e: IOException) { } if (conn != null) conn.disconnect() } return null } override fun onPreExecute() { super.onPreExecute() downloader.progress.max = 100 downloader.progress.progress = 0 downloader.progress.show() } override fun onProgressUpdate(vararg data: String) { downloader.progress.setMessage(data[0]) } override fun onPostExecute(result: String?) { super.onPostExecute(result); downloader.progress.setMessage("do post actions ...") if (downloader.callback != null) { Handler(downloader.context.getMainLooper()).post(downloader.callback) } downloader.progress.dismiss() if (result == null) { Alarm.showToast(downloader.context, "Download successful") } else { Alarm.showToast(downloader.context, "Download failed: $result") } } } init { progress = ProgressDialog(context) progress.isIndeterminate = true progress.setProgressStyle(ProgressDialog.STYLE_SPINNER) progress.setCancelable(true) } fun act(title: String, url: String, outfile: String) { val task = DownloadTask(this) progress.setTitle(title) progress.setOnCancelListener { task.cancel(true) } task.execute(url, outfile) } }
apache-2.0
f232b1ccf636df8733e305767dbc974c
35.819672
109
0.549866
5.030235
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/refresh/LegacyAutoRefreshController.kt
1
4727
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.util.refresh import android.annotation.TargetApi import android.app.AlarmManager import android.app.PendingIntent import android.app.job.JobScheduler import android.content.Context import android.content.Intent import android.os.Build import android.os.SystemClock import android.support.v4.util.ArrayMap import org.mariotaku.kpreferences.KPreferences import de.vanita5.twittnuker.annotation.AutoRefreshType import de.vanita5.twittnuker.constant.refreshIntervalKey import de.vanita5.twittnuker.service.JobTaskService.Companion.JOB_IDS_REFRESH import de.vanita5.twittnuker.service.LegacyTaskService import de.vanita5.twittnuker.util.TaskServiceRunner.Companion.ACTION_REFRESH_FILTERS_SUBSCRIPTIONS import de.vanita5.twittnuker.util.TaskServiceRunner.Companion.ACTION_REFRESH_LAUNCH_PRESENTATIONS import java.util.concurrent.TimeUnit class LegacyAutoRefreshController( context: Context, kPreferences: KPreferences ) : AutoRefreshController(context, kPreferences) { private val alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager private val pendingIntents: ArrayMap<String, PendingIntent> = ArrayMap() init { AutoRefreshType.ALL.forEach { type -> val action = LegacyTaskService.getRefreshAction(type) ?: return@forEach val intent = Intent(context, LegacyTaskService::class.java) intent.action = action pendingIntents[type] = PendingIntent.getService(context, 0, intent, 0) } } override fun appStarted() { rescheduleAll() rescheduleFiltersSubscriptionsRefresh() rescheduleLaunchPresentationsRefresh() } override fun rescheduleAll() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { removeAllJobs(context, JOB_IDS_REFRESH) } super.rescheduleAll() } override fun unschedule(type: String) { val pendingIntent = pendingIntents[type] ?: return alarmManager.cancel(pendingIntent) } override fun schedule(type: String) { val pendingIntent = pendingIntents[type] ?: return val interval = TimeUnit.MINUTES.toMillis(kPreferences[refreshIntervalKey]) if (interval > 0) { val triggerAt = SystemClock.elapsedRealtime() + interval alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAt, interval, pendingIntent) } } private fun rescheduleFiltersSubscriptionsRefresh() { val interval = TimeUnit.HOURS.toMillis(4) val triggerAt = SystemClock.elapsedRealtime() + interval val intent = Intent(context, LegacyTaskService::class.java) intent.action = ACTION_REFRESH_FILTERS_SUBSCRIPTIONS alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAt, interval, PendingIntent.getService(context, 0, intent, 0)) } private fun rescheduleLaunchPresentationsRefresh() { val interval = TimeUnit.HOURS.toMillis(6) val triggerAt = SystemClock.elapsedRealtime() + interval val intent = Intent(context, LegacyTaskService::class.java) intent.action = ACTION_REFRESH_LAUNCH_PRESENTATIONS alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAt, interval, PendingIntent.getService(context, 0, intent, 0)) } companion object { @TargetApi(Build.VERSION_CODES.LOLLIPOP) fun removeAllJobs(context: Context, jobIds: IntArray) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return val jobService = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler jobIds.forEach { id -> jobService.cancel(id) } } } }
gpl-3.0
1ef4cce97443cf996c8f1e432a3c569e
39.758621
118
0.724138
4.493346
false
false
false
false
SapuSeven/BetterUntis
weekview/src/main/java/com/sapuseven/untis/views/weekview/drawers/NowLineDrawer.kt
1
1696
package com.sapuseven.untis.views.weekview.drawers import android.graphics.Canvas import com.sapuseven.untis.views.weekview.DateUtils.isSameDay import com.sapuseven.untis.views.weekview.DrawingContext import com.sapuseven.untis.views.weekview.config.WeekViewConfig import com.sapuseven.untis.views.weekview.config.WeekViewDrawConfig import org.joda.time.DateTime import kotlin.math.max class NowLineDrawer(private val config: WeekViewConfig) : BaseDrawer { private val drawConfig: WeekViewDrawConfig = config.drawConfig override fun draw(drawingContext: DrawingContext, canvas: Canvas) { if (!config.showNowLine) return var startPixel = drawingContext.startPixel for (day in drawingContext.dayRange) { val isSameDay = isSameDay(day, DateTime.now()) val startX = max(startPixel, drawConfig.timeColumnWidth) if (config.isSingleDay) { // Add a margin at the start if we're in day view. Otherwise, screen space is too // precious and we refrain from doing so. startPixel += config.eventMarginHorizontal } // Draw the line at the current time. if (isSameDay) drawLine(startX, startPixel, canvas) // In the next iteration, start from the next day. startPixel += config.totalDayWidth } } private fun drawLine(startX: Float, startPixel: Float, canvas: Canvas) { val startY = drawConfig.headerHeight + drawConfig.currentOrigin.y val now = DateTime.now() // Draw line val minutesUntilNow = now.hourOfDay * 60 + now.minuteOfHour - config.startTime val lineStartY = startY + minutesUntilNow / 60.0f * config.hourHeight canvas.drawLine(startX, lineStartY, startPixel + drawConfig.widthPerDay, lineStartY, drawConfig.nowLinePaint) } }
gpl-3.0
5406a3621bb5efe95ccd686b931563e8
35.085106
111
0.767689
3.623932
false
true
false
false
stripe/stripe-android
stripe-core/src/main/java/com/stripe/android/core/networking/QueryStringFactory.kt
1
4963
package com.stripe.android.core.networking import androidx.annotation.RestrictTo import com.stripe.android.core.exception.InvalidRequestException import java.io.UnsupportedEncodingException import java.net.URLEncoder import java.util.HashMap import java.util.HashSet /** * Factory for HTTP request query strings, converts a [Map] of <param, value> into a query string * like "?p1=v1&p2=v2" */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) object QueryStringFactory { /** * Create a query string from a [Map] */ fun create(params: Map<String, *>?): String { return flattenParams(params).joinToString("&") { it.toString() } } /** * Create a query string from a [Map] with possible empty values, remove the empty values first */ fun createFromParamsWithEmptyValues(params: Map<String, *>?): String { return params?.let(QueryStringFactory::compactParams)?.let(QueryStringFactory::create) ?: "" } /** * Copy the {@param params} map and recursively remove null and empty values. The Stripe API * requires that parameters with null values are removed from requests. * * @param params a [Map] from which to remove the keys that have `null` values */ fun compactParams(params: Map<String, *>): Map<String, Any> { val compactParams = HashMap<String, Any>(params) // Remove all null values; they cause validation errors for (key in HashSet(compactParams.keys)) { when (val value = compactParams[key]) { is Map<*, *> -> { compactParams[key] = compactParams(value as Map<String, *>) } null -> { compactParams.remove(key) } } } return compactParams } @Throws(InvalidRequestException::class) private fun flattenParams(params: Map<String, *>?): List<Parameter> { return flattenParamsMap(params) } /** * Determine if a value is a primitive. Primitives in lists can be serialized without indexes. */ private fun isPrimitive(value: Any?) = value is String || value is Number || value is Boolean || value is Char /** * Determine if all elements in a list are primitives. */ private fun isPrimitiveList(l: List<*>) = l.all { isPrimitive(it) } @Throws(InvalidRequestException::class) private fun flattenParamsList( params: List<*>, keyPrefix: String ): List<Parameter> { // Because application/x-www-form-urlencoded cannot represent an empty // list, convention is to take the list parameter and just set it to an // empty string. (e.g. A regular list might look like `a[]=1&b[]=2`. // Emptying it would look like `a=`.) return if (params.isEmpty()) { listOf(Parameter(keyPrefix, "")) } else if (isPrimitiveList(params)) { // Lists of primitives can be serialized as `listName[]=` val newPrefix = "$keyPrefix[]" params.flatMap { flattenParamsValue(it, newPrefix) } } else { // Lists of objects must include the index like `listName[0]=` params.flatMapIndexed { index, value -> flattenParamsValue(value, "$keyPrefix[$index]") } } } @Throws(InvalidRequestException::class) private fun flattenParamsMap( params: Map<String, *>?, keyPrefix: String? = null ): List<Parameter> { return params?.flatMap { (key, value) -> val newPrefix = keyPrefix?.let { "$it[$key]" } ?: key flattenParamsValue(value, newPrefix) } ?: emptyList() } @Throws(InvalidRequestException::class) private fun flattenParamsValue( value: Any?, keyPrefix: String ): List<Parameter> { return when (value) { is Map<*, *> -> flattenParamsMap(value as Map<String, Any>?, keyPrefix) is List<*> -> flattenParamsList(value, keyPrefix) null -> { listOf(Parameter(keyPrefix, "")) } else -> { listOf(Parameter(keyPrefix, value.toString())) } } } private data class Parameter internal constructor( private val key: String, private val value: String ) { override fun toString(): String { val encodedKey = urlEncode(key) val encodedValue = urlEncode(value) return "$encodedKey=$encodedValue" } @Throws(UnsupportedEncodingException::class) private fun urlEncode(str: String): String { // Preserve original behavior that passing null for an object id will lead // to us actually making a request to /v1/foo/null return URLEncoder.encode(str, Charsets.UTF_8.name()) } } }
mit
722cbdb953d8338ec7f261f079dd086c
33.465278
100
0.595607
4.59537
false
false
false
false
exponent/exponent
packages/expo-dev-launcher/android/src/react-native-66/expo/modules/devlauncher/rncompatibility/DevLauncherDevSupportManager.kt
2
10584
package expo.modules.devlauncher.rncompatibility import android.content.Context import android.util.Log import android.widget.Toast import com.facebook.common.logging.FLog import com.facebook.debug.holder.PrinterHolder import com.facebook.debug.tags.ReactDebugOverlayTags import com.facebook.infer.annotation.Assertions import com.facebook.react.R import com.facebook.react.bridge.JSBundleLoader import com.facebook.react.bridge.JavaJSExecutor import com.facebook.react.bridge.ReactMarker import com.facebook.react.bridge.ReactMarkerConstants import com.facebook.react.bridge.UiThreadUtil import com.facebook.react.common.ReactConstants import com.facebook.react.common.futures.SimpleSettableFuture import com.facebook.react.devsupport.DevSupportManagerBase import com.facebook.react.devsupport.HMRClient import com.facebook.react.devsupport.ReactInstanceDevHelper import com.facebook.react.devsupport.RedBoxHandler import com.facebook.react.devsupport.WebsocketJavaScriptExecutor import com.facebook.react.devsupport.WebsocketJavaScriptExecutor.JSExecutorConnectCallback import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener import com.facebook.react.devsupport.interfaces.DevSplitBundleCallback import com.facebook.react.packagerconnection.RequestHandler import expo.modules.devlauncher.DevLauncherController import expo.modules.devlauncher.koin.DevLauncherKoinComponent import expo.modules.devlauncher.launcher.DevLauncherControllerInterface import expo.modules.devlauncher.launcher.errors.DevLauncherAppError import expo.modules.devlauncher.launcher.errors.DevLauncherErrorActivity import org.koin.core.component.inject import java.io.File import java.io.IOException import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException class DevLauncherDevSupportManager( applicationContext: Context?, val reactInstanceManagerHelper: ReactInstanceDevHelper?, packagerPathForJSBundleName: String?, enableOnCreate: Boolean, redBoxHandler: RedBoxHandler?, devBundleDownloadListener: DevBundleDownloadListener?, minNumShakes: Int, customPackagerCommandHandlers: MutableMap<String, RequestHandler>? ) : DevSupportManagerBase( applicationContext, reactInstanceManagerHelper, packagerPathForJSBundleName, enableOnCreate, redBoxHandler, devBundleDownloadListener, minNumShakes, customPackagerCommandHandlers ), DevLauncherKoinComponent { private val controller: DevLauncherControllerInterface by inject() // copied from https://github.com/facebook/react-native/blob/aa4da248c12e3ba41ecc9f1c547b21c208d9a15f/ReactAndroid/src/main/java/com/facebook/react/devsupport/BridgeDevSupportManager.java#L65 private var mIsSamplingProfilerEnabled = false // copied from https://github.com/facebook/react-native/blob/aa4da248c12e3ba41ecc9f1c547b21c208d9a15f/ReactAndroid/src/main/java/com/facebook/react/devsupport/BridgeDevSupportManager.java#L88-L128 init { if (devSettings.isStartSamplingProfilerOnInit) { // Only start the profiler. If its already running, there is an error if (!mIsSamplingProfilerEnabled) { toggleJSSamplingProfiler() } else { Toast.makeText( applicationContext, "JS Sampling Profiler was already running, so did not start the sampling profiler", Toast.LENGTH_LONG) .show() } } addCustomDevOption( if (mIsSamplingProfilerEnabled) applicationContext!!.getString( R.string.catalyst_sample_profiler_disable) else applicationContext!!.getString( R.string.catalyst_sample_profiler_enable) ) { toggleJSSamplingProfiler() } if (!devSettings.isDeviceDebugEnabled) { // For remote debugging, we open up Chrome running the app in a web worker. // Note that this requires async communication, which will not work for Turbo Modules. addCustomDevOption( if (devSettings.isRemoteJSDebugEnabled) applicationContext.getString(R.string.catalyst_debug_stop) else applicationContext.getString(R.string.catalyst_debug) ) { devSettings.isRemoteJSDebugEnabled = !devSettings.isRemoteJSDebugEnabled handleReloadJS() } } } override fun showNewJavaError(message: String?, e: Throwable) { if (!DevLauncherController.wasInitialized()) { Log.e("DevLauncher", "DevLauncher wasn't initialized. Couldn't intercept native error handling.") super.showNewJavaError(message, e) return } val activity = reactInstanceManagerHelper?.currentActivity if (activity == null || activity.isFinishing || activity.isDestroyed) { return } controller.onAppLoadedWithError() DevLauncherErrorActivity.showError(activity, DevLauncherAppError(message, e)) } // copied from https://github.com/facebook/react-native/blob/aa4da248c12e3ba41ecc9f1c547b21c208d9a15f/ReactAndroid/src/main/java/com/facebook/react/devsupport/BridgeDevSupportManager.java#L131-L134 override fun getUniqueTag() = "DevLauncherApp - Bridge" // copied from https://github.com/facebook/react-native/blob/aa4da248c12e3ba41ecc9f1c547b21c208d9a15f/ReactAndroid/src/main/java/com/facebook/react/devsupport/BridgeDevSupportManager.java#L136-L156 override fun loadSplitBundleFromServer( bundlePath: String?, callback: DevSplitBundleCallback) { fetchSplitBundleAndCreateBundleLoader( bundlePath, object : CallbackWithBundleLoader { override fun onSuccess(bundleLoader: JSBundleLoader) { bundleLoader.loadScript(currentContext!!.catalystInstance) currentContext!! .getJSModule(HMRClient::class.java) .registerBundle(devServerHelper.getDevServerSplitBundleURL(bundlePath)) callback.onSuccess() } override fun onError(url: String, cause: Throwable) { callback.onError(url, cause) } }) } // copied from https://github.com/facebook/react-native/blob/aa4da248c12e3ba41ecc9f1c547b21c208d9a15f/ReactAndroid/src/main/java/com/facebook/react/devsupport/BridgeDevSupportManager.java#L158-L165 private fun getExecutorConnectCallback( future: SimpleSettableFuture<Boolean>): JSExecutorConnectCallback { return object : JSExecutorConnectCallback { override fun onSuccess() { future.set(true) hideDevLoadingView() } override fun onFailure(cause: Throwable) { hideDevLoadingView() FLog.e(ReactConstants.TAG, "Failed to connect to debugger!", cause) future.setException( IOException( applicationContext.getString(R.string.catalyst_debug_error), cause)) } } } // copied from https://github.com/facebook/react-native/blob/aa4da248c12e3ba41ecc9f1c547b21c208d9a15f/ReactAndroid/src/main/java/com/facebook/react/devsupport/BridgeDevSupportManager.java#L179-L204 private fun reloadJSInProxyMode() { // When using js proxy, there is no need to fetch JS bundle as proxy executor will do that // anyway devServerHelper.launchJSDevtools() val factory = JavaJSExecutor.Factory { val executor = WebsocketJavaScriptExecutor() val future = SimpleSettableFuture<Boolean>() executor.connect( devServerHelper.websocketProxyURL, getExecutorConnectCallback(future)) // TODO(t9349129) Don't use timeout try { future[90, TimeUnit.SECONDS] return@Factory executor } catch (e: ExecutionException) { throw (e.cause as Exception) } catch (e: InterruptedException) { throw RuntimeException(e) } catch (e: TimeoutException) { throw RuntimeException(e) } } reactInstanceDevHelper.onReloadWithJSDebugger(factory) } // copied from https://github.com/facebook/react-native/blob/aa4da248c12e3ba41ecc9f1c547b21c208d9a15f/ReactAndroid/src/main/java/com/facebook/react/devsupport/BridgeDevSupportManager.java#L206-L231 override fun handleReloadJS() { UiThreadUtil.assertOnUiThread() ReactMarker.logMarker( ReactMarkerConstants.RELOAD, devSettings.packagerConnectionSettings.debugServerHost) // dismiss redbox if exists hideRedboxDialog() if (devSettings.isRemoteJSDebugEnabled) { PrinterHolder.getPrinter() .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from Proxy") showDevLoadingViewForRemoteJSEnabled() reloadJSInProxyMode() } else { PrinterHolder.getPrinter() .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from Server") val bundleURL = devServerHelper .getDevServerBundleURL(Assertions.assertNotNull(jsAppBundleName)) reloadJSFromServer(bundleURL) } } // copied from https://github.com/facebook/react-native/blob/aa4da248c12e3ba41ecc9f1c547b21c208d9a15f/ReactAndroid/src/main/java/com/facebook/react/devsupport/BridgeDevSupportManager.java#L233-L277 /** Starts of stops the sampling profiler */ private fun toggleJSSamplingProfiler() { val javaScriptExecutorFactory = reactInstanceDevHelper.javaScriptExecutorFactory if (!mIsSamplingProfilerEnabled) { try { javaScriptExecutorFactory.startSamplingProfiler() Toast.makeText(applicationContext, "Starting Sampling Profiler", Toast.LENGTH_SHORT) .show() } catch (e: UnsupportedOperationException) { Toast.makeText( applicationContext, "$javaScriptExecutorFactory does not support Sampling Profiler", Toast.LENGTH_LONG) .show() } finally { mIsSamplingProfilerEnabled = true } } else { try { val outputPath: String = File.createTempFile( "sampling-profiler-trace", ".cpuprofile", applicationContext.cacheDir) .path javaScriptExecutorFactory.stopSamplingProfiler(outputPath) Toast.makeText( applicationContext, "Saved results from Profiler to $outputPath", Toast.LENGTH_LONG) .show() } catch (e: IOException) { FLog.e( ReactConstants.TAG, "Could not create temporary file for saving results from Sampling Profiler") } catch (e: UnsupportedOperationException) { Toast.makeText( applicationContext, javaScriptExecutorFactory.toString() + "does not support Sampling Profiler", Toast.LENGTH_LONG) .show() } finally { mIsSamplingProfilerEnabled = false } } } companion object { fun getDevHelperInternalFieldName() = "mReactInstanceDevHelper" } }
bsd-3-clause
f18dd556bd52c76daf99874b966edf11
41.167331
199
0.750094
4.355556
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/filesystem/FilePermissionModule.kt
2
1721
package abi44_0_0.expo.modules.filesystem import android.content.Context import abi44_0_0.expo.modules.interfaces.filesystem.FilePermissionModuleInterface import abi44_0_0.expo.modules.core.interfaces.InternalModule import abi44_0_0.expo.modules.interfaces.filesystem.Permission import java.io.File import java.io.IOException import java.util.* // The class needs to be 'open', because it's inherited in expoview open class FilePermissionModule : FilePermissionModuleInterface, InternalModule { override fun getExportedInterfaces(): List<Class<*>> = listOf(FilePermissionModuleInterface::class.java) override fun getPathPermissions(context: Context, path: String): EnumSet<Permission> = getInternalPathPermissions(path, context) ?: getExternalPathPermissions(path) private fun getInternalPathPermissions(path: String, context: Context): EnumSet<Permission>? { return try { val canonicalPath = File(path).canonicalPath getInternalPaths(context) .firstOrNull { dir -> canonicalPath.startsWith("$dir/") || dir == canonicalPath } ?.let { EnumSet.of(Permission.READ, Permission.WRITE) } } catch (e: IOException) { EnumSet.noneOf(Permission::class.java) } } protected open fun getExternalPathPermissions(path: String): EnumSet<Permission> { val file = File(path) return EnumSet.noneOf(Permission::class.java).apply { if (file.canRead()) { add(Permission.READ) } if (file.canWrite()) { add(Permission.WRITE) } } } @Throws(IOException::class) private fun getInternalPaths(context: Context): List<String> = listOf( context.filesDir.canonicalPath, context.cacheDir.canonicalPath ) }
bsd-3-clause
7be771389b691ad08b5742c5b221c5ec
34.854167
96
0.728065
4.270471
false
false
false
false
pyamsoft/padlock
padlock-service/src/main/java/com/pyamsoft/padlock/service/ServiceManagerImpl.kt
1
6929
/* * Copyright 2019 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.pyamsoft.padlock.service import android.app.Activity import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.os.Build.VERSION import android.os.Build.VERSION_CODES import androidx.annotation.CheckResult import com.pyamsoft.padlock.api.preferences.MasterPinPreferences import com.pyamsoft.padlock.api.preferences.ServicePreferences import com.pyamsoft.padlock.api.service.ServiceManager import com.pyamsoft.padlock.model.service.ServicePauseState.PAUSED import com.pyamsoft.padlock.model.service.ServicePauseState.TEMP_PAUSED import com.pyamsoft.padlock.api.service.ServiceManager.Commands import com.pyamsoft.padlock.api.service.ServiceManager.Commands.PAUSE import com.pyamsoft.padlock.api.service.ServiceManager.Commands.START import com.pyamsoft.padlock.api.service.ServiceManager.Commands.TEMP_PAUSE import com.pyamsoft.padlock.api.service.ServiceManager.Commands.USER_PAUSE import com.pyamsoft.padlock.api.service.ServiceManager.Commands.USER_TEMP_PAUSE import com.pyamsoft.padlock.api.service.ServiceManager.Companion.FORCE_REFRESH_ON_OPEN import com.pyamsoft.padlock.service.device.UsagePermissionChecker import com.pyamsoft.pydroid.core.threads.Enforcer import io.reactivex.Completable import io.reactivex.CompletableObserver import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import timber.log.Timber import javax.inject.Inject internal class ServiceManagerImpl @Inject internal constructor( context: Context, private val enforcer: Enforcer, private val activityClass: Class<out Activity>, private val serviceClass: Class<out Service>, private val masterPinPreferences: MasterPinPreferences, private val servicePreferences: ServicePreferences ) : ServiceManager { private val appContext = context.applicationContext @CheckResult private fun hasUsageAccessPermission(): Boolean { return UsagePermissionChecker.hasPermission(appContext) } @CheckResult private fun hasMasterPassword(): Boolean { return masterPinPreferences.getMasterPassword() != null } @CheckResult private fun restartInPausedState(restart: Boolean): Boolean { val restarted = servicePreferences.getPaused() == PAUSED && !restart if (restarted) { // We don't use startForeground because starting in paused mode will not call foreground service // NOTE: Can crash if service is not already running from the Foreground. // most noticed in BootReceiver if restart is false appContext.startService(service(PAUSE)) } return restarted } @CheckResult private fun restartInTempPausedState(restart: Boolean): Boolean { val restarted = servicePreferences.getPaused() == TEMP_PAUSED && !restart if (restarted) { // We don't use startForeground because starting in paused mode will not call foreground service // NOTE: Can crash if service is not already running from the Foreground. // most noticed in BootReceiver if restart is false appContext.startService(service(TEMP_PAUSE)) } return restarted } private fun restartService(restart: Boolean) { if (restart) { Timber.d("Restarting service") } else { Timber.d("Starting service") } val intent = service(START) if (VERSION.SDK_INT >= VERSION_CODES.O) { appContext.startForegroundService(intent) } else { appContext.startService(intent) } } override fun startService(restart: Boolean) { Completable.fromAction { enforcer.assertNotOnMainThread() if (!hasUsageAccessPermission()) { Timber.w("Cannot start service, missing usage permission") return@fromAction } if (!hasMasterPassword()) { Timber.w("Cannot start service, missing master password") return@fromAction } when { restartInPausedState(restart) -> Timber.d("Starting service in PAUSED state") restartInTempPausedState(restart) -> Timber.d("Starting service in TEMP_PAUSED state") else -> restartService(restart) } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(object : CompletableObserver { override fun onComplete() { Timber.d("Service started") } override fun onSubscribe(d: Disposable) { Timber.d("Starting service...") } override fun onError(e: Throwable) { Timber.e(e, "Failed to start service") } }) } @CheckResult private fun mainActivity(forceRefreshOnOpen: Boolean): Intent { return Intent(appContext, activityClass).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK putExtra(FORCE_REFRESH_ON_OPEN, forceRefreshOnOpen) } } override fun fireMainActivityIntent(forceRefreshOnOpen: Boolean): PendingIntent { val intent = mainActivity(forceRefreshOnOpen) return PendingIntent.getActivity( appContext, REQUEST_CODE_MAIN_ACTIVITY, intent, PendingIntent.FLAG_ONE_SHOT ) } @CheckResult private fun service(command: Commands): Intent { return Intent(appContext, serviceClass).apply { putExtra(ServiceManager.SERVICE_COMMAND, command.name) } } override fun fireStartIntent(): PendingIntent { val intent = service(START) return PendingIntent.getService( appContext, REQUEST_CODE_SERVICE_START, intent, PendingIntent.FLAG_UPDATE_CURRENT ) } override fun fireUserPauseIntent(): PendingIntent { val intent = service(USER_PAUSE) return PendingIntent.getService( appContext, REQUEST_CODE_SERVICE_USER_PAUSE, intent, PendingIntent.FLAG_UPDATE_CURRENT ) } override fun fireTempPauseIntent(): PendingIntent { val intent = service(USER_TEMP_PAUSE) return PendingIntent.getService( appContext, REQUEST_CODE_SERVICE_USER_TEMP_PAUSE, intent, PendingIntent.FLAG_UPDATE_CURRENT ) } companion object { private const val REQUEST_CODE_MAIN_ACTIVITY = 1004 private const val REQUEST_CODE_SERVICE_START = 1005 private const val REQUEST_CODE_SERVICE_USER_PAUSE = 1006 private const val REQUEST_CODE_SERVICE_USER_TEMP_PAUSE = 1007 } }
apache-2.0
e7e12ebbf69b5d95d9902cc69d7e1559
33.645
102
0.737047
4.57058
false
false
false
false
noud02/Akatsuki
src/main/kotlin/moe/kyubey/akatsuki/commands/Clean.kt
1
2331
/* * Copyright (c) 2017-2019 Yui * * 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 moe.kyubey.akatsuki.commands import moe.kyubey.akatsuki.annotations.Alias import moe.kyubey.akatsuki.annotations.Argument import moe.kyubey.akatsuki.entities.AsyncCommand import moe.kyubey.akatsuki.entities.Context import moe.kyubey.akatsuki.annotations.Load import moe.kyubey.akatsuki.extensions.await import moe.kyubey.akatsuki.utils.I18n import kotlin.math.min @Load @Argument("messages", "number", true) @Alias("clear", "cls") class Clean : AsyncCommand() { override val desc = "Clean the last 10 messages sent by me" override val guildOnly = true override val cooldown = 15 override suspend fun asyncRun(ctx: Context) { val msgs = ctx.channel.getHistoryAround(ctx.msg, 100).await() val botmsgs = msgs.retrievedHistory.filter { it.author.id == ctx.selfMember!!.user.id } val sub = botmsgs.subList(0, min(botmsgs.size, min(ctx.args.getOrDefault("messages", 10) as Int, 10))) sub.forEach { it.delete().await() } ctx.send( I18n.parse( ctx.lang.getString("cleaned_messages"), mapOf("num" to sub.size) ) ) } }
mit
95ca9bbc8952aa2936efa393b108b3e5
37.866667
110
0.700129
4.089474
false
false
false
false
arcuri82/testing_security_development_enterprise_systems
advanced/exercise-solutions/card-game/part-10/user-collections/src/test/kotlin/org/tsdes/advanced/exercises/cardgame/usercollections/db/UserServiceTest.kt
3
4446
package org.tsdes.advanced.exercises.cardgame.usercollections.db import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory import org.springframework.context.annotation.Primary import org.springframework.context.annotation.Profile import org.springframework.stereotype.Service import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.web.client.RestTemplate import org.tsdes.advanced.exercises.cardgame.usercollections.CardService import org.tsdes.advanced.exercises.cardgame.usercollections.FakeData import org.tsdes.advanced.exercises.cardgame.usercollections.model.Collection @Profile("UserServiceTest") @Primary @Service class FakeCardService : CardService(RestTemplate(), Resilience4JCircuitBreakerFactory()){ override fun fetchData() { val dto = FakeData.getCollectionDto() super.collection = Collection(dto) } } @ActiveProfiles("UserServiceTest","test") @ExtendWith(SpringExtension::class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) internal class UserServiceTest{ @Autowired private lateinit var userService: UserService @Autowired private lateinit var userRepository: UserRepository @BeforeEach fun initTest(){ userRepository.deleteAll() } @Test fun testCreateUser(){ val id = "foo" assertTrue(userService.registerNewUser(id)) assertTrue(userRepository.existsById(id)) } @Test fun testFailCreateUserTwice(){ val id = "foo" assertTrue(userService.registerNewUser(id)) assertFalse(userService.registerNewUser(id)) } @Test fun testBuyCard(){ val userId = "foo" val cardId = "c00" userService.registerNewUser(userId) userService.buyCard(userId, cardId) val user = userService.findByIdEager(userId)!! assertTrue(user.ownedCards.any { it.cardId == cardId}) } @Test fun testBuyCardFailNotEnoughMoney(){ val userId = "foo" val cardId = "c09" userService.registerNewUser(userId) val e = assertThrows(IllegalArgumentException::class.java){ userService.buyCard(userId, cardId) } assertTrue(e.message!!.contains("coin"), "Wrong error message: ${e.message}") } @Test fun testOpenPack(){ val userId = "foo" userService.registerNewUser(userId) val before = userService.findByIdEager(userId)!! val totCards = before.ownedCards.sumBy { it.numberOfCopies } val totPacks = before.cardPacks assertTrue(totPacks > 0) val n = userService.openPack(userId).size assertEquals(UserService.CARDS_PER_PACK, n) val after = userService.findByIdEager(userId)!! assertEquals(totPacks - 1, after.cardPacks) assertEquals(totCards + UserService.CARDS_PER_PACK, after.ownedCards.sumBy { it.numberOfCopies } ) } @Test fun testOpenPackFail(){ val userId = "foo" userService.registerNewUser(userId) val before = userService.findByIdEager(userId)!! val totPacks = before.cardPacks repeat(totPacks){ userService.openPack(userId) } val after = userService.findByIdEager(userId)!! assertEquals(0, after.cardPacks) assertThrows(IllegalArgumentException::class.java){ userService.openPack(userId) } } @Test fun testMillCard(){ val userId = "foo" userService.registerNewUser(userId) val before = userRepository.findById(userId).get() val coins = before.coins userService.openPack(userId) val between = userService.findByIdEager(userId)!! val n = between.ownedCards.sumBy { it.numberOfCopies } userService.millCard(userId, between.ownedCards[0].cardId!!) val after = userService.findByIdEager(userId)!! assertTrue(after.coins > coins) assertEquals(n-1, after.ownedCards.sumBy { it.numberOfCopies }) } }
lgpl-3.0
5e8cdfbaf99042a488ec79ec1c1991b0
28.065359
94
0.69928
4.513706
false
true
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/challenges/ChallengeDetailFragment.kt
1
15226
package com.habitrpg.android.habitica.ui.fragments.social.challenges import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.core.net.toUri import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.ChallengeRepository import com.habitrpg.android.habitica.data.SocialRepository import com.habitrpg.android.habitica.databinding.DialogChallengeDetailTaskGroupBinding import com.habitrpg.android.habitica.databinding.FragmentChallengeDetailBinding import com.habitrpg.android.habitica.extensions.addCloseButton import com.habitrpg.android.habitica.extensions.inflate import com.habitrpg.android.habitica.helpers.MainNavigationController import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.members.Member import com.habitrpg.android.habitica.models.social.Challenge import com.habitrpg.android.habitica.models.tasks.Task import com.habitrpg.android.habitica.models.tasks.TaskType import com.habitrpg.android.habitica.ui.activities.ChallengeFormActivity import com.habitrpg.android.habitica.ui.activities.FullProfileActivity import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment import com.habitrpg.android.habitica.ui.helpers.EmojiParser import com.habitrpg.android.habitica.ui.helpers.setMarkdown import com.habitrpg.android.habitica.ui.viewHolders.tasks.DailyViewHolder import com.habitrpg.android.habitica.ui.viewHolders.tasks.HabitViewHolder import com.habitrpg.android.habitica.ui.viewHolders.tasks.RewardViewHolder import com.habitrpg.android.habitica.ui.viewHolders.tasks.TodoViewHolder import com.habitrpg.android.habitica.ui.viewmodels.MainUserViewModel import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog import retrofit2.HttpException import javax.inject.Inject class ChallengeDetailFragment : BaseMainFragment<FragmentChallengeDetailBinding>() { @Inject lateinit var challengeRepository: ChallengeRepository @Inject lateinit var socialRepository: SocialRepository @Inject lateinit var userViewModel: MainUserViewModel override var binding: FragmentChallengeDetailBinding? = null override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentChallengeDetailBinding { return FragmentChallengeDetailBinding.inflate(inflater, container, false) } var challengeID: String? = null var challenge: Challenge? = null private var isCreator = false override fun injectFragment(component: UserComponent) { component.inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { this.hidesToolbar = true return super.onCreateView(inflater, container, savedInstanceState) } @Suppress("ReturnCount") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { showsBackButton = true super.onViewCreated(view, savedInstanceState) arguments?.let { val args = ChallengeDetailFragmentArgs.fromBundle(it) challengeID = args.challengeID } binding?.gemAmountIcon?.setImageBitmap(HabiticaIconsHelper.imageOfGem_36()) binding?.participantCountIcon?.setImageBitmap(HabiticaIconsHelper.imageOfParticipantsIcon()) binding?.challengeDescription?.movementMethod = LinkMovementMethod.getInstance() binding?.challengeCreatorWrapper?.setOnClickListener { val leaderID = challenge?.leaderId ?: return@setOnClickListener FullProfileActivity.open(leaderID) } challengeID?.let { id -> compositeSubscription.add( challengeRepository.getChallenge(id) .doOnNext { set(it) } .map { return@map (it.leaderId ?: "") } .filter { it.isNotEmpty() } .flatMap { creatorID -> return@flatMap socialRepository.getMember(creatorID) } .subscribe({ set(it) }, RxErrorHandler.handleEmptyError()) ) compositeSubscription.add( challengeRepository.getChallengeTasks(id).subscribe( { taskList -> binding?.taskGroupLayout?.removeAllViewsInLayout() val todos = ArrayList<Task>() val habits = ArrayList<Task>() val dailies = ArrayList<Task>() val rewards = ArrayList<Task>() for (entry in taskList) { when (entry.type) { TaskType.TODO -> todos.add(entry) TaskType.HABIT -> habits.add(entry) TaskType.DAILY -> dailies.add(entry) TaskType.REWARD -> rewards.add(entry) } } if (habits.size > 0) { addHabits(habits) } if (dailies.size > 0) { addDailys(dailies) } if (todos.size > 0) { addTodos(todos) } if (rewards.size > 0) { addRewards(rewards) } }, RxErrorHandler.handleEmptyError() ) ) compositeSubscription.add( challengeRepository.isChallengeMember(id).subscribe( { isMember -> setJoined(isMember) }, RxErrorHandler.handleEmptyError() ) ) } binding?.joinButton?.setOnClickListener { challenge?.let { challenge -> challengeRepository.joinChallenge(challenge) .flatMap { userRepository.retrieveUser(true) } .subscribe({}, RxErrorHandler.handleEmptyError()) } } binding?.leaveButton?.setOnClickListener { showChallengeLeaveDialog() } refresh() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_challenge_details, menu) val editMenuItem = menu.findItem(R.id.action_edit) editMenuItem?.isVisible = isCreator val endChallengeMenuItem = menu.findItem(R.id.action_end_challenge) endChallengeMenuItem?.isVisible = isCreator } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_edit -> { val intent = Intent(getActivity(), ChallengeFormActivity::class.java) val bundle = Bundle() bundle.putString(ChallengeFormActivity.CHALLENGE_ID_KEY, challengeID) intent.putExtras(bundle) startActivity(intent) return true } R.id.action_share -> { val shareGuildIntent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT, "${context?.getString(R.string.base_url)}/challenges/$challengeID") type = "text/plain" } startActivity(Intent.createChooser(shareGuildIntent, context?.getString(R.string.share_challenge_with))) } R.id.action_end_challenge -> { showEndChallengeDialog() } } return super.onOptionsItemSelected(item) } private fun showEndChallengeDialog() { val context = context ?: return val dialog = HabiticaAlertDialog(context) dialog.setTitle(R.string.action_end_challenge) dialog.setMessage(R.string.end_challenge_description) dialog.addButton(R.string.open_website, true, false) { _, _ -> val uriUrl = "https://habitica.com/challenges/$challengeID".toUri() val launchBrowser = Intent(Intent.ACTION_VIEW, uriUrl) val l = context.packageManager.queryIntentActivities(launchBrowser, PackageManager.MATCH_DEFAULT_ONLY) val notHabitica = l.firstOrNull { !it.activityInfo.processName.contains("habitica") } if (notHabitica != null) { launchBrowser.setPackage(notHabitica.activityInfo.processName) } startActivity(launchBrowser) } dialog.addCloseButton() dialog.show() } private fun refresh() { challengeID?.let { id -> challengeRepository.retrieveChallenge(id) .flatMap { challengeRepository.retrieveChallengeTasks(id) } .subscribe({ }, { if (it is HttpException && it.code() == 404) { MainNavigationController.navigateBack() } RxErrorHandler.reportError(it) }) } } private fun set(challenge: Challenge) { this.challenge = challenge binding?.challengeName?.text = EmojiParser.parseEmojis(challenge.name) binding?.challengeDescription?.setMarkdown(challenge.description) binding?.creatorLabel?.username = challenge.leaderName binding?.gemAmount?.text = challenge.prize.toString() binding?.participantCount?.text = challenge.memberCount.toString() } private fun set(creator: Member) { binding?.creatorAvatarview?.setAvatar(creator) binding?.creatorLabel?.tier = creator.contributor?.level ?: 0 binding?.creatorLabel?.username = creator.displayName isCreator = creator.id == userViewModel.userID this.activity?.invalidateOptionsMenu() } private fun setJoined(joined: Boolean) { binding?.joinButton?.visibility = if (!joined) View.VISIBLE else View.GONE binding?.joinButtonWrapper?.visibility = if (!joined) View.VISIBLE else View.GONE binding?.leaveButton?.visibility = if (joined) View.VISIBLE else View.GONE binding?.leaveButtonWrapper?.visibility = if (joined) View.VISIBLE else View.GONE } private fun addHabits(habits: ArrayList<Task>) { val groupBinding = DialogChallengeDetailTaskGroupBinding.inflate(layoutInflater, binding?.taskGroupLayout, true) groupBinding.taskGroupName.text = getLabelByTypeAndCount(Challenge.TASK_ORDER_HABITS, habits.size) groupBinding.taskCountView.text = habits.size.toString() for (i in 0 until habits.size) { val task = habits[i] val entry = groupBinding.tasksLayout.inflate(R.layout.habit_item_card) val viewHolder = HabitViewHolder(entry, { _, _ -> }, {}, {}) viewHolder.isLocked = true viewHolder.bind(task, i, "normal") groupBinding.tasksLayout.addView(entry) } } private fun addDailys(dailies: ArrayList<Task>) { val groupBinding = DialogChallengeDetailTaskGroupBinding.inflate(layoutInflater, binding?.taskGroupLayout, true) groupBinding.taskGroupName.text = getLabelByTypeAndCount(Challenge.TASK_ORDER_DAILYS, dailies.size) groupBinding.taskCountView.text = dailies.size.toString() for (i in 0 until dailies.size) { val task = dailies[i] val entry = groupBinding.tasksLayout.inflate(R.layout.daily_item_card) val viewHolder = DailyViewHolder(entry, { _, _ -> }, { _, _ -> }, {}, {}) viewHolder.isLocked = true viewHolder.bind(task, i, "normal") groupBinding.tasksLayout.addView(entry) } } private fun addTodos(todos: ArrayList<Task>) { val groupBinding = DialogChallengeDetailTaskGroupBinding.inflate(layoutInflater, binding?.taskGroupLayout, true) groupBinding.taskGroupName.text = getLabelByTypeAndCount(Challenge.TASK_ORDER_TODOS, todos.size) groupBinding.taskCountView.text = todos.size.toString() for (i in 0 until todos.size) { val task = todos[i] val entry = groupBinding.tasksLayout.inflate(R.layout.todo_item_card) val viewHolder = TodoViewHolder(entry, { _, _ -> }, { _, _ -> }, {}, {}) viewHolder.isLocked = true viewHolder.bind(task, i, "normal") groupBinding.tasksLayout.addView(entry) } } private fun addRewards(rewards: ArrayList<Task>) { val groupBinding = DialogChallengeDetailTaskGroupBinding.inflate(layoutInflater, binding?.taskGroupLayout, true) groupBinding.taskGroupName.text = getLabelByTypeAndCount(Challenge.TASK_ORDER_REWARDS, rewards.size) groupBinding.taskCountView.text = rewards.size.toString() for (i in 0 until rewards.size) { val task = rewards[i] val entry = groupBinding.tasksLayout.inflate(R.layout.reward_item_card) val viewHolder = RewardViewHolder(entry, { _, _ -> }, {}, {}) viewHolder.isLocked = true viewHolder.bind(task, i, true, "normal") groupBinding.tasksLayout.addView(entry) } } private fun getLabelByTypeAndCount(type: String, count: Int): String { return when (type) { Challenge.TASK_ORDER_DAILYS -> context?.getString(if (count == 1) R.string.daily else R.string.dailies) Challenge.TASK_ORDER_HABITS -> context?.getString(if (count == 1) R.string.habit else R.string.habits) Challenge.TASK_ORDER_REWARDS -> context?.getString(if (count == 1) R.string.reward else R.string.rewards) else -> context?.getString(if (count == 1) R.string.todo else R.string.todos) } ?: "" } private fun showChallengeLeaveDialog() { val context = context ?: return val alert = HabiticaAlertDialog(context) alert.setTitle(this.getString(R.string.challenge_leave_title)) alert.setMessage(this.getString(R.string.challenge_leave_description)) alert.addButton(R.string.leave_keep_tasks, true) { _, _ -> val challenge = challenge ?: return@addButton challengeRepository.leaveChallenge(challenge, "keep-all").subscribe({}, RxErrorHandler.handleEmptyError()) } alert.addButton(R.string.leave_delete_tasks, isPrimary = false, isDestructive = true) { _, _ -> val challenge = challenge ?: return@addButton challengeRepository.leaveChallenge(challenge, "remove-all").subscribe({}, RxErrorHandler.handleEmptyError()) } alert.setExtraCloseButtonVisibility(View.VISIBLE) alert.show() } }
gpl-3.0
75a5be391dbbd0ec41cd30ee214fc1e5
43.651026
120
0.637594
4.969321
false
false
false
false
michael71/LanbahnPanel
app/src/main/java/de/blankedv/lanbahnpanel/view/LanbahnPanelActivity.kt
1
26727
package de.blankedv.lanbahnpanel.view import android.Manifest import android.app.AlertDialog import android.app.AlertDialog.Builder import android.content.* import android.content.pm.PackageManager import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.* import android.preference.PreferenceManager import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.util.DisplayMetrics import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.* import android.widget.LinearLayout.LayoutParams import de.blankedv.lanbahnpanel.* import java.util.Timer import java.util.TimerTask import de.blankedv.lanbahnpanel.model.LanbahnPanelApplication.Companion.clearPanelData import de.blankedv.lanbahnpanel.config.ReadConfig import de.blankedv.lanbahnpanel.config.Download import de.blankedv.lanbahnpanel.config.WriteConfig import de.blankedv.lanbahnpanel.elements.ActivePanelElement import de.blankedv.lanbahnpanel.elements.PanelElement import de.blankedv.lanbahnpanel.loco.Loco import de.blankedv.lanbahnpanel.model.* import de.blankedv.lanbahnpanel.railroad.Commands import de.blankedv.lanbahnpanel.railroad.Railroad import de.blankedv.lanbahnpanel.settings.SettingsActivity import de.blankedv.lanbahnpanel.util.LPaints import de.blankedv.lanbahnpanel.util.Utils.threadSleep import org.jetbrains.anko.* /** * LanbahnPanelActivity is the MAIN activity of the lanbahn panel * * @author mblank */ class LanbahnPanelActivity : AppCompatActivity() { internal lateinit var builder: Builder internal var mBound = false internal lateinit var tv: TextView internal lateinit var params: LayoutParams internal lateinit var but: Button private var mOptionsMenu: Menu? = null private var mHandler = Handler() // used for UI Update timer private var counter = 0 private val KEY_STATES = "states" private var shuttingDown = false /** * Defines callbacks for service binding, passed to bindService() */ private val mConnection = object : ServiceConnection { override fun onServiceConnected(className: ComponentName, service: IBinder) { // We've bound to LocalService, cast the IBinder and get LocalService instance /*binder = service as LoconetService.LocalBinder mService = binder.service mBound = true */ } override fun onServiceDisconnected(arg0: ComponentName) { mBound = false } } /** * Called when the activity is first created. */ public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (DEBUG) Log.d(TAG, "onCreate LanbahnPanelActivity") popUp = PopupWindow(this) layout = LinearLayout(this) appContext = this tv = TextView(this) but = Button(this) but.text = "Click Me" params = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) //layout.setOrientation(LinearLayout.VERTICAL); tv.text = "popup window with address..." layout.addView(tv, params) popUp.contentView = layout //ReadConfig.readConfig(this) READ IN ONRESUME setContentView(Panel(this)) builder = AlertDialog.Builder(this) builder.setMessage( applicationContext.getString(R.string.exit_confirm)) .setCancelable(false) .setPositiveButton(applicationContext.getString(R.string.yes) ) { _, _ -> shutdownClient() threadSleep(100L) clearPanelData() // needs to be done to start again with // a state of "UNKNOWN" when no current data finish() } .setNegativeButton(applicationContext.getString(R.string.no) ) { dialog, id -> dialog.cancel() } openCommunication() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { supportActionBar?.setBackgroundDrawable(ColorDrawable(-0xcf77d0)) } } override fun onBackPressed() { super.onBackPressed() if (DEBUG) Log.d(TAG, "onBackPressed - LanbahnPanelActivity") } override fun onStop() { super.onStop() if (DEBUG) Log.d(TAG, "onStop - LanbahnPanelActivity") // TODO unbindService(mConnection); // mBound = false; } override fun onPause() { super.onPause() if (DEBUG) Log.d(TAG, "onPause - LanbahnPanelActivity") (application as LanbahnPanelApplication).saveCurrentLoco() (application as LanbahnPanelApplication).savePanelSettings() //if (configHasChanged) { if (checkStorageWritePermission()) { WriteConfig.locosToXMLFile() } else { toast("ERROR: App has NO WRITE PERMISSION to write a new config file !") } if (prefs.getBoolean(KEY_SAVE_STATES, false)) saveStates() sendQ.clear() if (!shuttingDown) { (application as LanbahnPanelApplication).addNotification(this.intent) } } fun shutdownClient() { shuttingDown = true Log.d(TAG, "LanbahnPanelActivity - shutting down Client.") (application as LanbahnPanelApplication).removeNotification() client?.shutdown() client = null } override fun onResume() { super.onResume() if (DEBUG) Log.d(TAG, "onResume - LanbahnPanelActivity") sendQ.clear() var newPanel = reloadConfigIfPanelFileChanged() if (newPanel) { // get panel preferences (and override current preferences for scaling, quadrant (application as LanbahnPanelApplication).loadPanelSettings() } if (DEBUG) Log.d(TAG, "panelName=$panelName enableFiveViews=${prefs.getBoolean(KEY_FIVE_VIEWS_PREF,false)} selQuadrant=${prefs.getInt(KEY_QUADRANT,0)}") // set quadrants mode and display selected selQuadrant updateForQuadrantButtons() displayQuadrant(prefs.getInt(KEY_QUADRANT, 0)) displayLockAndRoutingState() setActionBarBackground() // matching to panel style LPaints.init(prescale, prefs.getString(KEY_STYLE_PREF, DEFAULT_STYLE), applicationContext) if (DEBUG) debugLogDisplayMetrics() if (prefs.getBoolean(KEY_SAVE_STATES, false)) { loadStates() } if (prefs.getBoolean(KEY_ENABLE_LOCO_CONTROL, false)) { // get last loco settings and (re-)init current loco initLocoList() } LanbahnPanelApplication.expireAllPanelElements() LanbahnPanelApplication.requestAllPanelData() mHandler.postDelayed({ updateUI() }, 500) (application as LanbahnPanelApplication).removeNotification() title = "Lanbahn Panel \"$panelName\"" } private fun setActionBarBackground() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return // does not work for old android versions when (prefs.getString(KEY_STYLE_PREF,DEFAULT_STYLE)) { "US" -> supportActionBar?.setBackgroundDrawable(ColorDrawable(-0xff990f)) //Color.BLUE)) // TODO color ?? "UK" -> supportActionBar?.setBackgroundDrawable(ColorDrawable(-0xdfAAdd)) // kotlin: 0xffff0000.toInt() "DE" -> supportActionBar?.setBackgroundDrawable(ColorDrawable(Color.BLUE)) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu, menu) mOptionsMenu = menu setConnectionIcon() updateForQuadrantButtons() displayLockAndRoutingState() return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_settings // call preferences activity -> { startActivity(Intent(this, SettingsActivity::class.java)) return true } R.id.action_connect -> { toast("trying reconnect") restartCommFlag = true return true } R.id.action_q1 -> { if (prefs.getBoolean(KEY_FIVE_VIEWS_PREF,false)) displayQuadrant(1) return true } R.id.action_q2 -> { if (prefs.getBoolean(KEY_FIVE_VIEWS_PREF,false)) displayQuadrant(2) return true } R.id.action_q3 -> { if (prefs.getBoolean(KEY_FIVE_VIEWS_PREF,false)) displayQuadrant(3) return true } R.id.action_q4 -> { if (prefs.getBoolean(KEY_FIVE_VIEWS_PREF,false)) displayQuadrant(4) return true } R.id.action_qall -> { if (prefs.getBoolean(KEY_FIVE_VIEWS_PREF,false)) displayQuadrant(0) return true } R.id.action_power -> { togglePower() // toast("switching power ON/OFF not allowed") return true } R.id.menu_about -> { startActivity(Intent(this, AboutActivity::class.java)) return true } R.id.menu_help -> { startActivity(Intent(this, HelpActivity::class.java)) return true } R.id.menu_get_panel -> { readPanelFromServer() return true } R.id.menu_flip_panel -> { PanelElement.flipPanel() return true } /* R.adr.menu_check_service -> { //TODO int num = mService.getRandomNumber(); toast("not implemented") // "number: " + num, Toast.LENGTH_SHORT).show(); return true } */ R.id.menu_quit -> { val alert = builder.create() alert.show() // done in alert: shutdownClient() return true } else -> return true //super.onOptionsItemSelected(item) } } fun openCommunication() { Log.d(TAG, "LanbahnPanelActivity - openCommunication.") sendQ.clear() if (client != null) { Log.d(TAG, "LanbahnPanelActivity - shutdown client.") client?.shutdown() threadSleep(100) // give client some time to shut down. } Log.d(TAG, "Sart of Communication to Comm.Station") startCommunication() Timer().scheduleAtFixedRate(object : TimerTask() { override fun run() { selectedLoco?.timer() if (restartCommFlag) { restartCommFlag = false runOnUiThread { Log.d(TAG, "restarting Communication to Comm.Station") startCommunication() } } } }, 100, 100) // request updates for all channels used in Panel is now done in "OnResume" } /** * remark: always running from UI Thread * * @return */ fun startCommunication() { Log.d(TAG, "LahnbahnPanelActivity - startCommunication.") if (client != null) { client?.shutdown() Thread.sleep(100) // give client some time to shut down. } val prefs = PreferenceManager .getDefaultSharedPreferences(this) val ip = prefs.getString(KEY_IP, DEFAULT_SXNET_IP) val port = Integer.parseInt(prefs.getString(KEY_PORT, DEFAULT_SXNET_PORT)) client = Railroad(ip!!, port) client?.start() /* // check connection after some seconds (async) (socket creation has 5sec timeout) val handler = Handler() handler.postDelayed({ if (connectionIsAlive()) { LanbahnPanelApplication.requestAllPanelData() } else { val msg = " NO CONNECTION TO $ip:$port! Check WiFi/SSID and server settings " longToast(msg) conn_state_string = "NOT CONNECTED" } }, 6500) */ } private fun updateUI() { counter++ // logString is updated via Binding mechanism // the actionBar icons are NOT updated via binding, because // "At the moment, data binding is only for layout resources, not menu resources" (google) // and the implementation to "work around" this limitation looks very complicated, see // https://stackoverflow.com/questions/38660735/how-bind-android-databinding-to-menu setConnectionIcon() setPowerStateIcon() displayLockAndRoutingState() // routing state can be changed by a lanbahn message anytime // now done centrally: Route.auto() /* TODO check which frequency is needed */ if ((counter.rem(4) == 0) and (prefs.getBoolean(KEY_ENABLE_LOCO_CONTROL, false)) and (selectedLoco != null)) { val adr = selectedLoco?.adr ?: INVALID_INT Commands.readLocoData(adr) } mHandler.postDelayed({ updateUI() }, 500) } private fun updateForQuadrantButtons() { if (mOptionsMenu == null) return if (prefs.getBoolean(KEY_FIVE_VIEWS_PREF,false)) { mOptionsMenu?.findItem(R.id.action_q1)?.setIcon(R.drawable.q1_v2_48_gray) mOptionsMenu?.findItem(R.id.action_q2)?.setIcon(R.drawable.q2_v2_48_gray) mOptionsMenu?.findItem(R.id.action_q3)?.setIcon(R.drawable.q3_v2_48_gray) mOptionsMenu?.findItem(R.id.action_q4)?.setIcon(R.drawable.q4_v2_48_gray) mOptionsMenu?.findItem(R.id.action_qall)?.setIcon(R.drawable.qa_v2_48_gray) when (prefs.getInt(KEY_QUADRANT, 0)) { // mark selected quadrant "white" 0 -> mOptionsMenu?.findItem(R.id.action_qall)?.setIcon(R.drawable.qa_v2_48) 1 -> mOptionsMenu?.findItem(R.id.action_q1)?.setIcon(R.drawable.q1_v2_48) 2 -> mOptionsMenu?.findItem(R.id.action_q2)?.setIcon(R.drawable.q2_v2_48) 3 -> mOptionsMenu?.findItem(R.id.action_q3)?.setIcon(R.drawable.q3_v2_48) 4 -> mOptionsMenu?.findItem(R.id.action_q4)?.setIcon(R.drawable.q4_v2_48) } } else { mOptionsMenu?.findItem(R.id.action_q1)?.setIcon(R.drawable.trans_48) mOptionsMenu?.findItem(R.id.action_q2)?.setIcon(R.drawable.trans_48) mOptionsMenu?.findItem(R.id.action_q3)?.setIcon(R.drawable.trans_48) mOptionsMenu?.findItem(R.id.action_q4)?.setIcon(R.drawable.trans_48) mOptionsMenu?.findItem(R.id.action_qall)?.setIcon(R.drawable.trans_48) } } private fun togglePower() { val prefs = PreferenceManager .getDefaultSharedPreferences(this) val allowed = prefs.getBoolean(KEY_ENABLE_POWER_CONTROL, false) if (client == null) return if (!(client!!.isConnected())) { toast("ERROR: not connected - cannot set global power state") } else if (allowed) { when (globalPower) { POWER_OFF -> Commands.setPower(1) POWER_ON -> Commands.setPower(0) POWER_UNKNOWN -> Commands.setPower(1) } } else { toast("not allowed to set global power state, check settings") } } private fun displayLockAndRoutingState() { //if (DEBUG) Log.d(TAG, "selectedScale = ${prefs.getString(KEY_SCALE_PREF,"auto")}") when (prefs.getString(KEY_SCALE_PREF,"auto")) { "auto" -> mOptionsMenu?.findItem(R.id.action_lock_state)?.setIcon(R.drawable.ic_letter_a) "manual" -> mOptionsMenu?.findItem(R.id.action_lock_state)?.setIcon(R.drawable.ic_lock_open_white_48dp) "locked" -> mOptionsMenu?.findItem(R.id.action_lock_state)?.setIcon(R.drawable.ic_lock_white_48dp) } when (prefs.getBoolean(KEY_ROUTING,false)) { true -> mOptionsMenu?.findItem(R.id.action_routing)?.setIcon(R.drawable.ic_letter_r) false -> mOptionsMenu?.findItem(R.id.action_routing)?.setIcon(R.drawable.ic_letter_non_r) } } private fun displayQuadrant(q: Int) { // 0 means "ALL" val editor = prefs.edit() if (prefs.getBoolean(KEY_FIVE_VIEWS_PREF,false) ) { editor.putInt(KEY_QUADRANT, q) } else { // must use "0" !! editor.putInt(KEY_QUADRANT, 0) } editor.commit() if (prefs.getString(KEY_SCALE_PREF,"auto") == "auto") { LanbahnPanelApplication.calcAutoScale(mWidth, mHeight, prefs.getInt(KEY_QUADRANT,0)) } // updateForQuadrantButtons() } private fun initLocoList() { if(!prefs.getBoolean(KEY_ENABLE_LOCO_CONTROL, false)) return; // do only when loco control is enabled val lastLocoAddress = prefs.getInt(KEY_LOCO_ADR, 3) if (locolist == null) { Toast.makeText(this, "could not read locolist from config xml file or errors in file", Toast.LENGTH_LONG).show() Log.e(TAG, "could not read loco list") } else { // if last loco (from stored loco_address) is in list then use this loco for (loco in locolist) { if (loco.adr === lastLocoAddress) { selectedLoco = loco // update from file selectedLoco?.initFromSX() } } } if (selectedLoco == null) { // use first loco in list or use default if (locolist.size >= 1) { selectedLoco = locolist[0] // first loco in xml file } else { // as a default use a "dummy loco" val locoMass = Integer .parseInt(prefs.getString(KEY_LOCO_MASS, "3")!!) val locoName = prefs.getString(KEY_LOCO_NAME, "DEFAULT") selectedLoco = Loco(locoName, lastLocoAddress, locoMass) selectedLoco?.initFromSX() } if (DEBUG) Log.d(TAG, "selectedLoco adr=" + selectedLoco?.adr) } } fun saveStates() { val sb = StringBuilder() for (pe in panelElements) { if (pe.adr != INVALID_INT) { if (pe.state != INVALID_INT) sb.append(pe.adr).append(",").append(pe.state).append(";") } } val prefs = PreferenceManager .getDefaultSharedPreferences(this) val editor = prefs.edit() Log.d(TAG, "saving States=" + sb.toString()) editor.putString(KEY_STATES, sb.toString()) editor.commit() } fun loadStates() { if (DEBUG) Log.d(TAG, "loading States") val prefs = PreferenceManager .getDefaultSharedPreferences(this) val states = prefs.getString(KEY_STATES, "") if (states!!.length == 0) { Log.d(TAG, "previous state of devices could not be read") return } try { val keyvalues = states.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() for (kv in keyvalues) { val s2 = kv.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() for (pe in panelElements) { if (pe is ActivePanelElement) { if (pe.adr == Integer.parseInt(s2[0])) { pe.state = Integer.parseInt(s2[1]) } } } } } catch (e: Exception) { Log.e(TAG, "Error during loadStates: " + e.message) } Log.d(TAG, "states=$states") } private fun setConnectionIcon() { if (LanbahnPanelApplication.connectionIsAlive()) { mOptionsMenu?.findItem(R.id.action_connect)?.setIcon(R.drawable.commok) } else { mOptionsMenu?.findItem(R.id.action_connect)?.setIcon(R.drawable.nocomm) globalPower = POWER_UNKNOWN } } /** display powert station only when the connection to the command station is on * */ private fun setPowerStateIcon() { if (cmdStationConnection == CMD_STATION_OFF) { mOptionsMenu?.findItem(R.id.action_power)?.setIcon(R.drawable.cmd_station_off) } else { when (globalPower) { POWER_OFF -> { mOptionsMenu?.findItem(R.id.action_power)?.setIcon(R.drawable.power_stop) } //power_red) POWER_ON -> { mOptionsMenu?.findItem(R.id.action_power)?.setIcon(R.drawable.power_green) } POWER_UNKNOWN -> mOptionsMenu?.findItem(R.id.action_power)?.setIcon(R.drawable.power_unknown) } } } private fun checkStorageWritePermission(): Boolean { if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // Permission is not granted // Should we show an explanation? /*if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. // TODO return false } else { */ // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), MY_PERMISSIONS_REQUEST_WRITE_STORAGE) // MY_PERMISSIONS_REQUEST_WRITE_STORAGE is an // app-defined int constant. The callback method gets the // result of the request. return false /* } */ } else { return true } } /** returned by Android after user has given permissions */ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { MY_PERMISSIONS_REQUEST_WRITE_STORAGE -> { // If request is cancelled, the result arrays are empty. if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // finally, we got the permission, write updated config file NOW WriteConfig.locosToXMLFile() } else { // permission denied, boo! Disable the functionality that depends on this permission. toast("cannot write log to File without permissions") } return } // Add other 'when' lines to check for other // permissions this app might request. else -> { // Ignore all other requests. } } } private fun reloadConfigIfPanelFileChanged(): Boolean { val prefs = PreferenceManager .getDefaultSharedPreferences(this) val cfFilename = prefs.getString(KEY_CONFIG_FILE, "-") var result = false // panel file changed or empty panel => (re-)load panel if ((cfFilename != configFilename) || (panelElements.size == 0)) { // reload, if a new panel config file selected configFilename = cfFilename if (DEBUG) { Log.d(TAG, "onResume - reloading panel config.") } if (prefs.getBoolean(KEY_LOCAL_LOCO_LIST, false)) { // if enabled, overwrite loco list from panel file with a local loco list ReadConfig.readConfigFromFile(this, true) // reload config File with relocate of origin ReadConfig.readLocalLocosFile(this) } else { ReadConfig.readConfigFromFile(this) // reload config File with relocate of origin } result = true } return result } private fun readPanelFromServer() { if (checkStorageWritePermission()) { saveStates() val prefs = PreferenceManager .getDefaultSharedPreferences(this) val server = prefs.getString(KEY_IP, "") val urlConfig = "http://$server:8000/config" getPanel(urlConfig) } else { longToast("ERROR: App has NO PERMISSION to write files !") } } private fun getPanel(url: String) { val state = Environment.getExternalStorageState() if (state != Environment.MEDIA_MOUNTED) {// We cannot read/write the media Log.e(TAG, "external storage not available or not writeable") toast("external storage not available or not writeable") return } doAsync { val (res, content) = Download(url).run() uiThread { if (res) { //Log.d(TAG, content) // content == filename longToast("file read => $content") Log.d(TAG, "config file read => reloading config from $content") ReadConfig.readConfigFromFile(appContext!!) loadStates() initLocoList() } else { longToast("ERROR: config file NOT read") Log.e(TAG, "config file NOT read - ERROR:\n$content") // content == error message } } } } private fun debugLogDisplayMetrics() { val metrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(metrics) val width = metrics.widthPixels val height = metrics.heightPixels if (DEBUG) Log.i(TAG, "metrics - w=$width h=$height") } companion object { lateinit var popUp: PopupWindow lateinit var layout: LinearLayout } }
gpl-3.0
543e7f9f0a518e09d113bb17e091dd5e
35.117568
160
0.580275
4.534611
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/lazy/list/LazyListAnimateItemPlacementTest.kt
3
48885
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.lazy.list import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.requiredHeightIn import androidx.compose.foundation.layout.requiredWidth import androidx.compose.foundation.layout.requiredWidthIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyItemScope import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.SemanticsNodeInteraction import androidx.compose.ui.test.assertHeightIsEqualTo import androidx.compose.ui.test.assertIsNotDisplayed import androidx.compose.ui.test.assertWidthIsEqualTo import androidx.compose.ui.test.getBoundsInRoot import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.height import androidx.compose.ui.unit.width import androidx.test.filters.LargeTest import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import kotlinx.coroutines.runBlocking import org.junit.Assume.assumeTrue import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import kotlin.math.roundToInt @LargeTest @RunWith(Parameterized::class) @OptIn(ExperimentalFoundationApi::class) class LazyListAnimateItemPlacementTest(private val config: Config) { private val isVertical: Boolean get() = config.isVertical private val reverseLayout: Boolean get() = config.reverseLayout @get:Rule val rule = createComposeRule() private val itemSize: Int = 50 private var itemSizeDp: Dp = Dp.Infinity private val itemSize2: Int = 30 private var itemSize2Dp: Dp = Dp.Infinity private val itemSize3: Int = 20 private var itemSize3Dp: Dp = Dp.Infinity private val containerSize: Int = itemSize * 5 private var containerSizeDp: Dp = Dp.Infinity private val spacing: Int = 10 private var spacingDp: Dp = Dp.Infinity private val itemSizePlusSpacing = itemSize + spacing private var itemSizePlusSpacingDp = Dp.Infinity private lateinit var state: LazyListState @Before fun before() { rule.mainClock.autoAdvance = false with(rule.density) { itemSizeDp = itemSize.toDp() itemSize2Dp = itemSize2.toDp() itemSize3Dp = itemSize3.toDp() containerSizeDp = containerSize.toDp() spacingDp = spacing.toDp() itemSizePlusSpacingDp = itemSizePlusSpacing.toDp() } } @Test fun reorderTwoItems() { var list by mutableStateOf(listOf(0, 1)) rule.setContent { LazyList { items(list, key = { it }) { Item(it) } } } assertPositions(0 to 0, 1 to itemSize) rule.runOnIdle { list = listOf(1, 0) } onAnimationFrame { fraction -> assertPositions( 0 to 0 + (itemSize * fraction).roundToInt(), 1 to itemSize - (itemSize * fraction).roundToInt(), fraction = fraction ) } } @Test fun reorderTwoItems_layoutInfoHasFinalPositions() { var list by mutableStateOf(listOf(0, 1)) rule.setContent { LazyList { items(list, key = { it }) { Item(it) } } } assertLayoutInfoPositions(0 to 0, 1 to itemSize) rule.runOnIdle { list = listOf(1, 0) } onAnimationFrame { // fraction doesn't affect the offsets in layout info assertLayoutInfoPositions(1 to 0, 0 to itemSize) } } @Test fun reorderFirstAndLastItems() { var list by mutableStateOf(listOf(0, 1, 2, 3, 4)) rule.setContent { LazyList { items(list, key = { it }) { Item(it) } } } assertPositions( 0 to 0, 1 to itemSize, 2 to itemSize * 2, 3 to itemSize * 3, 4 to itemSize * 4, ) rule.runOnIdle { list = listOf(4, 1, 2, 3, 0) } onAnimationFrame { fraction -> assertPositions( 0 to 0 + (itemSize * 4 * fraction).roundToInt(), 1 to itemSize, 2 to itemSize * 2, 3 to itemSize * 3, 4 to itemSize * 4 - (itemSize * 4 * fraction).roundToInt(), fraction = fraction ) } } @Test fun moveFirstItemToEndCausingAllItemsToAnimate() { var list by mutableStateOf(listOf(0, 1, 2, 3, 4)) rule.setContent { LazyList { items(list, key = { it }) { Item(it) } } } assertPositions( 0 to 0, 1 to itemSize, 2 to itemSize * 2, 3 to itemSize * 3, 4 to itemSize * 4, ) rule.runOnIdle { list = listOf(1, 2, 3, 4, 0) } onAnimationFrame { fraction -> assertPositions( 0 to 0 + (itemSize * 4 * fraction).roundToInt(), 1 to itemSize - (itemSize * fraction).roundToInt(), 2 to itemSize * 2 - (itemSize * fraction).roundToInt(), 3 to itemSize * 3 - (itemSize * fraction).roundToInt(), 4 to itemSize * 4 - (itemSize * fraction).roundToInt(), fraction = fraction ) } } @Test fun itemSizeChangeAnimatesNextItems() { var size by mutableStateOf(itemSizeDp) rule.setContent { LazyList( minSize = itemSizeDp * 5, maxSize = itemSizeDp * 5 ) { items(listOf(0, 1, 2, 3), key = { it }) { Item(it, size = if (it == 1) size else itemSizeDp) } } } rule.runOnIdle { size = itemSizeDp * 2 } rule.mainClock.advanceTimeByFrame() rule.onNodeWithTag("1") .assertMainAxisSizeIsEqualTo(size) onAnimationFrame { fraction -> if (!reverseLayout) { assertPositions( 0 to 0, 1 to itemSize, 2 to itemSize * 2 + (itemSize * fraction).roundToInt(), 3 to itemSize * 3 + (itemSize * fraction).roundToInt(), fraction = fraction, autoReverse = false ) } else { assertPositions( 3 to itemSize - (itemSize * fraction).roundToInt(), 2 to itemSize * 2 - (itemSize * fraction).roundToInt(), 1 to itemSize * 3 - (itemSize * fraction).roundToInt(), 0 to itemSize * 4, fraction = fraction, autoReverse = false ) } } } @Test fun onlyItemsWithModifierAnimates() { var list by mutableStateOf(listOf(0, 1, 2, 3, 4)) rule.setContent { LazyList { items(list, key = { it }) { Item(it, animSpec = if (it == 1 || it == 3) AnimSpec else null) } } } rule.runOnIdle { list = listOf(1, 2, 3, 4, 0) } onAnimationFrame { fraction -> assertPositions( 0 to itemSize * 4, 1 to itemSize - (itemSize * fraction).roundToInt(), 2 to itemSize, 3 to itemSize * 3 - (itemSize * fraction).roundToInt(), 4 to itemSize * 3, fraction = fraction ) } } @Test fun animationsWithDifferentDurations() { var list by mutableStateOf(listOf(0, 1, 2, 3, 4)) rule.setContent { LazyList { items(list, key = { it }) { val duration = if (it == 1 || it == 3) Duration * 2 else Duration Item(it, animSpec = tween(duration.toInt(), easing = LinearEasing)) } } } rule.runOnIdle { list = listOf(1, 2, 3, 4, 0) } onAnimationFrame(duration = Duration * 2) { fraction -> val shorterAnimFraction = (fraction * 2).coerceAtMost(1f) assertPositions( 0 to 0 + (itemSize * 4 * shorterAnimFraction).roundToInt(), 1 to itemSize - (itemSize * fraction).roundToInt(), 2 to itemSize * 2 - (itemSize * shorterAnimFraction).roundToInt(), 3 to itemSize * 3 - (itemSize * fraction).roundToInt(), 4 to itemSize * 4 - (itemSize * shorterAnimFraction).roundToInt(), fraction = fraction ) } } @Test fun multipleChildrenPerItem() { var list by mutableStateOf(listOf(0, 2)) rule.setContent { LazyList { items(list, key = { it }) { Item(it) Item(it + 1) } } } assertPositions( 0 to 0, 1 to itemSize, 2 to itemSize * 2, 3 to itemSize * 3, ) rule.runOnIdle { list = listOf(2, 0) } onAnimationFrame { fraction -> assertPositions( 0 to 0 + (itemSize * 2 * fraction).roundToInt(), 1 to itemSize + (itemSize * 2 * fraction).roundToInt(), 2 to itemSize * 2 - (itemSize * 2 * fraction).roundToInt(), 3 to itemSize * 3 - (itemSize * 2 * fraction).roundToInt(), fraction = fraction ) } } @Test fun multipleChildrenPerItemSomeDoNotAnimate() { var list by mutableStateOf(listOf(0, 2)) rule.setContent { LazyList { items(list, key = { it }) { Item(it) Item(it + 1, animSpec = null) } } } rule.runOnIdle { list = listOf(2, 0) } onAnimationFrame { fraction -> assertPositions( 0 to 0 + (itemSize * 2 * fraction).roundToInt(), 1 to itemSize * 3, 2 to itemSize * 2 - (itemSize * 2 * fraction).roundToInt(), 3 to itemSize, fraction = fraction ) } } @Test fun animateArrangementChange() { var arrangement by mutableStateOf(Arrangement.Center) rule.setContent { LazyList( arrangement = arrangement, minSize = itemSizeDp * 5, maxSize = itemSizeDp * 5 ) { items(listOf(1, 2, 3), key = { it }) { Item(it) } } } assertPositions( 1 to itemSize, 2 to itemSize * 2, 3 to itemSize * 3, ) rule.runOnIdle { arrangement = Arrangement.SpaceBetween } rule.mainClock.advanceTimeByFrame() onAnimationFrame { fraction -> assertPositions( 1 to itemSize - (itemSize * fraction).roundToInt(), 2 to itemSize * 2, 3 to itemSize * 3 + (itemSize * fraction).roundToInt(), fraction = fraction ) } } @Test fun moveItemToTheBottomOutsideOfBounds() { var list by mutableStateOf(listOf(0, 1, 2, 3, 4, 5)) rule.setContent { LazyList(maxSize = itemSizeDp * 3) { items(list, key = { it }) { Item(it) } } } assertPositions( 0 to 0, 1 to itemSize, 2 to itemSize * 2 ) rule.runOnIdle { list = listOf(0, 4, 2, 3, 1, 5) } onAnimationFrame { fraction -> val item1Offset = itemSize + (itemSize * 3 * fraction).roundToInt() val item4Offset = itemSize * 4 - (itemSize * 3 * fraction).roundToInt() val expected = mutableListOf<Pair<Any, Int>>().apply { add(0 to 0) if (item1Offset < itemSize * 3) { add(1 to item1Offset) } else { rule.onNodeWithTag("1").assertIsNotDisplayed() } add(2 to itemSize * 2) if (item4Offset < itemSize * 3) { add(4 to item4Offset) } else { rule.onNodeWithTag("4").assertIsNotDisplayed() } } assertPositions( expected = expected.toTypedArray(), fraction = fraction ) } } @Test fun moveItemToTheTopOutsideOfBounds() { var list by mutableStateOf(listOf(0, 1, 2, 3, 4, 5)) rule.setContent { LazyList(maxSize = itemSizeDp * 3f, startIndex = 3) { items(list, key = { it }) { Item(it) } } } assertPositions( 3 to 0, 4 to itemSize, 5 to itemSize * 2 ) rule.runOnIdle { list = listOf(2, 4, 0, 3, 1, 5) } onAnimationFrame { fraction -> val item1Offset = itemSize * -2 + (itemSize * 3 * fraction).roundToInt() val item4Offset = itemSize - (itemSize * 3 * fraction).roundToInt() val expected = mutableListOf<Pair<Any, Int>>().apply { if (item4Offset > -itemSize) { add(4 to item4Offset) } else { rule.onNodeWithTag("4").assertIsNotDisplayed() } add(3 to 0) if (item1Offset > -itemSize) { add(1 to item1Offset) } else { rule.onNodeWithTag("1").assertIsNotDisplayed() } add(5 to itemSize * 2) } assertPositions( expected = expected.toTypedArray(), fraction = fraction ) } } @Test fun moveItemToTheTopOutsideOfBounds_withStickyHeader() { var list by mutableStateOf(listOf(0, 1, 2, 3, 4)) rule.setContent { LazyList(maxSize = itemSizeDp * 2f, startIndex = 4) { // the existence of this header shouldn't affect the animation aside from // the fact that we need to adjust startIndex because of it`s existence. stickyHeader {} items(list, key = { it }) { Item(it) } } } assertPositions( 3 to 0, 4 to itemSize ) rule.runOnIdle { list = listOf(2, 4, 0, 3, 1) } onAnimationFrame { fraction -> val item1Offset = itemSize * -2 + (itemSize * 3 * fraction).roundToInt() val item4Offset = itemSize - (itemSize * 3 * fraction).roundToInt() val expected = mutableListOf<Pair<Any, Int>>().apply { if (item4Offset > -itemSize) { add(4 to item4Offset) } else { rule.onNodeWithTag("4").assertIsNotDisplayed() } add(3 to 0) if (item1Offset > -itemSize) { add(1 to item1Offset) } else { rule.onNodeWithTag("1").assertIsNotDisplayed() } } assertPositions( expected = expected.toTypedArray(), fraction = fraction ) } } @Test fun moveFirstItemToEndCausingAllItemsToAnimate_withSpacing() { var list by mutableStateOf(listOf(0, 1, 2, 3)) rule.setContent { LazyList(arrangement = Arrangement.spacedBy(spacingDp)) { items(list, key = { it }) { Item(it) } } } rule.runOnIdle { list = listOf(1, 2, 3, 0) } onAnimationFrame { fraction -> assertPositions( 0 to 0 + (itemSizePlusSpacing * 3 * fraction).roundToInt(), 1 to itemSizePlusSpacing - (itemSizePlusSpacing * fraction).roundToInt(), 2 to itemSizePlusSpacing * 2 - (itemSizePlusSpacing * fraction).roundToInt(), 3 to itemSizePlusSpacing * 3 - (itemSizePlusSpacing * fraction).roundToInt(), fraction = fraction ) } } @Test fun moveItemToTheBottomOutsideOfBounds_withSpacing() { var list by mutableStateOf(listOf(0, 1, 2, 3, 4, 5)) rule.setContent { LazyList( maxSize = itemSizeDp * 3 + spacingDp * 2, arrangement = Arrangement.spacedBy(spacingDp) ) { items(list, key = { it }) { Item(it) } } } assertPositions( 0 to 0, 1 to itemSizePlusSpacing, 2 to itemSizePlusSpacing * 2 ) rule.runOnIdle { list = listOf(0, 4, 2, 3, 1, 5) } onAnimationFrame { fraction -> val item1Offset = itemSizePlusSpacing + (itemSizePlusSpacing * 3 * fraction).roundToInt() val item4Offset = itemSizePlusSpacing * 4 - (itemSizePlusSpacing * 3 * fraction).roundToInt() val screenSize = itemSize * 3 + spacing * 2 val expected = mutableListOf<Pair<Any, Int>>().apply { add(0 to 0) if (item1Offset < screenSize) { add(1 to item1Offset) } else { rule.onNodeWithTag("1").assertIsNotDisplayed() } add(2 to itemSizePlusSpacing * 2) if (item4Offset < screenSize) { add(4 to item4Offset) } else { rule.onNodeWithTag("4").assertIsNotDisplayed() } } assertPositions( expected = expected.toTypedArray(), fraction = fraction ) } } @Test fun moveItemToTheTopOutsideOfBounds_withSpacing() { var list by mutableStateOf(listOf(0, 1, 2, 3, 4, 5, 6, 7)) rule.setContent { LazyList( maxSize = itemSizeDp * 3 + spacingDp * 2, startIndex = 3, arrangement = Arrangement.spacedBy(spacingDp) ) { items(list, key = { it }) { Item(it) } } } assertPositions( 3 to 0, 4 to itemSizePlusSpacing, 5 to itemSizePlusSpacing * 2 ) rule.runOnIdle { list = listOf(2, 4, 0, 3, 1, 5, 6, 7) } onAnimationFrame { fraction -> val item1Offset = itemSizePlusSpacing * -2 + (itemSizePlusSpacing * 3 * fraction).roundToInt() val item4Offset = (itemSizePlusSpacing - itemSizePlusSpacing * 3 * fraction).roundToInt() val expected = mutableListOf<Pair<Any, Int>>().apply { if (item4Offset > -itemSize) { add(4 to item4Offset) } else { rule.onNodeWithTag("4").assertIsNotDisplayed() } add(3 to 0) if (item1Offset > -itemSize) { add(1 to item1Offset) } else { rule.onNodeWithTag("1").assertIsNotDisplayed() } add(5 to itemSizePlusSpacing * 2) } assertPositions( expected = expected.toTypedArray(), fraction = fraction ) } } @Test fun moveItemToTheTopOutsideOfBounds_differentSizes() { var list by mutableStateOf(listOf(0, 1, 2, 3, 4, 5)) rule.setContent { LazyList(maxSize = itemSize2Dp + itemSize3Dp + itemSizeDp, startIndex = 3) { items(list, key = { it }) { val size = if (it == 3) itemSize2Dp else if (it == 1) itemSize3Dp else itemSizeDp Item(it, size = size) } } } val item3Size = itemSize2 val item4Size = itemSize assertPositions( 3 to 0, 4 to item3Size, 5 to item3Size + item4Size ) rule.runOnIdle { // swap 4 and 1 list = listOf(0, 4, 2, 3, 1, 5) } onAnimationFrame { fraction -> rule.onNodeWithTag("2").assertDoesNotExist() // item 2 was between 1 and 3 but we don't compose it and don't know the real size, // so we use an average size. val item2Size = (itemSize + itemSize2 + itemSize3) / 3 val item1Size = itemSize3 /* the real size of the item 1 */ val startItem1Offset = -item1Size - item2Size val item1Offset = startItem1Offset + ((itemSize2 - startItem1Offset) * fraction).roundToInt() val endItem4Offset = -item4Size - item2Size val item4Offset = item3Size - ((item3Size - endItem4Offset) * fraction).roundToInt() val expected = mutableListOf<Pair<Any, Int>>().apply { if (item4Offset > -item4Size) { add(4 to item4Offset) } else { rule.onNodeWithTag("4").assertIsNotDisplayed() } add(3 to 0) if (item1Offset > -item1Size) { add(1 to item1Offset) } else { rule.onNodeWithTag("1").assertIsNotDisplayed() } add(5 to item3Size + item4Size - ((item4Size - item1Size) * fraction).roundToInt()) } assertPositions( expected = expected.toTypedArray(), fraction = fraction ) } } @Test fun moveItemToTheBottomOutsideOfBounds_differentSizes() { var list by mutableStateOf(listOf(0, 1, 2, 3, 4, 5)) val listSize = itemSize2 + itemSize3 + itemSize - 1 val listSizeDp = with(rule.density) { listSize.toDp() } rule.setContent { LazyList(maxSize = listSizeDp) { items(list, key = { it }) { val size = if (it == 0) itemSize2Dp else if (it == 4) itemSize3Dp else itemSizeDp Item(it, size = size) } } } val item0Size = itemSize2 val item1Size = itemSize assertPositions( 0 to 0, 1 to item0Size, 2 to item0Size + item1Size ) rule.runOnIdle { list = listOf(0, 4, 2, 3, 1, 5) } onAnimationFrame { fraction -> val item2Size = itemSize val item4Size = itemSize3 // item 3 was between 2 and 4 but we don't compose it and don't know the real size, // so we use an average size. val item3Size = (itemSize + itemSize2 + itemSize3) / 3 val startItem4Offset = item0Size + item1Size + item2Size + item3Size val endItem1Offset = item0Size + item4Size + item2Size + item3Size val item1Offset = item0Size + ((endItem1Offset - item0Size) * fraction).roundToInt() val item4Offset = startItem4Offset - ((startItem4Offset - item0Size) * fraction).roundToInt() val expected = mutableListOf<Pair<Any, Int>>().apply { add(0 to 0) if (item1Offset < listSize) { add(1 to item1Offset) } else { rule.onNodeWithTag("1").assertIsNotDisplayed() } add(2 to item0Size + item1Size - ((item1Size - item4Size) * fraction).roundToInt()) if (item4Offset < listSize) { add(4 to item4Offset) } else { rule.onNodeWithTag("4").assertIsNotDisplayed() } } assertPositions( expected = expected.toTypedArray(), fraction = fraction ) } } @Test fun animateAlignmentChange() { var alignment by mutableStateOf(CrossAxisAlignment.End) rule.setContent { LazyList( crossAxisAlignment = alignment, crossAxisSize = itemSizeDp ) { items(listOf(1, 2, 3), key = { it }) { val crossAxisSize = if (it == 1) itemSizeDp else if (it == 2) itemSize2Dp else itemSize3Dp Item(it, crossAxisSize = crossAxisSize) } } } val item2Start = itemSize - itemSize2 val item3Start = itemSize - itemSize3 assertPositions( 1 to 0, 2 to itemSize, 3 to itemSize * 2, crossAxis = listOf( 1 to 0, 2 to item2Start, 3 to item3Start, ) ) rule.runOnIdle { alignment = CrossAxisAlignment.Center } rule.mainClock.advanceTimeByFrame() val item2End = itemSize / 2 - itemSize2 / 2 val item3End = itemSize / 2 - itemSize3 / 2 onAnimationFrame { fraction -> assertPositions( 1 to 0, 2 to itemSize, 3 to itemSize * 2, crossAxis = listOf( 1 to 0, 2 to item2Start + ((item2End - item2Start) * fraction).roundToInt(), 3 to item3Start + ((item3End - item3Start) * fraction).roundToInt(), ), fraction = fraction ) } } @Test fun animateAlignmentChange_multipleChildrenPerItem() { var alignment by mutableStateOf(CrossAxisAlignment.Start) rule.setContent { LazyList( crossAxisAlignment = alignment, crossAxisSize = itemSizeDp * 2 ) { items(1) { listOf(1, 2, 3).forEach { val crossAxisSize = if (it == 1) itemSizeDp else if (it == 2) itemSize2Dp else itemSize3Dp Item(it, crossAxisSize = crossAxisSize) } } } } rule.runOnIdle { alignment = CrossAxisAlignment.End } rule.mainClock.advanceTimeByFrame() val containerSize = itemSize * 2 onAnimationFrame { fraction -> assertPositions( 1 to 0, 2 to itemSize, 3 to itemSize * 2, crossAxis = listOf( 1 to ((containerSize - itemSize) * fraction).roundToInt(), 2 to ((containerSize - itemSize2) * fraction).roundToInt(), 3 to ((containerSize - itemSize3) * fraction).roundToInt() ), fraction = fraction ) } } @Test fun animateAlignmentChange_rtl() { // this test is not applicable to LazyRow assumeTrue(isVertical) var alignment by mutableStateOf(CrossAxisAlignment.End) rule.setContent { CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) { LazyList( crossAxisAlignment = alignment, crossAxisSize = itemSizeDp ) { items(listOf(1, 2, 3), key = { it }) { val crossAxisSize = if (it == 1) itemSizeDp else if (it == 2) itemSize2Dp else itemSize3Dp Item(it, crossAxisSize = crossAxisSize) } } } } assertPositions( 1 to 0, 2 to itemSize, 3 to itemSize * 2, crossAxis = listOf( 1 to 0, 2 to 0, 3 to 0, ) ) rule.runOnIdle { alignment = CrossAxisAlignment.Center } rule.mainClock.advanceTimeByFrame() onAnimationFrame { fraction -> assertPositions( 1 to 0, 2 to itemSize, 3 to itemSize * 2, crossAxis = listOf( 1 to 0, 2 to ((itemSize / 2 - itemSize2 / 2) * fraction).roundToInt(), 3 to ((itemSize / 2 - itemSize3 / 2) * fraction).roundToInt(), ), fraction = fraction ) } } @Test fun moveItemToEndCausingNextItemsToAnimate_withContentPadding() { var list by mutableStateOf(listOf(0, 1, 2, 3, 4)) val rawStartPadding = 8 val rawEndPadding = 12 val (startPaddingDp, endPaddingDp) = with(rule.density) { rawStartPadding.toDp() to rawEndPadding.toDp() } rule.setContent { LazyList(startPadding = startPaddingDp, endPadding = endPaddingDp) { items(list, key = { it }) { Item(it) } } } val startPadding = if (reverseLayout) rawEndPadding else rawStartPadding assertPositions( 0 to startPadding, 1 to startPadding + itemSize, 2 to startPadding + itemSize * 2, 3 to startPadding + itemSize * 3, 4 to startPadding + itemSize * 4, ) rule.runOnIdle { list = listOf(0, 2, 3, 4, 1) } onAnimationFrame { fraction -> assertPositions( 0 to startPadding, 1 to startPadding + itemSize + (itemSize * 3 * fraction).roundToInt(), 2 to startPadding + itemSize * 2 - (itemSize * fraction).roundToInt(), 3 to startPadding + itemSize * 3 - (itemSize * fraction).roundToInt(), 4 to startPadding + itemSize * 4 - (itemSize * fraction).roundToInt(), fraction = fraction ) } } @Test fun reorderFirstAndLastItems_noNewLayoutInfoProduced() { var list by mutableStateOf(listOf(0, 1, 2, 3, 4)) var measurePasses = 0 rule.setContent { LazyList { items(list, key = { it }) { Item(it) } } LaunchedEffect(Unit) { snapshotFlow { state.layoutInfo } .collect { measurePasses++ } } } rule.runOnIdle { list = listOf(4, 1, 2, 3, 0) } var startMeasurePasses = Int.MIN_VALUE onAnimationFrame { fraction -> if (fraction == 0f) { startMeasurePasses = measurePasses } } rule.mainClock.advanceTimeByFrame() // new layoutInfo is produced on every remeasure of Lazy lists. // but we want to avoid remeasuring and only do relayout on each animation frame. // two extra measures are possible as we switch inProgress flag. assertThat(measurePasses).isAtMost(startMeasurePasses + 2) } @Test fun noAnimationWhenScrollOtherPosition() { rule.setContent { LazyList(maxSize = itemSizeDp * 3) { items(listOf(0, 1, 2, 3, 4, 5, 6, 7), key = { it }) { Item(it) } } } rule.runOnIdle { runBlocking { state.scrollToItem(0, itemSize / 2) } } onAnimationFrame { fraction -> assertPositions( 0 to -itemSize / 2, 1 to itemSize / 2, 2 to itemSize * 3 / 2, 3 to itemSize * 5 / 2, fraction = fraction ) } } @Test fun noAnimationWhenScrollForwardBySmallOffset() { rule.setContent { LazyList(maxSize = itemSizeDp * 3) { items(listOf(0, 1, 2, 3, 4, 5, 6, 7), key = { it }) { Item(it) } } } rule.runOnIdle { runBlocking { state.scrollBy(itemSize / 2f) } } onAnimationFrame { fraction -> assertPositions( 0 to -itemSize / 2, 1 to itemSize / 2, 2 to itemSize * 3 / 2, 3 to itemSize * 5 / 2, fraction = fraction ) } } @Test fun noAnimationWhenScrollBackwardBySmallOffset() { rule.setContent { LazyList(maxSize = itemSizeDp * 3, startIndex = 2) { items(listOf(0, 1, 2, 3, 4, 5, 6, 7), key = { it }) { Item(it) } } } rule.runOnIdle { runBlocking { state.scrollBy(-itemSize / 2f) } } onAnimationFrame { fraction -> assertPositions( 1 to -itemSize / 2, 2 to itemSize / 2, 3 to itemSize * 3 / 2, 4 to itemSize * 5 / 2, fraction = fraction ) } } @Test fun noAnimationWhenScrollForwardByLargeOffset() { rule.setContent { LazyList(maxSize = itemSizeDp * 3) { items(listOf(0, 1, 2, 3, 4, 5, 6, 7), key = { it }) { Item(it) } } } rule.runOnIdle { runBlocking { state.scrollBy(itemSize * 2.5f) } } onAnimationFrame { fraction -> assertPositions( 2 to -itemSize / 2, 3 to itemSize / 2, 4 to itemSize * 3 / 2, 5 to itemSize * 5 / 2, fraction = fraction ) } } @Test fun noAnimationWhenScrollBackwardByLargeOffset() { rule.setContent { LazyList(maxSize = itemSizeDp * 3, startIndex = 3) { items(listOf(0, 1, 2, 3, 4, 5, 6, 7), key = { it }) { Item(it) } } } rule.runOnIdle { runBlocking { state.scrollBy(-itemSize * 2.5f) } } onAnimationFrame { fraction -> assertPositions( 0 to -itemSize / 2, 1 to itemSize / 2, 2 to itemSize * 3 / 2, 3 to itemSize * 5 / 2, fraction = fraction ) } } @Test fun noAnimationWhenScrollForwardByLargeOffset_differentSizes() { rule.setContent { LazyList(maxSize = itemSizeDp * 3) { items(listOf(0, 1, 2, 3, 4, 5, 6, 7), key = { it }) { Item(it, size = if (it % 2 == 0) itemSizeDp else itemSize2Dp) } } } rule.runOnIdle { runBlocking { state.scrollBy(itemSize + itemSize2 + itemSize / 2f) } } onAnimationFrame { fraction -> assertPositions( 2 to -itemSize / 2, 3 to itemSize / 2, 4 to itemSize2 + itemSize / 2, 5 to itemSize2 + itemSize * 3 / 2, fraction = fraction ) } } @Test fun noAnimationWhenScrollBackwardByLargeOffset_differentSizes() { rule.setContent { LazyList(maxSize = itemSizeDp * 3, startIndex = 3) { items(listOf(0, 1, 2, 3, 4, 5, 6, 7), key = { it }) { Item(it, size = if (it % 2 == 0) itemSizeDp else itemSize2Dp) } } } rule.runOnIdle { runBlocking { state.scrollBy(-(itemSize + itemSize2 + itemSize / 2f)) } } onAnimationFrame { fraction -> assertPositions( 0 to -itemSize / 2, 1 to itemSize / 2, 2 to itemSize2 + itemSize / 2, 3 to itemSize2 + itemSize * 3 / 2, fraction = fraction ) } } @Test fun itemWithSpecsIsMovingOut() { var list by mutableStateOf(listOf(0, 1, 2, 3)) rule.setContent { LazyList(maxSize = itemSizeDp * 2) { items(list, key = { it }) { Item(it, animSpec = if (it == 1) AnimSpec else null) } } } rule.runOnIdle { list = listOf(0, 2, 3, 1) } onAnimationFrame { fraction -> val listSize = itemSize * 2 val item1Offset = itemSize + (itemSize * 2f * fraction).roundToInt() val expected = mutableListOf<Pair<Any, Int>>().apply { add(0 to 0) if (item1Offset < listSize) { add(1 to item1Offset) } else { rule.onNodeWithTag("1").assertIsNotDisplayed() } } assertPositions( expected = expected.toTypedArray(), fraction = fraction ) } } private fun assertPositions( vararg expected: Pair<Any, Int>, crossAxis: List<Pair<Any, Int>>? = null, fraction: Float? = null, autoReverse: Boolean = reverseLayout ) { with(rule.density) { val actual = expected.map { val actualOffset = rule.onNodeWithTag(it.first.toString()) .getUnclippedBoundsInRoot().let { bounds -> val offset = if (isVertical) bounds.top else bounds.left if (offset == Dp.Unspecified) Int.MIN_VALUE else offset.roundToPx() } it.first to actualOffset } val subject = if (fraction == null) { assertThat(actual) } else { assertWithMessage("Fraction=$fraction").that(actual) } subject.isEqualTo( listOf(*expected).let { list -> if (!autoReverse) { list } else { val containerBounds = rule.onNodeWithTag(ContainerTag).getBoundsInRoot() val mainAxisSize = if (isVertical) containerBounds.height else containerBounds.width val mainAxisSizePx = with(rule.density) { mainAxisSize.roundToPx() } list.map { val itemSize = rule.onNodeWithTag(it.first.toString()) .getUnclippedBoundsInRoot().let { bounds -> (if (isVertical) bounds.height else bounds.width).roundToPx() } it.first to (mainAxisSizePx - itemSize - it.second) } } } ) if (crossAxis != null) { val actualCross = expected.map { val actualOffset = rule.onNodeWithTag(it.first.toString()) .getUnclippedBoundsInRoot().let { bounds -> val offset = if (isVertical) bounds.left else bounds.top if (offset == Dp.Unspecified) Int.MIN_VALUE else offset.roundToPx() } it.first to actualOffset } assertWithMessage( "CrossAxis" + if (fraction != null) "for fraction=$fraction" else "" ) .that(actualCross) .isEqualTo(crossAxis) } } } private fun assertLayoutInfoPositions(vararg offsets: Pair<Any, Int>) { rule.runOnIdle { assertThat(visibleItemsOffsets).isEqualTo(listOf(*offsets)) } } private val visibleItemsOffsets: List<Pair<Any, Int>> get() = state.layoutInfo.visibleItemsInfo.map { it.key to it.offset } private fun onAnimationFrame(duration: Long = Duration, onFrame: (fraction: Float) -> Unit) { require(duration.mod(FrameDuration) == 0L) rule.waitForIdle() rule.mainClock.advanceTimeByFrame() var expectedTime = rule.mainClock.currentTime for (i in 0..duration step FrameDuration) { onFrame(i / duration.toFloat()) rule.mainClock.advanceTimeBy(FrameDuration) expectedTime += FrameDuration assertThat(expectedTime).isEqualTo(rule.mainClock.currentTime) rule.waitForIdle() } } @Composable private fun LazyList( arrangement: Arrangement.HorizontalOrVertical? = null, minSize: Dp = 0.dp, maxSize: Dp = containerSizeDp, startIndex: Int = 0, crossAxisSize: Dp = Dp.Unspecified, crossAxisAlignment: CrossAxisAlignment = CrossAxisAlignment.Start, startPadding: Dp = 0.dp, endPadding: Dp = 0.dp, content: LazyListScope.() -> Unit ) { state = rememberLazyListState(startIndex) if (isVertical) { val verticalArrangement = arrangement ?: if (!reverseLayout) Arrangement.Top else Arrangement.Bottom val horizontalAlignment = if (crossAxisAlignment == CrossAxisAlignment.Start) { Alignment.Start } else if (crossAxisAlignment == CrossAxisAlignment.Center) { Alignment.CenterHorizontally } else { Alignment.End } LazyColumn( state = state, modifier = Modifier .requiredHeightIn(min = minSize, max = maxSize) .then( if (crossAxisSize != Dp.Unspecified) { Modifier.requiredWidth(crossAxisSize) } else { Modifier.fillMaxWidth() } ) .testTag(ContainerTag), verticalArrangement = verticalArrangement, horizontalAlignment = horizontalAlignment, reverseLayout = reverseLayout, contentPadding = PaddingValues(top = startPadding, bottom = endPadding), content = content ) } else { val horizontalArrangement = arrangement ?: if (!reverseLayout) Arrangement.Start else Arrangement.End val verticalAlignment = if (crossAxisAlignment == CrossAxisAlignment.Start) { Alignment.Top } else if (crossAxisAlignment == CrossAxisAlignment.Center) { Alignment.CenterVertically } else { Alignment.Bottom } LazyRow( state = state, modifier = Modifier .requiredWidthIn(min = minSize, max = maxSize) .then( if (crossAxisSize != Dp.Unspecified) { Modifier.requiredHeight(crossAxisSize) } else { Modifier.fillMaxHeight() } ) .testTag(ContainerTag), horizontalArrangement = horizontalArrangement, verticalAlignment = verticalAlignment, reverseLayout = reverseLayout, contentPadding = PaddingValues(start = startPadding, end = endPadding), content = content ) } } @Composable private fun LazyItemScope.Item( tag: Int, size: Dp = itemSizeDp, crossAxisSize: Dp = size, animSpec: FiniteAnimationSpec<IntOffset>? = AnimSpec ) { Box( Modifier .then( if (isVertical) { Modifier.requiredHeight(size).requiredWidth(crossAxisSize) } else { Modifier.requiredWidth(size).requiredHeight(crossAxisSize) } ) .testTag(tag.toString()) .then( if (animSpec != null) { Modifier.animateItemPlacement(animSpec) } else { Modifier } ) ) } private fun SemanticsNodeInteraction.assertMainAxisSizeIsEqualTo( expected: Dp ): SemanticsNodeInteraction { return if (isVertical) assertHeightIsEqualTo(expected) else assertWidthIsEqualTo(expected) } companion object { @JvmStatic @Parameterized.Parameters(name = "{0}") fun params() = arrayOf( Config(isVertical = true, reverseLayout = false), Config(isVertical = false, reverseLayout = false), Config(isVertical = true, reverseLayout = true), Config(isVertical = false, reverseLayout = true), ) class Config( val isVertical: Boolean, val reverseLayout: Boolean ) { override fun toString() = (if (isVertical) "LazyColumn" else "LazyRow") + (if (reverseLayout) "(reverse)" else "") } } } private val FrameDuration = 16L private val Duration = 400L private val AnimSpec = tween<IntOffset>(Duration.toInt(), easing = LinearEasing) private val ContainerTag = "container" private enum class CrossAxisAlignment { Start, End, Center }
apache-2.0
3933cf184660b16ac8445f7dcc7d07e8
32.209918
99
0.500828
5.092718
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/search/KotlinQueryParticipant.kt
1
14664
/******************************************************************************* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.jetbrains.kotlin.ui.search import org.eclipse.core.resources.IFile import org.eclipse.core.resources.IResource import org.eclipse.core.runtime.CoreException import org.eclipse.core.runtime.IProgressMonitor import org.eclipse.jdt.core.IJavaElement import org.eclipse.jdt.ui.search.ElementQuerySpecification import org.eclipse.jdt.ui.search.IMatchPresentation import org.eclipse.jdt.ui.search.IQueryParticipant import org.eclipse.jdt.ui.search.ISearchRequestor import org.eclipse.jdt.ui.search.QuerySpecification import org.eclipse.search.internal.ui.text.FileSearchQuery import org.eclipse.search.ui.ISearchResult import org.eclipse.search.ui.text.FileTextSearchScope import org.eclipse.core.resources.ResourcesPlugin import org.jetbrains.kotlin.core.builder.KotlinPsiManager import com.intellij.psi.PsiElement import org.eclipse.search.internal.ui.text.FileSearchResult import org.jetbrains.kotlin.eclipse.ui.utils.findElementByDocumentOffset import org.jetbrains.kotlin.eclipse.ui.utils.EditorUtil import org.jetbrains.kotlin.core.references.getReferenceExpression import org.jetbrains.kotlin.core.references.resolveToSourceDeclaration import java.util.ArrayList import org.jetbrains.kotlin.core.references.KotlinReference import org.jetbrains.kotlin.core.model.KotlinAnalysisProjectCache import org.eclipse.search.ui.text.Match import org.eclipse.jface.viewers.ILabelProvider import org.jetbrains.kotlin.ui.editors.outline.PsiLabelProvider import org.eclipse.jface.viewers.LabelProvider import org.jetbrains.kotlin.psi.KtElement import org.eclipse.jdt.internal.core.JavaModel import org.eclipse.core.resources.IProject import org.jetbrains.kotlin.core.references.createReferences import org.eclipse.core.runtime.IAdaptable import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.core.asJava.getDeclaringTypeFqName import org.eclipse.jdt.core.IJavaProject import org.eclipse.jdt.core.IMethod import org.eclipse.jdt.core.IMember import org.eclipse.jdt.core.search.SearchPattern import org.eclipse.jdt.core.IType import org.eclipse.jdt.core.IField import org.eclipse.jdt.core.JavaCore import org.jetbrains.kotlin.resolve.source.KotlinSourceElement import org.jetbrains.kotlin.descriptors.SourceElement import org.jetbrains.kotlin.core.model.sourceElementsToLightElements import org.eclipse.jface.util.SafeRunnable import org.eclipse.core.runtime.ISafeRunnable import org.jetbrains.kotlin.core.log.KotlinLogger import org.eclipse.jdt.internal.ui.search.JavaSearchQuery import org.eclipse.jdt.internal.ui.search.AbstractJavaSearchResult import org.jetbrains.kotlin.psi.psiUtil.isImportDirectiveExpression import org.jetbrains.kotlin.core.model.KotlinAnalysisFileCache import org.jetbrains.kotlin.ui.commands.findReferences.KotlinScopedQuerySpecification import org.eclipse.jdt.core.search.IJavaSearchScope import org.jetbrains.kotlin.ui.commands.findReferences.KotlinJavaQuerySpecification import org.jetbrains.kotlin.ui.commands.findReferences.KotlinOnlyQuerySpecification import org.jetbrains.kotlin.ui.commands.findReferences.KotlinAndJavaSearchable import org.jetbrains.kotlin.ui.commands.findReferences.KotlinScoped import org.jetbrains.kotlin.psi.KtConstructor import org.eclipse.search2.internal.ui.text2.DefaultTextSearchQueryProvider import org.eclipse.search.ui.text.TextSearchQueryProvider.TextSearchInput public class KotlinQueryParticipant : IQueryParticipant { override public fun search(requestor: ISearchRequestor, querySpecification: QuerySpecification, monitor: IProgressMonitor?) { SafeRunnable.run(object : ISafeRunnable { override fun run() { val searchElements = getSearchElements(querySpecification) if (searchElements.isEmpty()) return if (querySpecification is KotlinAndJavaSearchable) { runCompositeSearch(searchElements, requestor, querySpecification, monitor) return } val kotlinFiles = getKotlinFilesByScope(querySpecification) if (kotlinFiles.isEmpty()) return if (searchElements.size > 1) { KotlinLogger.logWarning("There are more than one elements to search: $searchElements") } // We assume that there is only one search element, it could be IJavaElement or KtElement val searchElement = searchElements.first() val searchResult = searchTextOccurrences(searchElement, kotlinFiles) if (searchResult == null) return val elements = obtainElements(searchResult as FileSearchResult, kotlinFiles) val matchedReferences = resolveElementsAndMatch(elements, searchElement, querySpecification) matchedReferences.forEach { requestor.reportMatch(KotlinElementMatch(it)) } } override fun handleException(exception: Throwable) { KotlinLogger.logError(exception) } }) } override public fun estimateTicks(specification: QuerySpecification): Int = 500 override public fun getUIParticipant() = KotlinReferenceMatchPresentation() private fun runCompositeSearch(elements: List<SearchElement>, requestor: ISearchRequestor, originSpecification: QuerySpecification, monitor: IProgressMonitor?) { fun reportSearchResults(result: AbstractJavaSearchResult) { for (searchElement in result.getElements()) { result.getMatches(searchElement).forEach { requestor.reportMatch(it) } } } val specifications = elements.map { searchElement -> when (searchElement) { is SearchElement.JavaSearchElement -> ElementQuerySpecification( searchElement.javaElement, originSpecification.getLimitTo(), originSpecification.getScope(), originSpecification.getScopeDescription()) is SearchElement.KotlinSearchElement -> KotlinOnlyQuerySpecification( searchElement.kotlinElement, originSpecification.getFilesInScope(), originSpecification.getLimitTo(), originSpecification.getScopeDescription()) } } if (originSpecification is KotlinScoped) { for (specification in specifications) { KotlinQueryParticipant().search({ requestor.reportMatch(it) }, specification, monitor) } } else { for (specification in specifications) { val searchQuery = JavaSearchQuery(specification) searchQuery.run(monitor) reportSearchResults(searchQuery.getSearchResult() as AbstractJavaSearchResult) } } } sealed class SearchElement private constructor() { abstract fun getSearchText(): String? class JavaSearchElement(val javaElement: IJavaElement) : SearchElement() { override fun getSearchText(): String = javaElement.getElementName() } class KotlinSearchElement(val kotlinElement: KtElement) : SearchElement() { override fun getSearchText(): String? = kotlinElement.getName() } } private fun getSearchElements(querySpecification: QuerySpecification): List<SearchElement> { fun obtainSearchElements(sourceElements: List<SourceElement>): List<SearchElement> { val (javaElements, kotlinElements) = getJavaAndKotlinElements(sourceElements) return javaElements.map { SearchElement.JavaSearchElement(it) } + kotlinElements.map { SearchElement.KotlinSearchElement(it) } } return when (querySpecification) { is ElementQuerySpecification -> listOf(SearchElement.JavaSearchElement(querySpecification.getElement())) is KotlinOnlyQuerySpecification -> listOf(SearchElement.KotlinSearchElement(querySpecification.kotlinElement)) is KotlinAndJavaSearchable -> obtainSearchElements(querySpecification.sourceElements) else -> emptyList() } } private fun searchTextOccurrences(searchElement: SearchElement, filesScope: List<IFile>): ISearchResult? { val searchText = searchElement.getSearchText() if (searchText == null) return null val scope = FileTextSearchScope.newSearchScope(filesScope.toTypedArray(), null as Array<String?>?, false) val query = DefaultTextSearchQueryProvider().createQuery(object : TextSearchInput() { override fun isWholeWordSearch(): Boolean = true override fun getSearchText(): String = searchText override fun isCaseSensitiveSearch(): Boolean = true override fun isRegExSearch(): Boolean = false override fun getScope(): FileTextSearchScope = scope }) query.run(null) return query.getSearchResult() } private fun resolveElementsAndMatch(elements: List<KtElement>, searchElement: SearchElement, querySpecification: QuerySpecification): List<KtElement> { val beforeResolveFilters = getBeforeResolveFilters(querySpecification) val afterResolveFilters = getAfterResolveFilters() // This is important for optimization: // we will consequentially cache files one by one which are containing these references val sortedByFileNameElements = elements.sortedBy { it.getContainingKtFile().getName() } return sortedByFileNameElements.filter { element -> val beforeResolveCheck = beforeResolveFilters.all { it.isApplicable(element) } if (!beforeResolveCheck) return@filter false val sourceElements = element.resolveToSourceDeclaration() if (sourceElements.isEmpty()) return@filter false val additionalElements = getContainingClassOrObjectForConstructor(sourceElements) return@filter afterResolveFilters.all { it.isApplicable(sourceElements, searchElement) } || afterResolveFilters.all { it.isApplicable(additionalElements, searchElement) } } } private fun obtainElements(searchResult: FileSearchResult, files: List<IFile>): List<KtElement> { val elements = ArrayList<KtElement>() for (file in files) { val matches = searchResult.getMatches(file) val jetFile = KotlinPsiManager.getParsedFile(file) val document = EditorUtil.getDocument(file) matches .map { val element = jetFile.findElementByDocumentOffset(it.getOffset(), document) element?.let { PsiTreeUtil.getNonStrictParentOfType(it, KtElement::class.java) } } .filterNotNullTo(elements) } return elements } private fun getKotlinFilesByScope(querySpecification: QuerySpecification): List<IFile> { return when (querySpecification) { is ElementQuerySpecification, is KotlinJavaQuerySpecification -> querySpecification.getScope().getKotlinFiles() is KotlinScoped -> querySpecification.searchScope else -> emptyList() } } } fun getContainingClassOrObjectForConstructor(sourceElements: List<SourceElement>): List<SourceElement> { return sourceElements.mapNotNull { if (it is KotlinSourceElement) { val psi = it.psi if (psi is KtConstructor<*>) { return@mapNotNull KotlinSourceElement(psi.getContainingClassOrObject()) } } null } } fun getJavaAndKotlinElements(sourceElements: List<SourceElement>): Pair<List<IJavaElement>, List<KtElement>> { val javaElements = sourceElementsToLightElements(sourceElements) // Filter out Kotlin elements which have light elements because Javas search will call KotlinQueryParticipant // to look up for these elements val kotlinElements = sourceElementsToKotlinElements(sourceElements).filterNot { kotlinElement -> javaElements.any { it.getElementName() == kotlinElement.getName() } } return Pair(javaElements, kotlinElements) } private fun sourceElementsToKotlinElements(sourceElements: List<SourceElement>): List<KtElement> { return sourceElements .filterIsInstance(KotlinSourceElement::class.java) .map { it.psi } } fun IJavaSearchScope.getKotlinFiles(): List<IFile> { return enclosingProjectsAndJars() .map { JavaModel.getTarget(it, true) } .filterIsInstance(IProject::class.java) .flatMap { KotlinPsiManager.getFilesByProject(it) } } fun QuerySpecification.getFilesInScope(): List<IFile> { return when (this) { is KotlinScoped -> this.searchScope else -> this.scope.getKotlinFiles() } } public class KotlinElementMatch(val jetElement: KtElement) : Match(KotlinAdaptableElement(jetElement), jetElement.getTextOffset(), jetElement.getTextOffset()) class KotlinAdaptableElement(val jetElement: KtElement): IAdaptable { @Suppress("UNCHECKED_CAST") override fun <T> getAdapter(adapter: Class<T>?): T? { return when { IResource::class.java == adapter -> KotlinPsiManager.getEclipseFile(jetElement.getContainingKtFile()) as T else -> null } } }
apache-2.0
23c7babc2ada0b1bafa86e8617d1b3d8
44.685358
136
0.685215
5.179795
false
false
false
false
yuncheolkim/gitmt
src/main/kotlin/com/joyouskim/http/Filter.kt
1
9962
package com.joyouskim.http import com.joyouskim.git.* import io.netty.handler.codec.http.HttpResponseStatus import io.netty.handler.codec.http.HttpResponseStatus.* import io.vertx.kotlin.lang.contentLength import io.vertx.kotlin.lang.setStatus import org.eclipse.jgit.errors.RepositoryNotFoundException import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.lib.Repository import org.eclipse.jgit.transport.PacketLineOut import org.eclipse.jgit.transport.RefAdvertiser import org.eclipse.jgit.transport.ServiceMayNotContinueException import org.eclipse.jgit.transport.resolver.* import sun.jvm.hotspot.debugger.posix.elf.ELFSectionHeader import java.io.File import java.io.FileNotFoundException import java.util.* import javax.naming.OperationNotSupportedException /** * Created by jinyunzhe on 16/4/5. */ interface Filter { fun doFilter(httpRequest: HttpRequest, httpResponse: HttpResponse, filterChain: FilterChain) fun init() } interface FilterChain { fun doFilterChain(httpRequest: HttpRequest, httpResponse: HttpResponse) } open class BaseFilter : Filter { override fun init() { } @Volatile var urlPipeLine: Array<UrlPipeLine>? = null val bindingList: MutableList<ActionBindImpl> = arrayListOf() override fun doFilter(httpRequest: HttpRequest, httpResponse: HttpResponse, filterChain: FilterChain) { val p = find(httpRequest) if (p != null) { p.service(httpRequest, httpResponse) } else { filterChain.doFilterChain(httpRequest, httpResponse) } } fun serve(path: String): ActionBind { if (path.startsWith("*")) { return register0(SuffixActionBind(path.substring(1))) } throw OperationNotSupportedException() } fun serveRegx(regx: String): ActionBind { return register0(RegxActionBind(regx)) } private fun register0(bind: ActionBindImpl): ActionBind { synchronized(bindingList, { if (urlPipeLine != null) { throw IllegalStateException("already init") } bindingList.add(bind) }) return register(bind) } open fun register(bind: ActionBind): ActionBind { return bind } fun find(httpRequest: HttpRequest): UrlPipeLine? { return getPipeLine().find { it.match(httpRequest) } } private fun getPipeLine(): Array<UrlPipeLine> { var array = urlPipeLine if (array == null) { synchronized(bindingList, { array = urlPipeLine if (array == null) { array = createPipeLine() urlPipeLine = array } }) } return array!! } private fun createPipeLine(): Array<UrlPipeLine> { val pipeLine: MutableList<UrlPipeLine> = arrayListOf() bindingList.forEachIndexed { index, actionBindImpl -> pipeLine.add(actionBindImpl.create()) } val identity = newIdentitySet() pipeLine.forEach { it!!.init(identity) } return pipeLine.toTypedArray() } private fun newIdent(): MutableSet<Any> { val m: MutableMap<Any, Any> = IdentityHashMap<Any, Any>(); return object : AbstractSet<Any>() { override val size: Int get() = m.size override fun iterator(): MutableIterator<Any> { return m.keys.iterator() } override fun add(element: Any?): Boolean { return m.put(element!!, element) == null } override fun contains(element: Any?): Boolean { return m.keys.contains(element) } } } private fun newIdentitySet(): MutableSet<Any> { return hashSetOf() } } class GitFilter : BaseFilter() { lateinit var resolver: RepositoryResolver<HttpRequest> @Volatile var initialized = false var uploadFactory: UploadPackFactory<HttpRequest> = DefaultUploadPackFy() var receiveFactory: ReceivePackFactory<HttpRequest> = DefaultReceivePackFy() val uploadFilter: MutableList<Filter> = arrayListOf() val reciveFilter: MutableList<Filter> = arrayListOf() override fun init() { val root = File("gr") if (!root.exists()) { throw FileNotFoundException() } resolver = FileResolver<HttpRequest>(root, true) val uploadBind = serve("*/$UPLOAD_PACK") uploadBind.pass(UploadAction.Factory(uploadFactory)) uploadFilter.forEach { uploadBind.pass(it) } uploadBind.bind(UploadAction()) val receiveBind = serve("*/$RECEIVE_PACK") receiveBind.pass(ReceiveAction.Factory(receiveFactory)) reciveFilter.forEach { receiveBind.pass(it) } receiveBind.bind(ReceiveAction()) val InfoRefsBind = serve("*/${Constants.INFO_REFS}") InfoRefsBind.pass(UploadAction.Info(uploadFactory, uploadFilter.toTypedArray())) InfoRefsBind.pass(ReceiveAction.Info(receiveFactory, reciveFilter.toTypedArray())) InfoRefsBind.bind(ErrorAction(NOT_ACCEPTABLE.code())) } override fun register(bind: ActionBind): ActionBind { if (resolver == null) { throw NullPointerException() } bind.pass(NoCacheFilter()) bind.pass(RepositoryFilter(resolver)) return bind } } abstract class SmartServiceInfoRefs(open val svc: String, open val filters: Array<Filter>) : Filter { override fun doFilter(httpRequest: HttpRequest, httpResponse: HttpResponse, filterChain: FilterChain) { if (svc == httpRequest.getParam("service")) { val db = getRepository(httpRequest) try { begin(httpRequest, db) } catch(e: ServiceNotAuthorizedException) { httpResponse.setStatus(UNAUTHORIZED.code(), e.message.toString()) return; } catch(e: ServiceNotEnabledException) { sendError(httpRequest, httpResponse, FORBIDDEN.code(), e.message) return; } try { if (filters.size == 0) service(httpRequest, httpResponse) else Chain().doFilterChain(httpRequest, httpResponse) } finally { httpRequest.formAttributes().remove(ATTRIBUTE_HANDLER) } } else { filterChain.doFilterChain(httpRequest, httpResponse) } } private fun service(httpRequest: HttpRequest, httpResponse: HttpResponse) { try { val buf = SmartOutputStream(httpRequest,httpResponse,true) httpResponse.setContentType(infoRefsResultType(svc)) val out = PacketLineOut(buf) val s = "# service=" + svc + "\n" httpResponse.contentLength = s.length.toLong() out.writeString(s) out.end() advertise(httpRequest, RefAdvertiser.PacketLineOutRefAdvertiser(out)) buf.close() } catch(e: Exception) { httpResponse.statusCode = 505 } } protected abstract fun advertise(httpRequest: HttpRequest, packetLineOutRefAdvertiser: RefAdvertiser.PacketLineOutRefAdvertiser) protected abstract fun begin(httpRequest: HttpRequest, db: Repository) private inner class Chain : FilterChain { var filterIndex = 0 override fun doFilterChain(httpRequest: HttpRequest, httpResponse: HttpResponse) { if (filterIndex < filters.size) { filters[filterIndex++].doFilter(httpRequest, httpResponse, this) } else { service(httpRequest, httpResponse) } } } } class NoCacheFilter : Filter { override fun doFilter(httpRequest: HttpRequest, httpResponse: HttpResponse, filterChain: FilterChain) { httpResponse.putHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT") httpResponse.putHeader("Pragma", "no-cache"); val nocache = "no-cache, max-age=0, must-revalidate"; httpResponse.putHeader("Cache-Control", "no-cache, max-age=0, must-revalidate"); filterChain.doFilterChain(httpRequest, httpResponse) } override fun init() { } } class RepositoryFilter(val resolver: RepositoryResolver<HttpRequest>) : Filter { override fun doFilter(httpRequest: HttpRequest, httpResponse: HttpResponse, filterChain: FilterChain) { if (httpRequest.attMap[ATTRIBUTE_REPOSITORY] != null) { sendError(httpRequest, httpResponse, INTERNAL_SERVER_ERROR.code()) return } var name = httpRequest.gitPath() while (name != null && name.length > 0 && name[0] == '/' ) { name = name.substring(1) } if(name == null || name.length == 0){ sendError(httpRequest, httpResponse, NOT_FOUND.code()) return; } println("name:$name") var db:Repository try { db = resolver.open(httpRequest, name) } catch(e: RepositoryNotFoundException) { sendError(httpRequest, httpResponse, NOT_FOUND.code()) return } catch(e: ServiceNotEnabledException){ sendError(httpRequest,httpResponse,FORBIDDEN.code(),e.message) return }catch(e:ServiceNotAuthorizedException){ sendError(httpRequest,httpResponse,UNAUTHORIZED.code(),e.message) return }catch(e:ServiceMayNotContinueException){ sendError(httpRequest,httpResponse,FORBIDDEN.code(),e.message) return } try { httpRequest.attMap[ATTRIBUTE_REPOSITORY] = db filterChain.doFilterChain(httpRequest,httpResponse) } finally { httpRequest.attMap.remove(ATTRIBUTE_REPOSITORY) db.close() } } override fun init() { } }
mit
4561f7cbc2ef66b137ee212e2f078539
31.347403
132
0.62628
4.701274
false
false
false
false
C6H2Cl2/SolidXp
src/main/java/c6h2cl2/solidxp/gui/GuiXpCollector.kt
1
2132
package c6h2cl2.solidxp.gui import c6h2cl2.solidxp.MOD_ID import c6h2cl2.solidxp.PacketHandler import c6h2cl2.solidxp.network.CMessageUpdateTileEntity import c6h2cl2.solidxp.tileentity.getXpValue import net.minecraft.client.gui.GuiButton import net.minecraft.client.gui.inventory.GuiContainer import net.minecraft.entity.player.InventoryPlayer import net.minecraft.util.ResourceLocation import net.minecraft.util.math.BlockPos import net.minecraft.util.text.TextComponentTranslation import net.minecraft.world.World import java.awt.Color /** * @author C6H2Cl2 */ class GuiXpCollector(world: World, pos: BlockPos, playerInventory: InventoryPlayer) : GuiContainer(ContainerXpCollector(world, pos, playerInventory)) { val tile = (inventorySlots as ContainerXpCollector).tile override fun drawGuiContainerBackgroundLayer(partialTicks: Float, mouseX: Int, mouseY: Int) { mc.renderEngine.bindTexture(ResourceLocation(MOD_ID, "textures/gui/xp_collector.png")) val j = (width - xSize) / 2 val k = (height - ySize) / 2 drawTexturedModalRect(j, k - 10, 0, 0, xSize, ySize) } override fun drawGuiContainerForegroundLayer(mouseX: Int, mouseY: Int) { val s = TextComponentTranslation("$MOD_ID.gui.xp_infuser").formattedText fontRendererObj.drawString(s, xSize / 2 - fontRendererObj.getStringWidth(s) / 2, 0, Color.BLACK.rgb) val xp = getXpValue(tile.xpStorage.xpTier).toString() fontRendererObj.drawString(xp, 138 - (fontRendererObj.getStringWidth(xp) / 2.0f), 32.0f, Color.BLACK.rgb, false) } override fun initGui() { super.initGui() var s = "+" addButton(GuiButton(0, 255 - (fontRendererObj.getStringWidth(s) / 2), 40, 20, 20, s)) s = "-" addButton(GuiButton(1, 255 - (fontRendererObj.getStringWidth(s) / 2), 85, 20, 20, s)) } override fun actionPerformed(button: GuiButton) { when (button.id) { 0 -> tile.xpStorage.xpTier++ 1 -> tile.xpStorage.xpTier-- } PacketHandler.INSTANCE.sendToServer(CMessageUpdateTileEntity(tile.updateTag, tile.pos)) } }
mpl-2.0
af4d3d4c4658f81530db1093caf5eacb
40.823529
151
0.712477
3.595278
false
false
false
false
esofthead/mycollab
mycollab-web/src/main/java/com/mycollab/module/project/ui/format/TaskHistoryFieldFormat.kt
3
2602
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.project.ui.format import com.mycollab.common.i18n.GenericI18Enum import com.mycollab.module.project.ProjectLinkBuilder import com.mycollab.module.project.ProjectTypeConstants import com.mycollab.module.project.service.TaskService import com.mycollab.module.user.domain.SimpleUser import com.mycollab.spring.AppContextUtil import com.mycollab.vaadin.AppUI import com.mycollab.vaadin.UserUIContext import com.mycollab.vaadin.ui.formatter.HistoryFieldFormat import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory /** * @author MyCollab Ltd * @since 5.2.9 */ class TaskHistoryFieldFormat : HistoryFieldFormat { override fun toString(value: String): String = toString(UserUIContext.getUser(), value, true, UserUIContext.getMessage(GenericI18Enum.FORM_EMPTY)) override fun toString(currentViewUser:SimpleUser, value: String, displayAsHtml: Boolean, msgIfBlank: String): String { if (StringUtils.isBlank(value)) { return msgIfBlank } try { val taskId = Integer.parseInt(value) val taskService = AppContextUtil.getSpringBean(TaskService::class.java) val task = taskService.findById(taskId, AppUI.accountId) return if (task != null) { if (displayAsHtml) { ProjectLinkBuilder.generateProjectItemHtmlLinkAndTooltip(task.projectShortname!!, task.projectid!!, task.name, ProjectTypeConstants.TASK, task.id!!.toString() + "") } else { task.name } } else { "Deleted task" } } catch (e: Exception) { LOG.error("Error", e) } return value } companion object { private val LOG = LoggerFactory.getLogger(TaskHistoryFieldFormat::class.java) } }
agpl-3.0
b569aff5b548bf9f4f3b5b8dcdefd9bc
36.157143
122
0.687043
4.5
false
false
false
false
PublicXiaoWu/XiaoWuMySelf
app/src/main/java/com/xiaowu/myself/utils/NetworkUtils.kt
1
1544
package com.xiaowu.myself.utils import android.annotation.SuppressLint import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo /** * Created by lvruheng on 2017/7/2. */ object NetworkUtils{ @SuppressLint("MissingPermission") fun isNetConneted(context: Context):Boolean{ val connectManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo : NetworkInfo?= connectManager.activeNetworkInfo if(networkInfo==null){ return false }else{ return networkInfo.isAvailable&& networkInfo.isConnected } } @SuppressLint("MissingPermission") fun isNetworkConnected(context: Context, typeMoblie : Int): Boolean{ if(!isNetConneted(context)){ return false } val connectManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo : NetworkInfo = connectManager.getNetworkInfo(typeMoblie) return if(networkInfo==null){ false }else{ networkInfo.isConnected && networkInfo.isAvailable } } fun isPhoneNetConnected(context: Context): Boolean { val typeMobile = ConnectivityManager.TYPE_MOBILE return isNetworkConnected(context,typeMobile) } fun isWifiNetConnected(context: Context) : Boolean{ val typeMobile = ConnectivityManager.TYPE_WIFI return isNetworkConnected(context,typeMobile) } }
apache-2.0
f8f07c3000f9731b569ddcd8b5376c8e
28.711538
107
0.697539
4.996764
false
false
false
false
elect86/jAssimp
src/main/kotlin/assimp/metadata.kt
2
1685
package assimp import assimp.AiMetadataType as Mt /** Enum used to distinguish data types */ enum class AiMetadataType { BOOL, INT32, UINT64, FLOAT, DOUBLE, AISTRING, AIVECTOR3D } /** * Metadata entry * * The type field uniquely identifies the underlying type of the data field */ class AiMetadataEntry<T>(val type: Mt, val data: T) { constructor (d: T) : this(d!!.type, d) } /** * Container for holding metadata. * * Metadata is a key-value store using string keys and values. */ class AiMetadata( /** Arrays of keys, may not be NULL. Entries in this array may not be NULL as well. * Arrays of values, may not be NULL. Entries in this array may be NULL if the corresponding property key has no * assigned value. => JVM map */ val map: MutableMap<String, AiMetadataEntry<*>?> = mutableMapOf() ) { /** Length of the mKeys and mValues arrays, respectively */ val numProperties get() = map.size operator fun <T> set(key: String, value: T) = when { // Ensure that we have a valid key. key.isEmpty() -> false else -> { // Set metadata key map[key] = AiMetadataEntry(value) true } } fun clear() = map.clear() fun isEmpty() = map.isEmpty() fun isNotEmpty() = map.isNotEmpty() operator fun <T> get(key: String) = map[key]?.data as? T } private val Any.type get() = when (this) { is Boolean -> Mt.BOOL is Int -> Mt.INT32 is Long -> Mt.UINT64 is Float -> Mt.FLOAT is Double -> Mt.DOUBLE is String -> Mt.AISTRING is AiVector3D -> Mt.AIVECTOR3D else -> throw Exception() }
mit
aa32aac69da17d04bd82fce3d12ef30b
28.068966
121
0.611276
3.744444
false
false
false
false
dhleong/ideavim
src/com/maddyhome/idea/vim/group/visual/VisualGroup.kt
1
12117
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.group.visual import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.CaretVisualAttributes import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.VisualPosition import com.intellij.openapi.editor.colors.EditorColors import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.command.CommandState import com.maddyhome.idea.vim.group.ChangeGroup import com.maddyhome.idea.vim.group.MotionGroup import com.maddyhome.idea.vim.helper.EditorHelper import com.maddyhome.idea.vim.helper.inBlockSubMode import com.maddyhome.idea.vim.helper.inSelectMode import com.maddyhome.idea.vim.helper.inVisualMode import com.maddyhome.idea.vim.helper.isEndAllowed import com.maddyhome.idea.vim.helper.mode import com.maddyhome.idea.vim.helper.sort import com.maddyhome.idea.vim.helper.subMode import com.maddyhome.idea.vim.helper.vimLastColumn import com.maddyhome.idea.vim.helper.vimSelectionStart /** * @author Alex Plate */ /** * Set selection for caret * This method doesn't change CommandState and operates only with caret and it's properties * if [moveCaretToSelectionEnd] is true, caret movement to [end] will be performed */ fun Caret.vimSetSelection(start: Int, end: Int = start, moveCaretToSelectionEnd: Boolean = false) { vimSelectionStart = start setVisualSelection(start, end, this) if (moveCaretToSelectionEnd && !editor.inBlockSubMode) moveToOffset(end) } /** * Move selection end to current caret position * This method is created only for Character and Line mode * @see vimMoveBlockSelectionToOffset for blockwise selection */ fun Caret.vimMoveSelectionToCaret() { if (!editor.inVisualMode && !editor.inSelectMode) throw RuntimeException("Attempt to extent selection in non-visual mode") if (editor.inBlockSubMode) throw RuntimeException("Move caret with [vimMoveBlockSelectionToOffset]") val startOffsetMark = vimSelectionStart setVisualSelection(startOffsetMark, offset, this) } /** * Move selection end to current primary caret position * This method is created only for block mode * @see vimMoveSelectionToCaret for character and line selection */ fun vimMoveBlockSelectionToOffset(editor: Editor, offset: Int) { val primaryCaret = editor.caretModel.primaryCaret val startOffsetMark = primaryCaret.vimSelectionStart setVisualSelection(startOffsetMark, offset, primaryCaret) } /** * Update selection according to new CommandState * This method should be used for switching from character to line wise selection and so on */ fun Caret.vimUpdateEditorSelection() { val startOffsetMark = vimSelectionStart setVisualSelection(startOffsetMark, offset, this) } /** * This works almost like [Caret.getLeadSelectionOffset], but vim-specific */ val Caret.vimLeadSelectionOffset: Int get() { val caretOffset = offset if (hasSelection()) { val selectionAdj = VimPlugin.getVisualMotion().selectionAdj if (caretOffset != selectionStart && caretOffset != selectionEnd) { // Try to check if current selection is tweaked by fold region. val foldingModel = editor.foldingModel val foldRegion = foldingModel.getCollapsedRegionAtOffset(caretOffset) if (foldRegion != null) { if (foldRegion.startOffset == selectionStart) { return (selectionEnd - selectionAdj).coerceAtLeast(0) } else if (foldRegion.endOffset == selectionEnd) { return selectionStart } } } return if (editor.subMode == CommandState.SubMode.VISUAL_LINE) { val selectionStartLine = editor.offsetToLogicalPosition(selectionStart).line val caretLine = editor.offsetToLogicalPosition(this.offset).line if (caretLine == selectionStartLine) { val column = editor.offsetToLogicalPosition(selectionEnd).column if (column == 0) (selectionEnd - 1).coerceAtLeast(0) else selectionEnd } else selectionStart } else if (editor.inBlockSubMode) { val selections = editor.caretModel.allCarets.map { it.selectionStart to it.selectionEnd }.sortedBy { it.first } val pCaret = editor.caretModel.primaryCaret when { pCaret.offset == selections.first().first -> (selections.last().second - selectionAdj).coerceAtLeast(0) pCaret.offset == selections.first().second -> selections.last().first pCaret.offset == selections.last().first -> (selections.first().second - selectionAdj).coerceAtLeast(0) pCaret.offset == selections.last().second -> selections.first().first else -> selections.first().first } } else { if (caretOffset == selectionStart) (selectionEnd - selectionAdj).coerceAtLeast(0) else selectionStart } } return caretOffset } /** * Update caret's colour according to the current state * * Secondary carets became invisible colour in visual block mode */ fun updateCaretState(editor: Editor) { // Update colour if (editor.inBlockSubMode) { editor.caretModel.allCarets.forEach { if (it != editor.caretModel.primaryCaret) { // Set background color for non-primary carets as selection background color // to make them invisible val color = editor.colorsScheme.getColor(EditorColors.SELECTION_BACKGROUND_COLOR) val visualAttributes = it.visualAttributes it.visualAttributes = CaretVisualAttributes(color, visualAttributes.weight) } } } else { editor.caretModel.allCarets.forEach { it.visualAttributes = CaretVisualAttributes.DEFAULT } } // Update shape when (editor.mode) { CommandState.Mode.COMMAND, CommandState.Mode.VISUAL, CommandState.Mode.REPLACE -> ChangeGroup.resetCaret(editor, false) CommandState.Mode.SELECT, CommandState.Mode.INSERT -> ChangeGroup.resetCaret(editor, true) CommandState.Mode.REPEAT, CommandState.Mode.EX_ENTRY -> Unit } } /** * Convert vim's selection start and end to corresponding native selection. * * Adds caret adjustment or extends to line start / end in case of linewise selection */ fun toNativeSelection(editor: Editor, start: Int, end: Int, mode: CommandState.Mode, subMode: CommandState.SubMode): Pair<Int, Int> = when (subMode) { CommandState.SubMode.VISUAL_LINE -> { val (nativeStart, nativeEnd) = sort(start, end) val lineStart = EditorHelper.getLineStartForOffset(editor, nativeStart) // Extend to \n char of line to fill full line with selection val lineEnd = (EditorHelper.getLineEndForOffset(editor, nativeEnd) + 1).coerceAtMost(EditorHelper.getFileSize(editor, true)) lineStart to lineEnd } CommandState.SubMode.VISUAL_CHARACTER -> { val (nativeStart, nativeEnd) = sort(start, end) val lineEnd = EditorHelper.getLineEndForOffset(editor, nativeEnd) val adj = if (VimPlugin.getVisualMotion().exclusiveSelection || nativeEnd == lineEnd || mode == CommandState.Mode.SELECT) 0 else 1 val adjEnd = (nativeEnd + adj).coerceAtMost(EditorHelper.getFileSize(editor)) nativeStart to adjEnd } CommandState.SubMode.VISUAL_BLOCK -> { var blockStart = editor.offsetToLogicalPosition(start) var blockEnd = editor.offsetToLogicalPosition(end) if (!VimPlugin.getVisualMotion().exclusiveSelection && mode != CommandState.Mode.SELECT) { if (blockStart.column > blockEnd.column) { blockStart = LogicalPosition(blockStart.line, blockStart.column + 1) } else { blockEnd = LogicalPosition(blockEnd.line, blockEnd.column + 1) } } editor.logicalPositionToOffset(blockStart) to editor.logicalPositionToOffset(blockEnd) } else -> sort(start, end) } fun moveCaretOneCharLeftFromSelectionEnd(editor: Editor) { if (!editor.inVisualMode) { if (!editor.mode.isEndAllowed) { editor.caretModel.allCarets.forEach { caret -> val lineEnd = EditorHelper.getLineEndForOffset(editor, caret.offset) val lineStart = EditorHelper.getLineStartForOffset(editor, caret.offset) if (caret.offset == lineEnd && lineEnd != lineStart) caret.moveToOffset(caret.offset - 1) } } return } editor.caretModel.allCarets.forEach { caret -> if (caret.hasSelection() && caret.selectionEnd == caret.offset) { if (caret.selectionEnd <= 0) return@forEach if (EditorHelper.getLineStartForOffset(editor, caret.selectionEnd - 1) != caret.selectionEnd - 1 && caret.selectionEnd > 1 && editor.document.text[caret.selectionEnd - 1] == '\n') { caret.moveToOffset(caret.selectionEnd - 2) } else { caret.moveToOffset(caret.selectionEnd - 1) } } } } private fun setVisualSelection(selectionStart: Int, selectionEnd: Int, caret: Caret) { val (start, end) = if (selectionStart > selectionEnd) selectionEnd to selectionStart else selectionStart to selectionEnd val editor = caret.editor val subMode = editor.subMode val mode = editor.mode when (subMode) { CommandState.SubMode.VISUAL_LINE, CommandState.SubMode.VISUAL_CHARACTER -> { val (nativeStart, nativeEnd) = toNativeSelection(editor, start, end, mode, subMode) caret.vimSetSystemSelectionSilently(nativeStart, nativeEnd) } CommandState.SubMode.VISUAL_BLOCK -> { editor.caretModel.removeSecondaryCarets() // Set system selection val (nativeStart, nativeEnd) = toNativeSelection(editor, selectionStart, selectionEnd, mode, subMode) val (blockStart, blockEnd) = editor.offsetToLogicalPosition(nativeStart) to editor.offsetToLogicalPosition(nativeEnd) val lastColumn = editor.caretModel.primaryCaret.vimLastColumn editor.selectionModel.vimSetSystemBlockSelectionSilently(blockStart, blockEnd) for (aCaret in editor.caretModel.allCarets) { if (!aCaret.isValid) continue val line = aCaret.logicalPosition.line val lineEndOffset = EditorHelper.getLineEndOffset(editor, line, true) val lineStartOffset = EditorHelper.getLineStartOffset(editor, line) // Extend selection to line end if it was made with `$` command if (lastColumn >= MotionGroup.LAST_COLUMN) { aCaret.vimSetSystemSelectionSilently(aCaret.selectionStart, lineEndOffset) val newOffset = (lineEndOffset - VimPlugin.getVisualMotion().selectionAdj).coerceAtLeast(lineStartOffset) aCaret.moveToOffset(newOffset) } val visualPosition = editor.offsetToVisualPosition(aCaret.selectionEnd) if (aCaret.offset == aCaret.selectionEnd && visualPosition != aCaret.visualPosition) { // Put right caret position for tab character aCaret.moveToVisualPosition(visualPosition) } if (mode != CommandState.Mode.SELECT && !EditorHelper.isLineEmpty(editor, line, false) && aCaret.offset == aCaret.selectionEnd && aCaret.selectionEnd - 1 >= lineStartOffset && aCaret.selectionEnd - aCaret.selectionStart != 0) { // Move all carets one char left in case if it's on selection end aCaret.moveToVisualPosition(VisualPosition(visualPosition.line, visualPosition.column - 1)) } } editor.caretModel.primaryCaret.moveToOffset(selectionEnd) } else -> Unit } updateCaretState(editor) }
gpl-2.0
47e66c4628509615089f5b9c3e8a41b0
42.430108
136
0.724602
4.512849
false
false
false
false
GKZX-HN/MyGithub
app/src/main/java/com/gkzxhn/mygithub/utils/AppUtils.kt
1
1791
package com.gkzxhn.mygithub.utils import android.content.Context import android.content.pm.PackageManager /** * Created by 方 on 2017/11/1. */ object AppUtils { /** * 获取应用程序名称 */ fun getAppName(context: Context): String? { try { val packageManager = context.getPackageManager() val packageInfo = packageManager.getPackageInfo( context.getPackageName(), 0) val labelRes = packageInfo.applicationInfo.labelRes return context.getResources().getString(labelRes) } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return null } /** * [获取应用程序版本名称信息] * @param context * * * @return 当前应用的版本名称 */ fun getVersionName(context: Context): String? { try { val packageManager = context.getPackageManager() val packageInfo = packageManager.getPackageInfo( context.getPackageName(), 0) return packageInfo.versionName } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return null } /** * [获取应用程序版本名称信息] * @param context * * * @return 当前应用的版本号 */ fun getVersionCode(context: Context): Int? { try { val packageManager = context.getPackageManager() val packageInfo = packageManager.getPackageInfo( context.getPackageName(), 0) return packageInfo.versionCode } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return 0 } }
gpl-3.0
97d23682cb67aafb4ad82aced2cfdab4
23.521739
63
0.578947
5.047761
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/browse/BrowseSourceController.kt
1
7707
package eu.kanade.tachiyomi.ui.browse.source.browse import android.os.Bundle import androidx.activity.compose.BackHandler import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.platform.LocalContext import androidx.core.os.bundleOf import eu.kanade.domain.source.model.Source import eu.kanade.presentation.browse.BrowseSourceScreen import eu.kanade.presentation.browse.components.RemoveMangaDialog import eu.kanade.presentation.components.ChangeCategoryDialog import eu.kanade.presentation.components.DuplicateMangaDialog import eu.kanade.tachiyomi.source.CatalogueSource import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.ui.base.controller.FullComposeController import eu.kanade.tachiyomi.ui.base.controller.pushController import eu.kanade.tachiyomi.ui.browse.source.browse.BrowseSourcePresenter.Dialog import eu.kanade.tachiyomi.ui.category.CategoryController import eu.kanade.tachiyomi.ui.manga.MangaController import eu.kanade.tachiyomi.ui.webview.WebViewActivity import eu.kanade.tachiyomi.util.lang.launchIO open class BrowseSourceController(bundle: Bundle) : FullComposeController<BrowseSourcePresenter>(bundle) { constructor(sourceId: Long, query: String? = null) : this( bundleOf( SOURCE_ID_KEY to sourceId, SEARCH_QUERY_KEY to query, ), ) constructor(source: CatalogueSource, query: String? = null) : this(source.id, query) constructor(source: Source, query: String? = null) : this(source.id, query) /** * Sheet containing filter items. */ protected var filterSheet: SourceFilterSheet? = null override fun createPresenter(): BrowseSourcePresenter { return BrowseSourcePresenter(args.getLong(SOURCE_ID_KEY), args.getString(SEARCH_QUERY_KEY)) } @Composable override fun ComposeContent() { val scope = rememberCoroutineScope() val context = LocalContext.current BrowseSourceScreen( presenter = presenter, navigateUp = ::navigateUp, openFilterSheet = { filterSheet?.show() }, onMangaClick = { router.pushController(MangaController(it.id, true)) }, onMangaLongClick = { manga -> scope.launchIO { val duplicateManga = presenter.getDuplicateLibraryManga(manga) when { manga.favorite -> presenter.dialog = Dialog.RemoveManga(manga) duplicateManga != null -> presenter.dialog = Dialog.AddDuplicateManga(manga, duplicateManga) else -> presenter.addFavorite(manga) } } }, onWebViewClick = f@{ val source = presenter.source as? HttpSource ?: return@f val intent = WebViewActivity.newIntent(context, source.baseUrl, source.id, source.name) context.startActivity(intent) }, incognitoMode = presenter.isIncognitoMode, downloadedOnlyMode = presenter.isDownloadOnly, ) val onDismissRequest = { presenter.dialog = null } when (val dialog = presenter.dialog) { is Dialog.AddDuplicateManga -> { DuplicateMangaDialog( onDismissRequest = onDismissRequest, onConfirm = { presenter.addFavorite(dialog.manga) }, onOpenManga = { router.pushController(MangaController(dialog.duplicate.id)) }, duplicateFrom = presenter.getSourceOrStub(dialog.duplicate), ) } is Dialog.RemoveManga -> { RemoveMangaDialog( onDismissRequest = onDismissRequest, onConfirm = { presenter.changeMangaFavorite(dialog.manga) }, mangaToRemove = dialog.manga, ) } is Dialog.ChangeMangaCategory -> { ChangeCategoryDialog( initialSelection = dialog.initialSelection, onDismissRequest = onDismissRequest, onEditCategories = { router.pushController(CategoryController()) }, onConfirm = { include, _ -> presenter.changeMangaFavorite(dialog.manga) presenter.moveMangaToCategories(dialog.manga, include) }, ) } null -> {} } BackHandler(onBack = ::navigateUp) LaunchedEffect(presenter.filters) { initFilterSheet() } } private fun navigateUp() { when { presenter.searchQuery != null -> presenter.searchQuery = null presenter.isUserQuery -> { val (_, filters) = presenter.currentFilter as BrowseSourcePresenter.Filter.UserInput presenter.search(query = "", filters = filters) } else -> router.popCurrentController() } } open fun initFilterSheet() { if (presenter.filters.isEmpty()) { return } filterSheet = SourceFilterSheet( activity!!, onFilterClicked = { presenter.search(filters = presenter.filters) }, onResetClicked = { presenter.reset() filterSheet?.setFilters(presenter.filterItems) }, ) filterSheet?.setFilters(presenter.filterItems) } /** * Restarts the request with a new query. * * @param newQuery the new query. */ fun searchWithQuery(newQuery: String) { presenter.search(newQuery) } /** * Attempts to restart the request with a new genre-filtered query. * If the genre name can't be found the filters, * the standard searchWithQuery search method is used instead. * * @param genreName the name of the genre */ fun searchWithGenre(genreName: String) { val defaultFilters = presenter.source!!.getFilterList() var genreExists = false filter@ for (sourceFilter in defaultFilters) { if (sourceFilter is Filter.Group<*>) { for (filter in sourceFilter.state) { if (filter is Filter<*> && filter.name.equals(genreName, true)) { when (filter) { is Filter.TriState -> filter.state = 1 is Filter.CheckBox -> filter.state = true else -> {} } genreExists = true break@filter } } } else if (sourceFilter is Filter.Select<*>) { val index = sourceFilter.values.filterIsInstance<String>() .indexOfFirst { it.equals(genreName, true) } if (index != -1) { sourceFilter.state = index genreExists = true break } } } if (genreExists) { filterSheet?.setFilters(defaultFilters.toItems()) presenter.search(filters = defaultFilters) } else { searchWithQuery(genreName) } } protected companion object { const val SOURCE_ID_KEY = "sourceId" const val SEARCH_QUERY_KEY = "searchQuery" } }
apache-2.0
647ca08dcfff650fce21a71f72473c57
35.875598
116
0.585572
5.200405
false
false
false
false
google/filament
android/samples/sample-stream-test/src/main/java/com/google/android/filament/streamtest/MainActivity.kt
1
17230
/* * Copyright (C) 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.google.android.filament.streamtest import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.os.Bundle import android.view.Choreographer import android.view.Surface import android.view.SurfaceView import androidx.core.app.ActivityCompat import com.google.android.filament.* import com.google.android.filament.RenderableManager.* import com.google.android.filament.VertexBuffer.* import com.google.android.filament.android.UiHelper import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.channels.Channels import android.opengl.* import android.os.Build import android.view.MotionEvent import androidx.annotation.RequiresApi import com.google.android.filament.android.DisplayHelper class MainActivity : Activity(), ActivityCompat.OnRequestPermissionsResultCallback { companion object { init { Filament.init() } } private lateinit var surfaceView: SurfaceView private lateinit var uiHelper: UiHelper private lateinit var displayHelper: DisplayHelper private lateinit var choreographer: Choreographer private lateinit var engine: Engine private lateinit var renderer: Renderer private lateinit var scene: Scene private lateinit var view: View // This helper wraps the Android camera2 API and connects it to a Filament material. private lateinit var streamHelper: StreamHelper // This is the Filament camera, not the phone camera. :) private lateinit var camera: Camera // Other Filament objects: private lateinit var material: Material private lateinit var materialInstance: MaterialInstance private lateinit var vertexBuffer: VertexBuffer private lateinit var indexBuffer: IndexBuffer // Filament entity representing a renderable object @Entity private var renderable = 0 @Entity private var light = 0 // A swap chain is Filament's representation of a surface private var swapChain: SwapChain? = null // Performs the rendering and schedules new frames private val frameScheduler = FrameCallback() @RequiresApi(30) class Api30Impl { companion object { fun getDisplay(context: Context) = context.display!! } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) surfaceView = SurfaceView(this) setContentView(surfaceView) choreographer = Choreographer.getInstance() displayHelper = DisplayHelper(this) setupSurfaceView() setupFilament() setupView() setupScene() @Suppress("deprecation") val display = if (Build.VERSION.SDK_INT >= 30) { Api30Impl.getDisplay(this) } else { windowManager.defaultDisplay!! } streamHelper = StreamHelper(engine, materialInstance, display) this.title = streamHelper.getTestName() } @SuppressLint("ClickableViewAccessibility") private fun setupSurfaceView() { uiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK) uiHelper.renderCallback = SurfaceCallback() uiHelper.attachTo(surfaceView) surfaceView.setOnTouchListener { _, event -> when(event.action){ MotionEvent.ACTION_DOWN -> { streamHelper.nextTest() this.title = streamHelper.getTestName() } } super.onTouchEvent(event) } } private fun setupFilament() { val eglContext = createEGLContext() engine = Engine.create(eglContext) renderer = engine.createRenderer() scene = engine.createScene() view = engine.createView() camera = engine.createCamera(engine.entityManager.create()) } private fun setupView() { scene.skybox = Skybox.Builder().color(0.035f, 0.035f, 0.035f, 1.0f).build(engine) view.camera = camera view.scene = scene } private fun setupScene() { loadMaterial() setupMaterial() createMesh() // To create a renderable we first create a generic entity renderable = EntityManager.get().create() // We then create a renderable component on that entity // A renderable is made of several primitives; in this case we declare only 1 // If we wanted each face of the cube to have a different material, we could // declare 6 primitives (1 per face) and give each of them a different material // instance, setup with different parameters RenderableManager.Builder(1) // Overall bounding box of the renderable .boundingBox(Box(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f)) // Sets the mesh data of the first primitive, 6 faces of 6 indices each .geometry(0, PrimitiveType.TRIANGLES, vertexBuffer, indexBuffer, 0, 6 * 6) // Sets the material of the first primitive .material(0, materialInstance) .build(engine, renderable) // Add the entity to the scene to render it scene.addEntity(renderable) // We now need a light, let's create a directional light light = EntityManager.get().create() // Create a color from a temperature (5,500K) val (r, g, b) = Colors.cct(5_500.0f) LightManager.Builder(LightManager.Type.DIRECTIONAL) .color(r, g, b) // Intensity of the sun in lux on a clear day .intensity(110_000.0f) // The direction is normalized on our behalf .direction(0.0f, -0.5f, -1.0f) .castShadows(true) .build(engine, light) // Add the entity to the scene to light it scene.addEntity(light) // Set the exposure on the camera, this exposure follows the sunny f/16 rule // Since we've defined a light that has the same intensity as the sun, it // guarantees a proper exposure camera.setExposure(16.0f, 1.0f / 125.0f, 100.0f) // Move the camera back to see the object camera.lookAt(0.0, 0.0, 6.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) } private fun loadMaterial() { readUncompressedAsset("materials/lit.filamat").let { material = Material.Builder().payload(it, it.remaining()).build(engine) } } private fun setupMaterial() { materialInstance = material.createInstance() materialInstance.setParameter("baseColor", Colors.RgbType.SRGB, 1.0f, 0.85f, 0.57f) materialInstance.setParameter("roughness", 0.3f) } private fun createMesh() { val floatSize = 4 val shortSize = 2 // A vertex is a position + a tangent frame: // 3 floats for XYZ position, 4 floats for normal+tangents (quaternion) val vertexSize = 3 * floatSize + 4 * floatSize // Define a vertex and a function to put a vertex in a ByteBuffer @Suppress("ArrayInDataClass") data class Vertex(val x: Float, val y: Float, val z: Float, val tangents: FloatArray) fun ByteBuffer.put(v: Vertex): ByteBuffer { putFloat(v.x) putFloat(v.y) putFloat(v.z) v.tangents.forEach { putFloat(it) } return this } // 6 faces, 4 vertices per face val vertexCount = 6 * 4 // Create tangent frames, one per face val tfPX = FloatArray(4) val tfNX = FloatArray(4) val tfPY = FloatArray(4) val tfNY = FloatArray(4) val tfPZ = FloatArray(4) val tfNZ = FloatArray(4) MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, tfPX) MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, -1.0f, 0.0f, 0.0f, tfNX) MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, tfPY) MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, tfNY) MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, tfPZ) MathUtils.packTangentFrame( 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, tfNZ) val vertexData = ByteBuffer.allocate(vertexCount * vertexSize) // It is important to respect the native byte order .order(ByteOrder.nativeOrder()) // Face -Z .put(Vertex(-1.5f, -1.5f, -1.0f, tfNZ)) .put(Vertex(-1.5f, 1.5f, -1.0f, tfNZ)) .put(Vertex( 1.5f, 1.5f, -1.0f, tfNZ)) .put(Vertex( 1.5f, -1.5f, -1.0f, tfNZ)) // Face +X .put(Vertex( 1.5f, -1.5f, -1.0f, tfPX)) .put(Vertex( 1.5f, 1.5f, -1.0f, tfPX)) .put(Vertex( 1.0f, 1.0f, 1.0f, tfPX)) .put(Vertex( 1.0f, -1.0f, 1.0f, tfPX)) // Face +Z .put(Vertex(-1.0f, -1.0f, 1.0f, tfPZ)) .put(Vertex( 1.0f, -1.0f, 1.0f, tfPZ)) .put(Vertex( 1.0f, 1.0f, 1.0f, tfPZ)) .put(Vertex(-1.0f, 1.0f, 1.0f, tfPZ)) // Face -X .put(Vertex(-1.0f, -1.0f, 1.0f, tfNX)) .put(Vertex(-1.0f, 1.0f, 1.0f, tfNX)) .put(Vertex(-1.5f, 1.5f, -1.0f, tfNX)) .put(Vertex(-1.5f, -1.5f, -1.0f, tfNX)) // Face -Y .put(Vertex(-1.0f, -1.0f, 1.0f, tfNY)) .put(Vertex(-1.5f, -1.5f, -1.0f, tfNY)) .put(Vertex( 1.5f, -1.5f, -1.0f, tfNY)) .put(Vertex( 1.0f, -1.0f, 1.0f, tfNY)) // Face +Y .put(Vertex(-1.5f, 1.5f, -1.0f, tfPY)) .put(Vertex(-1.0f, 1.0f, 1.0f, tfPY)) .put(Vertex( 1.0f, 1.0f, 1.0f, tfPY)) .put(Vertex( 1.5f, 1.5f, -1.0f, tfPY)) // Make sure the cursor is pointing in the right place in the byte buffer .flip() // Declare the layout of our mesh vertexBuffer = VertexBuffer.Builder() .bufferCount(1) .vertexCount(vertexCount) // Because we interleave position and color data we must specify offset and stride // We could use de-interleaved data by declaring two buffers and giving each // attribute a different buffer index .attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize) .attribute(VertexAttribute.TANGENTS, 0, AttributeType.FLOAT4, 3 * floatSize, vertexSize) .build(engine) // Feed the vertex data to the mesh // We only set 1 buffer because the data is interleaved vertexBuffer.setBufferAt(engine, 0, vertexData) // Create the indices val indexData = ByteBuffer.allocate(6 * 2 * 3 * shortSize) .order(ByteOrder.nativeOrder()) repeat(6) { val i = (it * 4).toShort() indexData .putShort(i).putShort((i + 1).toShort()).putShort((i + 2).toShort()) .putShort(i).putShort((i + 2).toShort()).putShort((i + 3).toShort()) } indexData.flip() // 6 faces, 2 triangles per face, indexBuffer = IndexBuffer.Builder() .indexCount(vertexCount * 2) .bufferType(IndexBuffer.Builder.IndexType.USHORT) .build(engine) indexBuffer.setBuffer(engine, indexData) } override fun onResume() { super.onResume() choreographer.postFrameCallback(frameScheduler) } override fun onPause() { super.onPause() choreographer.removeFrameCallback(frameScheduler) } override fun onDestroy() { super.onDestroy() // Stop the animation and any pending frame choreographer.removeFrameCallback(frameScheduler) // Always detach the surface before destroying the engine uiHelper.detach() // Cleanup all resources engine.destroyEntity(light) engine.destroyEntity(renderable) engine.destroyRenderer(renderer) engine.destroyVertexBuffer(vertexBuffer) engine.destroyIndexBuffer(indexBuffer) engine.destroyMaterialInstance(materialInstance) engine.destroyMaterial(material) engine.destroyView(view) engine.destroyScene(scene) engine.destroyCameraComponent(camera.entity) // Engine.destroyEntity() destroys Filament related resources only // (components), not the entity itself val entityManager = EntityManager.get() entityManager.destroy(light) entityManager.destroy(renderable) entityManager.destroy(camera.entity) // Destroying the engine will free up any resource you may have forgotten // to destroy, but it's recommended to do the cleanup properly engine.destroy() } inner class FrameCallback : Choreographer.FrameCallback { override fun doFrame(frameTimeNanos: Long) { // Schedule the next frame choreographer.postFrameCallback(this) // This check guarantees that we have a swap chain if (uiHelper.isReadyToRender) { // If beginFrame() returns false you should skip the frame // This means you are sending frames too quickly to the GPU if (renderer.beginFrame(swapChain!!, frameTimeNanos)) { streamHelper.repaintCanvas() materialInstance.setParameter("uvOffset", streamHelper.uvOffset) renderer.render(view) renderer.endFrame() } } } } inner class SurfaceCallback : UiHelper.RendererCallback { override fun onNativeWindowChanged(surface: Surface) { swapChain?.let { engine.destroySwapChain(it) } swapChain = engine.createSwapChain(surface) displayHelper.attach(renderer, surfaceView.display) } override fun onDetachedFromSurface() { displayHelper.detach() swapChain?.let { engine.destroySwapChain(it) // Required to ensure we don't return before Filament is done executing the // destroySwapChain command, otherwise Android might destroy the Surface // too early engine.flushAndWait() swapChain = null } } override fun onResized(width: Int, height: Int) { val aspect = width.toDouble() / height.toDouble() camera.setProjection(45.0, aspect, 0.1, 20.0, Camera.Fov.VERTICAL) view.viewport = Viewport(0, 0, width, height) } } private fun readUncompressedAsset(@Suppress("SameParameterValue") assetName: String): ByteBuffer { assets.openFd(assetName).use { fd -> val input = fd.createInputStream() val dst = ByteBuffer.allocate(fd.length.toInt()) val src = Channels.newChannel(input) src.read(dst) src.close() return dst.apply { rewind() } } } private fun createEGLContext(): EGLContext { // Providing this constant here (rather than using EGL_OPENGL_ES3_BIT ) allows us to use a lower target API for this project. val kEGLOpenGLES3Bit = 64 val shareContext = EGL14.EGL_NO_CONTEXT val display = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY) val minorMajor: IntArray = IntArray(2) EGL14.eglInitialize(display, minorMajor, 0, minorMajor, 1) val configs = arrayOfNulls<EGLConfig>(1) val numConfig = intArrayOf(0) val attribs = intArrayOf(EGL14.EGL_RENDERABLE_TYPE, kEGLOpenGLES3Bit, EGL14.EGL_NONE) EGL14.eglChooseConfig(display, attribs, 0, configs, 0, 1, numConfig, 0) val contextAttribs = intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 3, EGL14.EGL_NONE) val context = EGL14.eglCreateContext(display, configs[0], shareContext, contextAttribs, 0) val surfaceAttribs = intArrayOf(EGL14.EGL_WIDTH, 1, EGL14.EGL_HEIGHT, 1, EGL14.EGL_NONE) val surface = EGL14.eglCreatePbufferSurface(display, configs[0], surfaceAttribs, 0) check(EGL14.eglMakeCurrent(display, surface, surface, context)) { "Error making GL context." } return context } }
apache-2.0
1096a97393f3ffac656321bae7808e13
37.806306
133
0.610911
4.161836
false
false
false
false
exponentjs/exponent
packages/expo-image-picker/android/src/main/java/expo/modules/imagepicker/ImagePickerOptions.kt
2
2161
package expo.modules.imagepicker import expo.modules.core.Promise import expo.modules.core.utilities.ifNull data class ImagePickerOptions( val quality: Int, val isAllowsEditing: Boolean, val forceAspect: List<*>?, val isBase64: Boolean, val mediaTypes: MediaTypes, val isExif: Boolean, val videoMaxDuration: Int ) { companion object { fun optionsFromMap(options: Map<String, Any?>, promise: Promise): ImagePickerOptions? { val quality = options[ImagePickerConstants.OPTION_QUALITY]?.let { if (it is Number) { return@let (it.toDouble() * 100).toInt() } promise.reject(ImagePickerConstants.ERR_INVALID_OPTION, "Quality can not be `null`.") return null } ?: ImagePickerConstants.DEFAULT_QUALITY val isAllowsEditing = options[ImagePickerConstants.OPTION_ALLOWS_EDITING] as? Boolean ?: false val forceAspect: List<*>? = options[ImagePickerConstants.OPTION_ASPECT]?.let { if (it is List<*> && it.size == 2 && it[0] is Number && it[1] is Number) { return@let it } promise.reject(ImagePickerConstants.ERR_INVALID_OPTION, "'Aspect option must be of form [Number, Number]") return null } val isBase64 = options[ImagePickerConstants.OPTION_BASE64] as? Boolean ?: false val mediaTypes = MediaTypes.fromString( options[ImagePickerConstants.OPTION_MEDIA_TYPES] as? String ?: "Images" ).ifNull { promise.reject(ImagePickerConstants.ERR_INVALID_OPTION, "Unknown media types: ${options[ImagePickerConstants.OPTION_MEDIA_TYPES]}") return null } val isExif = options[ImagePickerConstants.OPTION_EXIF] as? Boolean ?: false val videoMaxDuration = options[ImagePickerConstants.OPTION_VIDEO_MAX_DURATION]?.let { if (it is Number && it.toInt() >= 0) { return@let it.toInt() } promise.reject(ImagePickerConstants.ERR_INVALID_OPTION, "videoMaxDuration must be a non-negative integer") return null } ?: 0 return ImagePickerOptions(quality, isAllowsEditing, forceAspect, isBase64, mediaTypes, isExif, videoMaxDuration) } } }
bsd-3-clause
a5c5e29844f1bab7581cb520ca31bf2c
36.258621
139
0.679778
4.322
false
false
false
false
exponentjs/exponent
android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/gesturehandler/react/RNGestureHandlerRegistry.kt
2
3032
package versioned.host.exp.exponent.modules.api.components.gesturehandler.react import android.util.SparseArray import android.view.View import com.facebook.react.bridge.UiThreadUtil import versioned.host.exp.exponent.modules.api.components.gesturehandler.GestureHandler import versioned.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerRegistry import java.util.* class RNGestureHandlerRegistry : GestureHandlerRegistry { private val handlers = SparseArray<GestureHandler<*>>() private val attachedTo = SparseArray<Int?>() private val handlersForView = SparseArray<ArrayList<GestureHandler<*>>>() @Synchronized fun registerHandler(handler: GestureHandler<*>) { handlers.put(handler.tag, handler) } @Synchronized fun getHandler(handlerTag: Int): GestureHandler<*>? { return handlers[handlerTag] } @Synchronized fun attachHandlerToView(handlerTag: Int, viewTag: Int, useDeviceEvents: Boolean = false): Boolean { val handler = handlers[handlerTag] return handler?.let { detachHandler(handler) handler.usesDeviceEvents = useDeviceEvents registerHandlerForViewWithTag(viewTag, handler) true } ?: false } @Synchronized private fun registerHandlerForViewWithTag(viewTag: Int, handler: GestureHandler<*>) { check(attachedTo[handler.tag] == null) { "Handler $handler already attached" } attachedTo.put(handler.tag, viewTag) var listToAdd = handlersForView[viewTag] if (listToAdd == null) { listToAdd = ArrayList(1) listToAdd.add(handler) handlersForView.put(viewTag, listToAdd) } else { listToAdd.add(handler) } } @Synchronized private fun detachHandler(handler: GestureHandler<*>) { val attachedToView = attachedTo[handler.tag] if (attachedToView != null) { attachedTo.remove(handler.tag) val attachedHandlers = handlersForView[attachedToView] if (attachedHandlers != null) { attachedHandlers.remove(handler) if (attachedHandlers.size == 0) { handlersForView.remove(attachedToView) } } } if (handler.view != null) { // Handler is in "prepared" state which means it is registered in the orchestrator and can // receive touch events. This means that before we remove it from the registry we need to // "cancel" it so that orchestrator does no longer keep a reference to it. UiThreadUtil.runOnUiThread { handler.cancel() } } } @Synchronized fun dropHandler(handlerTag: Int) { handlers[handlerTag]?.let { detachHandler(it) handlers.remove(handlerTag) } } @Synchronized fun dropAllHandlers() { handlers.clear() attachedTo.clear() handlersForView.clear() } @Synchronized fun getHandlersForViewWithTag(viewTag: Int): ArrayList<GestureHandler<*>>? { return handlersForView[viewTag] } @Synchronized override fun getHandlersForView(view: View): ArrayList<GestureHandler<*>>? { return getHandlersForViewWithTag(view.id) } }
bsd-3-clause
99c14209bd4eb8b70353659265c3b609
30.915789
101
0.716689
4.452276
false
false
false
false
exponentjs/exponent
packages/expo-camera/android/src/main/java/expo/modules/camera/CameraViewManager.kt
2
3584
package expo.modules.camera import android.content.Context import com.google.android.cameraview.AspectRatio import com.google.android.cameraview.Size import expo.modules.core.interfaces.ExpoProp import expo.modules.core.interfaces.services.UIManager import expo.modules.core.ModuleRegistry import expo.modules.core.ModuleRegistryDelegate import expo.modules.core.ViewManager import expo.modules.interfaces.barcodescanner.BarCodeScannerSettings class CameraViewManager( private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate() ) : ViewManager<ExpoCameraView>() { private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>() enum class Events(private val eventsName: String) { EVENT_CAMERA_READY("onCameraReady"), EVENT_ON_MOUNT_ERROR("onMountError"), EVENT_ON_BAR_CODE_SCANNED("onBarCodeScanned"), EVENT_ON_FACES_DETECTED("onFacesDetected"), EVENT_ON_FACE_DETECTION_ERROR("onFaceDetectionError"), EVENT_ON_PICTURE_SAVED("onPictureSaved"); override fun toString() = eventsName } override fun onCreate(moduleRegistry: ModuleRegistry) { moduleRegistryDelegate.onCreate(moduleRegistry) } override fun onDropViewInstance(view: ExpoCameraView) { val uIManager: UIManager by moduleRegistry() uIManager.unregisterLifecycleEventListener(view) view.stop() } override fun getName() = REACT_CLASS override fun getViewManagerType() = ViewManagerType.GROUP override fun createViewInstance(context: Context) = ExpoCameraView(context, moduleRegistryDelegate) override fun getExportedEventNames() = Events.values().map { it.toString() } @ExpoProp(name = "type") fun setType(view: ExpoCameraView, type: Int) { view.facing = type } @ExpoProp(name = "ratio") fun setRatio(view: ExpoCameraView, ratio: String?) { view.setAspectRatio(AspectRatio.parse(ratio)) } @ExpoProp(name = "flashMode") fun setFlashMode(view: ExpoCameraView, torchMode: Int) { view.flash = torchMode } @ExpoProp(name = "autoFocus") fun setAutoFocus(view: ExpoCameraView, autoFocus: Boolean) { view.autoFocus = autoFocus } @ExpoProp(name = "focusDepth") fun setFocusDepth(view: ExpoCameraView, depth: Float) { view.focusDepth = depth } @ExpoProp(name = "zoom") fun setZoom(view: ExpoCameraView, zoom: Float) { view.zoom = zoom } @ExpoProp(name = "whiteBalance") fun setWhiteBalance(view: ExpoCameraView, whiteBalance: Int) { view.whiteBalance = whiteBalance } @ExpoProp(name = "pictureSize") fun setPictureSize(view: ExpoCameraView, size: String?) { view.pictureSize = Size.parse(size) } @ExpoProp(name = "barCodeScannerSettings") fun setBarCodeScannerSettings(view: ExpoCameraView, settings: Map<String?, Any?>?) { view.setBarCodeScannerSettings(BarCodeScannerSettings(settings)) } @ExpoProp(name = "useCamera2Api") fun setUseCamera2Api(view: ExpoCameraView, useCamera2Api: Boolean) { view.setUsingCamera2Api(useCamera2Api) } @ExpoProp(name = "barCodeScannerEnabled") fun setBarCodeScanning(view: ExpoCameraView, barCodeScannerEnabled: Boolean) { view.setShouldScanBarCodes(barCodeScannerEnabled) } @ExpoProp(name = "faceDetectorEnabled") fun setFaceDetectorEnabled(view: ExpoCameraView, faceDetectorEnabled: Boolean) { view.setShouldDetectFaces(faceDetectorEnabled) } @ExpoProp(name = "faceDetectorSettings") fun setFaceDetectorSettings(view: ExpoCameraView, settings: Map<String, Any>?) { view.setFaceDetectorSettings(settings) } }
bsd-3-clause
99338141eaa9156907eb6599b3c267b5
29.896552
101
0.754185
4.063492
false
false
false
false
Heiner1/AndroidAPS
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt
1
4831
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotParseMessageException import info.nightscout.androidaps.plugins.pump.omnipod.dash.util.Flag import java.nio.ByteBuffer /*** * MessagePacket contains header and raw payload for a message */ data class MessagePacket( val type: MessageType, val source: Id, val destination: Id, val payload: ByteArray, val sequenceNumber: Byte, val ack: Boolean = false, val ackNumber: Byte = 0.toByte(), val eqos: Short = 0.toShort(), val priority: Boolean = false, val lastMessage: Boolean = false, val gateway: Boolean = false, val sas: Boolean = true, // TODO: understand, seems to always be true val tfs: Boolean = false, // TODO: understand, seems to be false val version: Short = 0.toShort() ) { fun asByteArray(forEncryption: Boolean = false): ByteArray { val bb = ByteBuffer.allocate(16 + payload.size) bb.put(MAGIC_PATTERN.toByteArray()) val f1 = Flag() f1.set(0, this.version.toInt() and 4 != 0) f1.set(1, this.version.toInt() and 2 != 0) f1.set(2, this.version.toInt() and 1 != 0) f1.set(3, this.sas) f1.set(4, this.tfs) f1.set(5, this.eqos.toInt() and 4 != 0) f1.set(6, this.eqos.toInt() and 2 != 0) f1.set(7, this.eqos.toInt() and 1 != 0) val f2 = Flag() f2.set(0, this.ack) f2.set(1, this.priority) f2.set(2, this.lastMessage) f2.set(3, this.gateway) f2.set(4, this.type.value.toInt() and 8 != 0) f2.set(5, this.type.value.toInt() and 4 != 0) f2.set(6, this.type.value.toInt() and 2 != 0) f2.set(7, this.type.value.toInt() and 1 != 0) bb.put(f1.value.toByte()) bb.put(f2.value.toByte()) bb.put(this.sequenceNumber) bb.put(this.ackNumber) val size = payload.size - if (type == MessageType.ENCRYPTED && !forEncryption) 8 else 0 bb.put((size ushr 3).toByte()) bb.put((size shl 5).toByte()) bb.put(this.source.address) bb.put(this.destination.address) bb.put(this.payload) val ret = ByteArray(bb.position()) bb.flip() bb.get(ret) return ret } companion object { private const val MAGIC_PATTERN = "TW" // all messages start with this string private const val HEADER_SIZE = 16 fun parse(payload: ByteArray): MessagePacket { payload.assertSizeAtLeast(HEADER_SIZE) if (payload.copyOfRange(0, 2).decodeToString() != MAGIC_PATTERN) { throw CouldNotParseMessageException(payload) } val f1 = Flag(payload[2].toInt() and 0xff) val sas = f1.get(3) != 0 val tfs = f1.get(4) != 0 val version = ((f1.get(0) shl 2) or (f1.get(1) shl 1) or (f1.get(2) shl 0)).toShort() val eqos = (f1.get(7) or (f1.get(6) shl 1) or (f1.get(5) shl 2)).toShort() val f2 = Flag(payload[3].toInt() and 0xff) val ack = f2.get(0) != 0 val priority = f2.get(1) != 0 val lastMessage = f2.get(2) != 0 val gateway = f2.get(3) != 0 val type = MessageType.byValue((f1.get(7) or (f1.get(6) shl 1) or (f1.get(5) shl 2) or (f1.get(4) shl 3)).toByte()) if (version.toInt() != 0) { throw CouldNotParseMessageException(payload) } val sequenceNumber = payload[4] val ackNumber = payload[5] val size = (payload[6].toInt() shl 3) or (payload[7].toUnsignedInt() ushr 5) payload.assertSizeAtLeast(size + HEADER_SIZE) val payloadEnd = 16 + size + if (type == MessageType.ENCRYPTED) 8 // TAG else 0 return MessagePacket( type = type, ack = ack, eqos = eqos, priority = priority, lastMessage = lastMessage, gateway = gateway, sas = sas, tfs = tfs, version = version, sequenceNumber = sequenceNumber, ackNumber = ackNumber, source = Id(payload.copyOfRange(8, 12)), destination = Id(payload.copyOfRange(12, 16)), payload = payload.copyOfRange(16, payloadEnd) ) } } } internal fun Byte.toUnsignedInt() = this.toInt() and 0xff private fun ByteArray.assertSizeAtLeast(size: Int) { if (this.size < size) { throw CouldNotParseMessageException(this) } }
agpl-3.0
0a636ae531713f057bff616d2231ec5f
34.785185
120
0.568205
3.65155
false
false
false
false
Maccimo/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHPRVirtualFileSystem.kt
1
2435
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.vcs.editor.ComplexPathVirtualFileSystem import com.intellij.vcs.editor.GsonComplexPathSerializer import org.jetbrains.plugins.github.api.GHRepositoryCoordinates import org.jetbrains.plugins.github.pullrequest.data.GHPRDataContextRepository import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier import org.jetbrains.plugins.github.pullrequest.data.SimpleGHPRIdentifier internal class GHPRVirtualFileSystem : ComplexPathVirtualFileSystem<GHPRVirtualFileSystem.GHPRFilePath>( GsonComplexPathSerializer(GHPRFilePath::class.java) ) { override fun getProtocol() = PROTOCOL override fun findOrCreateFile(project: Project, path: GHPRFilePath): VirtualFile? { val filesManager = GHPRDataContextRepository.getInstance(project).findContext(path.repository)?.filesManager ?: return null val pullRequest = path.prId val sourceId = path.sourceId return when { pullRequest == null && sourceId != null -> filesManager.createOrGetNewPRDiffFile(sourceId) pullRequest == null -> null path.isDiff -> filesManager.findDiffFile(pullRequest) else -> filesManager.findTimelineFile(pullRequest) } } fun getPath(fileManagerId: String, project: Project, repository: GHRepositoryCoordinates, id: GHPRIdentifier?, sourceId: String?, isDiff: Boolean = false): String = getPath(GHPRFilePath(fileManagerId, project.locationHash, repository, id?.let { SimpleGHPRIdentifier(it) }, sourceId, isDiff)) data class GHPRFilePath(override val sessionId: String, override val projectHash: String, val repository: GHRepositoryCoordinates, val prId: SimpleGHPRIdentifier?, val sourceId: String?, val isDiff: Boolean) : ComplexPath companion object { private const val PROTOCOL = "ghpr" fun getInstance() = service<VirtualFileManager>().getFileSystem(PROTOCOL) as GHPRVirtualFileSystem } }
apache-2.0
6193214880f923097c29c43a27799fe9
45.826923
140
0.734292
4.989754
false
false
false
false
JetBrains/ideavim
src/test/java/org/jetbrains/plugins/ideavim/ex/implementation/functions/FunctionTest.kt
1
3438
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package org.jetbrains.plugins.ideavim.ex.implementation.functions import org.jetbrains.plugins.ideavim.SkipNeovimReason import org.jetbrains.plugins.ideavim.TestWithoutNeovim import org.jetbrains.plugins.ideavim.VimTestCase class FunctionTest : VimTestCase() { fun `test function for built-in function`() { configureByText("\n") typeText(commandToKeys("let Ff = function('abs')")) typeText(commandToKeys("echo Ff(-10)")) assertExOutput("10\n") typeText(commandToKeys("echo Ff")) assertExOutput("abs\n") } fun `test function with arglist`() { configureByText("\n") typeText(commandToKeys("let Ff = function('abs', [-10])")) typeText(commandToKeys("echo Ff()")) assertExOutput("10\n") typeText(commandToKeys("echo Ff")) assertExOutput("function('abs', [-10])\n") } @TestWithoutNeovim(SkipNeovimReason.PLUGIN_ERROR) fun `test function for unknown function`() { configureByText("\n") typeText(commandToKeys("let Ff = function('unknown')")) assertPluginError(true) assertPluginErrorMessageContains("E700: Unknown function: unknown") } // todo in release 1.9 (good example of multiple exceptions at once) @TestWithoutNeovim(SkipNeovimReason.PLUGIN_ERROR) fun `test function with wrong function name`() { configureByText("\n") typeText(commandToKeys("let Ff = function(32)")) assertPluginError(true) assertPluginErrorMessageContains("E129: Function name required") } @TestWithoutNeovim(SkipNeovimReason.PLUGIN_ERROR) fun `test function with wrong second argument`() { configureByText("\n") typeText(commandToKeys("let Ff = function('abs', 10)")) assertPluginError(true) assertPluginErrorMessageContains("E923: Second argument of function() must be a list or a dict") } @TestWithoutNeovim(SkipNeovimReason.PLUGIN_ERROR) fun `test function with wrong third argument`() { configureByText("\n") typeText(commandToKeys("let Ff = function('abs', [], 40)")) assertPluginError(true) assertPluginErrorMessageContains("E922: expected a dict") } fun `test redefining a function`() { configureByText("\n") typeText( commandToKeys( """ function! SayHi() | echo 'hello' | endfunction """.trimIndent() ) ) typeText(commandToKeys("let Ff = function('SayHi')")) typeText(commandToKeys("call Ff()")) assertExOutput("hello\n") typeText( commandToKeys( """ function! SayHi() | echo 'hi' | endfunction """.trimIndent() ) ) typeText(commandToKeys("call Ff()")) assertExOutput("hi\n") typeText(commandToKeys("delfunction! SayHi")) } @TestWithoutNeovim(SkipNeovimReason.PLUGIN_ERROR) fun `test deleting function`() { configureByText("\n") typeText( commandToKeys( """ function! SayHi() | echo 'hello' | endfunction """.trimIndent() ) ) typeText(commandToKeys("let Ff = function('SayHi')")) typeText(commandToKeys("delfunction! SayHi")) typeText(commandToKeys("call Ff()")) assertPluginError(true) assertPluginErrorMessageContains("E933: Function was deleted: SayHi") } }
mit
362262392e3125ad01fd18b067bf66e3
28.135593
100
0.672193
4.302879
false
true
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/data/DefaultStackedTile.kt
1
2809
package org.hexworks.zircon.internal.data import kotlinx.collections.immutable.PersistentList import kotlinx.collections.immutable.persistentListOf import org.hexworks.zircon.api.Beta import org.hexworks.zircon.api.builder.data.TileBuilder import org.hexworks.zircon.api.color.TileColor import org.hexworks.zircon.api.data.* import org.hexworks.zircon.api.graphics.StyleSet import org.hexworks.zircon.api.modifier.Modifier @Suppress("RUNTIME_ANNOTATION_NOT_SUPPORTED") @Beta data class DefaultStackedTile( override val baseTile: Tile, private val rest: PersistentList<Tile> = persistentListOf() ) : StackedTile, Tile by baseTile { override val tiles: List<Tile> = persistentListOf(baseTile) + rest override val top: Tile = rest.lastOrNull() ?: baseTile override fun withPushedTile(tile: Tile): StackedTile = DefaultStackedTile( baseTile = baseTile, rest = rest.add(tile) ) override fun withBaseTile(tile: Tile): StackedTile = DefaultStackedTile( baseTile = tile, rest = rest ) override fun withRemovedTile(tile: Tile): StackedTile = DefaultStackedTile( baseTile = baseTile, rest = rest.remove(tile) ) override fun createCopy() = this override fun withForegroundColor(foregroundColor: TileColor) = withBaseTile(baseTile.withForegroundColor(foregroundColor)) override fun withBackgroundColor(backgroundColor: TileColor) = withBaseTile(baseTile.withBackgroundColor(backgroundColor)) override fun withModifiers(modifiers: Set<Modifier>) = withBaseTile(baseTile.withModifiers(modifiers)) override fun withModifiers(vararg modifiers: Modifier) = withBaseTile(baseTile.withModifiers(modifiers.toSet())) override fun withAddedModifiers(modifiers: Set<Modifier>) = withBaseTile(baseTile.withAddedModifiers(modifiers)) override fun withAddedModifiers(vararg modifiers: Modifier) = withBaseTile(baseTile.withAddedModifiers(modifiers.toSet())) override fun withRemovedModifiers(modifiers: Set<Modifier>) = withBaseTile(baseTile.withRemovedModifiers(modifiers)) override fun withRemovedModifiers(vararg modifiers: Modifier) = withBaseTile(baseTile.withRemovedModifiers(modifiers.toSet())) override fun withNoModifiers() = withBaseTile(baseTile.withNoModifiers()) override fun withStyle(style: StyleSet) = withBaseTile(baseTile.withStyle(style)) override fun asCharacterTileOrNull() = top.asCharacterTileOrNull() override fun asImageTileOrNull() = top.asImageTileOrNull() override fun asGraphicalTileOrNull() = top.asGraphicalTileOrNull() override fun toBuilder(): TileBuilder { throw UnsupportedOperationException("This operation is not implemented yet") } }
apache-2.0
0f83b9efbbc961f4f1944eaf61f62747
34.1125
84
0.749021
4.465819
false
false
false
false
mvysny/vaadin-on-kotlin
vok-rest/src/main/kotlin/eu/vaadinonkotlin/rest/VokOrmCrudHandler.kt
1
4948
package eu.vaadinonkotlin.rest import com.github.vokorm.* import com.github.vokorm.dataloader.EntityDataLoader import com.gitlab.mvysny.jdbiorm.Dao import io.javalin.apibuilder.CrudHandler import io.javalin.http.Context import io.javalin.http.NotFoundResponse import io.javalin.http.UnauthorizedResponse /** * A very simple handler that exposes instances of given entity of type [E] using the `vok-orm` database access library. * * The [getAll] honors the following query parameters: * * `limit` and `offset` for result paging. Both must be 0 or greater; `limit` must be less than `maxLimit` * * `sort_by=-last_modified,+email,first_name` - a list of sorting clauses. Only those which appear in `allowSortColumns` are allowed. * Prepending a column name with `-` will sort DESC. * * To define filters, simply pass in column names with the values, for example `age=81`. You can also specify operators: one of * `eq:`, `lt:`, `lte:`, `gt:`, `gte:`, `ilike:`, `like:`, `isnull:`, `isnotnull:`, for example `age=lt:25`. You can pass single column name * multiple times to AND additional clauses, for example `name=ilike:martin&age=lte:70&age=gte:20&birthdate=isnull:&grade=5`. OR filters are not supported. * * `select=count` - if this is passed in, then instead of a list of matching objects a single number will be returned: the number of * records matching given filters. * * All column names are expected to be Kotlin [kotlin.reflect.KProperty1.name] of the entity in question. * * @param idClass the type of the Entity ID. Only `String`, `Long` and `Integer` IDs are supported as of now; all others will be rejected with an [IllegalArgumentException]. * @param E the type of the entity for which to provide instances. * @param ID the type of the ID of entity [E] * @property allowsModification if false then POST/PATCH/DELETE [create]/[delete]/[update] will fail with 401 UNAUTHORIZED * @param maxLimit the maximum number of items permitted to be returned by [getAll]. If the client attempts to request more * items then 400 BAD REQUEST is returned. Defaults to [Int.MAX_VALUE], definitely change this in production! * @param defaultLimit if `limit` is unspecified in [getAll] request, then return at most this number of items. By default equals to [maxLimit]. * @param allowSortColumns if not null, only these columns are allowed to be sorted upon. Defaults to null. References the [kotlin.reflect.KProperty1.name] of the entity. * @param allowFilterColumns if not null, only these columns are allowed to be filtered upon. Defaults to null. References the [kotlin.reflect.KProperty1.name] of the entity. */ public open class VokOrmCrudHandler<ID : Any, E : KEntity<ID>>( idClass: Class<ID>, private val dao: Dao<E, ID>, public val allowsModification: Boolean, maxLimit: Long = Long.MAX_VALUE, defaultLimit: Long = maxLimit, allowSortColumns: Set<String>? = null, allowFilterColumns: Set<String>? = null ) : CrudHandler { /** * The [getAll] call delegates here. */ protected val getAllHandler: CrudHandler = DataLoaderCrudHandler(dao.entityClass, EntityDataLoader(dao.entityClass), maxLimit, defaultLimit, allowSortColumns, allowFilterColumns) @Suppress("UNCHECKED_CAST") private val idConverter: (String)->ID = when (idClass) { String::class.java -> { it -> it as ID } java.lang.Long::class.java -> { it -> it.toLong() as ID } Integer::class.java -> { it -> it.toInt() as ID } else -> throw IllegalArgumentException("Can't provide converter for $idClass") } private fun checkAllowsModification() { if (!allowsModification) throw UnauthorizedResponse() } private fun convertID(resourceId: String): ID = try { idConverter(resourceId) } catch (e: NumberFormatException) { throw NotFoundResponse("Malformed ID: $resourceId") } override fun create(ctx: Context) { checkAllowsModification() ctx.bodyAsClass(dao.entityClass).save() } override fun delete(ctx: Context, resourceId: String) { checkAllowsModification() val id: ID = convertID(resourceId) dao.deleteById(id) } override fun getAll(ctx: Context) { getAllHandler.getAll(ctx) } override fun getOne(ctx: Context, resourceId: String) { val id: ID = convertID(resourceId) val obj: E = dao.findById(id) ?: throw NotFoundResponse("No such entity with ID $resourceId") ctx.json(obj) } override fun update(ctx: Context, resourceId: String) { checkAllowsModification() val entity: E = ctx.bodyAsClass(dao.entityClass) entity.id = idConverter(resourceId) db { if (!dao.existsById(entity.id!!)) { throw NotFoundResponse("No such entity with ID $resourceId") } entity.save() } } }
mit
7af42e0d162ee1cd8b38def28094a6cb
47.038835
174
0.692805
4.035889
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddValVarToConstructorParameterAction.kt
1
4239
// 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.codeInsight.template.TemplateBuilderImpl import com.intellij.codeInsight.template.TemplateManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.refactoring.ValVarExpression import org.jetbrains.kotlin.idea.util.isExpectDeclaration import org.jetbrains.kotlin.idea.util.mustHaveValOrVar import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset interface AddValVarToConstructorParameterAction { fun canInvoke(element: KtParameter): Boolean = element.valOrVarKeyword == null && ((element.parent as? KtParameterList)?.parent as? KtPrimaryConstructor)?.takeIf { it.mustHaveValOrVar() || !it.isExpectDeclaration() } != null operator fun invoke(element: KtParameter, editor: Editor?) { val project = element.project element.addBefore(KtPsiFactory(project).createValKeyword(), element.nameIdentifier) if (element.containingClass()?.isInline() == true || editor == null) return val parameter = element.createSmartPointer().let { PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) it.element } ?: return editor.caretModel.moveToOffset(parameter.startOffset) TemplateBuilderImpl(parameter) .apply { replaceElement(parameter.valOrVarKeyword ?: return@apply, ValVarExpression) } .buildInlineTemplate() .let { TemplateManager.getInstance(project).startTemplate(editor, it) } } class Intention : SelfTargetingRangeIntention<KtParameter>( KtParameter::class.java, KotlinBundle.lazyMessage("add.val.var.to.primary.constructor.parameter") ), AddValVarToConstructorParameterAction { override fun applicabilityRange(element: KtParameter): TextRange? { if (!canInvoke(element)) return null val containingClass = element.getStrictParentOfType<KtClass>() if (containingClass?.isData() == true || containingClass?.isInline() == true) return null setTextGetter(KotlinBundle.lazyMessage("add.val.var.to.parameter.0", element.name ?: "")) return element.nameIdentifier?.textRange } override fun applyTo(element: KtParameter, editor: Editor?) = invoke(element, editor) } class QuickFix(parameter: KtParameter) : KotlinQuickFixAction<KtParameter>(parameter), AddValVarToConstructorParameterAction { override fun getText(): String { val element = this.element ?: return "" val key = when { element.getStrictParentOfType<KtClass>()?.isInline() == true -> "add.val.to.parameter.0" else -> "add.val.var.to.parameter.0" } return KotlinBundle.message(key, element.name ?: "") } override fun getFamilyName() = KotlinBundle.message("add.val.var.to.primary.constructor.parameter") override fun invoke(project: Project, editor: Editor?, file: KtFile) { invoke(element ?: return, editor) } } object QuickFixFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = QuickFix(Errors.DATA_CLASS_NOT_PROPERTY_PARAMETER.cast(diagnostic).psiElement) } }
apache-2.0
efdd5ed6032ae82c6366b370327be44a
46.640449
185
0.735079
4.975352
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/en1545/En1545LookupSTR.kt
1
3421
/* * En1545LookupSTR.kt * * Copyright 2018 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.en1545 import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.multi.StringResource import au.id.micolous.metrodroid.util.NumberUtils import au.id.micolous.metrodroid.multi.FormattedString import au.id.micolous.metrodroid.transit.Station import au.id.micolous.metrodroid.transit.Trip import au.id.micolous.metrodroid.util.StationTableReader abstract class En1545LookupSTR protected constructor(protected val mStr: String) : En1545Lookup { override fun getRouteName(routeNumber: Int?, routeVariant: Int?, agency: Int?, transport: Int?): FormattedString? { if (routeNumber == null) return null val routeId = routeNumber or ((agency ?: 0) shl 16) or ((transport ?: 0) shl 24) val routeReadable = getHumanReadableRouteId(routeNumber, routeVariant, agency ?: 0, transport ?: 0) return StationTableReader.getLineName(mStr, routeId, routeReadable!!) } override fun getAgencyName(agency: Int?, isShort: Boolean): FormattedString? { if (agency == null || agency == 0) return null return StationTableReader.getOperatorName(mStr, agency, isShort) } override fun getStation(station: Int, agency: Int?, transport: Int?): Station? { if (station == 0) return null return StationTableReader.getStation( mStr, station or ((agency ?: 0) shl 16), NumberUtils.intToHex(station)) } override fun getMode(agency: Int?, route: Int?): Trip.Mode { if (route != null) { val mode: Trip.Mode? = if (agency == null) StationTableReader.getLineMode(mStr, route) else StationTableReader.getLineMode(mStr, route or (agency shl 16)) if (mode != null) return mode } if (agency == null) return Trip.Mode.OTHER return StationTableReader.getOperatorDefaultMode(mStr, agency) } override fun getSubscriptionName(agency: Int?, contractTariff: Int?): String? { if (contractTariff == null) return null val res = subscriptionMapByAgency[Pair(agency, contractTariff)] ?: subscriptionMap[contractTariff] ?: return Localizer.localizeString(R.string.unknown_format, contractTariff.toString()) return Localizer.localizeString(res) } // TODO: move to MdST open val subscriptionMap: Map<Int, StringResource> get() = mapOf() open val subscriptionMapByAgency: Map<Pair<Int?, Int>, StringResource> get() = mapOf() }
gpl-3.0
7fd4bc5a16baf0feb383629381393571
39.247059
119
0.670564
4.352417
false
false
false
false
ACRA/acra
acra-core/src/main/java/org/acra/data/CrashReportData.kt
1
4835
/* * Copyright (c) 2017 * * 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.acra.data import org.acra.ACRAConstants import org.acra.ReportField import org.acra.log.warn import org.json.JSONArray import org.json.JSONException import org.json.JSONObject /** * Stores a crash report data */ class CrashReportData { private val content: JSONObject constructor() { content = JSONObject() } constructor(json: String) { content = JSONObject(json) } @Synchronized fun put(key: String, value: Boolean) { try { content.put(key, value) } catch (e: JSONException) { warn { "Failed to put value into CrashReportData: $value" } } } @Synchronized fun put(key: String, value: Double) { try { content.put(key, value) } catch (e: JSONException) { warn { "Failed to put value into CrashReportData: $value" } } } @Synchronized fun put(key: String, value: Int) { try { content.put(key, value) } catch (e: JSONException) { warn { "Failed to put value into CrashReportData: $value" } } } @Synchronized fun put(key: String, value: Long) { try { content.put(key, value) } catch (e: JSONException) { warn { "Failed to put value into CrashReportData: $value" } } } @Synchronized fun put(key: String, value: String?) { if (value == null) { putNA(key) return } try { content.put(key, value) } catch (e: JSONException) { warn { "Failed to put value into CrashReportData: $value" } } } @Synchronized fun put(key: String, value: JSONObject?) { if (value == null) { putNA(key) return } try { content.put(key, value) } catch (e: JSONException) { warn { "Failed to put value into CrashReportData: $value" } } } @Synchronized fun put(key: String, value: JSONArray?) { if (value == null) { putNA(key) return } try { content.put(key, value) } catch (e: JSONException) { warn { "Failed to put value into CrashReportData: $value" } } } @Synchronized fun put(key: ReportField, value: Boolean) { put(key.toString(), value) } @Synchronized fun put(key: ReportField, value: Double) { put(key.toString(), value) } @Synchronized fun put(key: ReportField, value: Int) { put(key.toString(), value) } @Synchronized fun put(key: ReportField, value: Long) { put(key.toString(), value) } @Synchronized fun put(key: ReportField, value: String?) { put(key.toString(), value) } @Synchronized fun put(key: ReportField, value: JSONObject?) { put(key.toString(), value) } @Synchronized fun put(key: ReportField, value: JSONArray?) { put(key.toString(), value) } private fun putNA(key: String) { try { content.put(key, ACRAConstants.NOT_AVAILABLE) } catch (ignored: JSONException) { } } /** * Returns the property with the specified key. * * @param key the key of the property to find. * @return the keyd property value, or `null` if it can't be found. */ fun getString(key: ReportField): String? { return content.optString(key.toString()) } operator fun get(key: String): Any? { return content.opt(key) } fun containsKey(key: String): Boolean { return content.has(key) } fun containsKey(key: ReportField): Boolean { return containsKey(key.toString()) } @Throws(JSONException::class) fun toJSON(): String { return try { StringFormat.JSON.toFormattedString(this, emptyList(), "", "", false) } catch (e: JSONException) { throw e } catch (e: Exception) { throw JSONException(e.message) } } fun toMap(): Map<String, Any?> { return content.keys().asSequence().map { it to get(it) }.toMap() } }
apache-2.0
af2a6bec67aed703791d8b6f45172b44
24.1875
81
0.569804
4.12895
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/LibraryFilesPackagingElementEntityImpl.kt
2
12087
// 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.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.SymbolicEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.SoftLinkable import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class LibraryFilesPackagingElementEntityImpl(val dataSource: LibraryFilesPackagingElementEntityData) : LibraryFilesPackagingElementEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val parentEntity: CompositePackagingElementEntity? get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) override val library: LibraryId? get() = dataSource.library override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: LibraryFilesPackagingElementEntityData?) : ModifiableWorkspaceEntityBase<LibraryFilesPackagingElementEntity, LibraryFilesPackagingElementEntityData>( result), LibraryFilesPackagingElementEntity.Builder { constructor() : this(LibraryFilesPackagingElementEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity LibraryFilesPackagingElementEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as LibraryFilesPackagingElementEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.library != dataSource?.library) this.library = dataSource.library if (parents != null) { val parentEntityNew = parents.filterIsInstance<CompositePackagingElementEntity?>().singleOrNull() if ((parentEntityNew == null && this.parentEntity != null) || (parentEntityNew != null && this.parentEntity == null) || (parentEntityNew != null && this.parentEntity != null && (this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id)) { this.parentEntity = parentEntityNew } } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var parentEntity: CompositePackagingElementEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override var library: LibraryId? get() = getEntityData().library set(value) { checkModificationAllowed() getEntityData(true).library = value changedProperty.add("library") } override fun getEntityClass(): Class<LibraryFilesPackagingElementEntity> = LibraryFilesPackagingElementEntity::class.java } } class LibraryFilesPackagingElementEntityData : WorkspaceEntityData<LibraryFilesPackagingElementEntity>(), SoftLinkable { var library: LibraryId? = null override fun getLinks(): Set<SymbolicEntityId<*>> { val result = HashSet<SymbolicEntityId<*>>() val optionalLink_library = library if (optionalLink_library != null) { result.add(optionalLink_library) } return result } override fun index(index: WorkspaceMutableIndex<SymbolicEntityId<*>>) { val optionalLink_library = library if (optionalLink_library != null) { index.index(this, optionalLink_library) } } override fun updateLinksIndex(prev: Set<SymbolicEntityId<*>>, index: WorkspaceMutableIndex<SymbolicEntityId<*>>) { // TODO verify logic val mutablePreviousSet = HashSet(prev) val optionalLink_library = library if (optionalLink_library != null) { val removedItem_optionalLink_library = mutablePreviousSet.remove(optionalLink_library) if (!removedItem_optionalLink_library) { index.index(this, optionalLink_library) } } for (removed in mutablePreviousSet) { index.remove(this, removed) } } override fun updateLink(oldLink: SymbolicEntityId<*>, newLink: SymbolicEntityId<*>): Boolean { var changed = false var library_data_optional = if (library != null) { val library___data = if (library!! == oldLink) { changed = true newLink as LibraryId } else { null } library___data } else { null } if (library_data_optional != null) { library = library_data_optional } return changed } override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<LibraryFilesPackagingElementEntity> { val modifiable = LibraryFilesPackagingElementEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): LibraryFilesPackagingElementEntity { return getCached(snapshot) { val entity = LibraryFilesPackagingElementEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return LibraryFilesPackagingElementEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return LibraryFilesPackagingElementEntity(entitySource) { this.library = [email protected] this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as LibraryFilesPackagingElementEntityData if (this.entitySource != other.entitySource) return false if (this.library != other.library) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as LibraryFilesPackagingElementEntityData if (this.library != other.library) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + library.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + library.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.add(LibraryTableId::class.java) collector.add(LibraryTableId.ModuleLibraryTableId::class.java) collector.add(ModuleId::class.java) collector.add(LibraryTableId.GlobalLibraryTableId::class.java) collector.add(LibraryId::class.java) collector.addObject(LibraryTableId.ProjectLibraryTableId::class.java) collector.sameForAllEntities = true } }
apache-2.0
6c714f693baa05190bd0427f948028eb
38.243506
281
0.710929
5.534341
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsProcessor.kt
1
9524
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.cutPaste import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiManager import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.suggested.range import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeInsight.shorten.runRefactoringAndKeepDelayedRequests import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.refactoring.cutPaste.MoveDeclarationsTransferableData.Companion.STUB_RENDERER import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.* import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.idea.util.getSourceRoot import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset class MoveDeclarationsProcessor( val project: Project, private val sourceContainer: KtDeclarationContainer, private val targetPsiFile: KtFile, val pastedDeclarations: List<KtNamedDeclaration>, private val imports: List<String>, private val sourceDeclarationsText: List<String> ) { companion object { fun build(editor: Editor, cookie: MoveDeclarationsEditorCookie): MoveDeclarationsProcessor? { val data = cookie.data val project = editor.project ?: return null val range = cookie.bounds.range ?: return null val sourceFileUrl = data.sourceFileUrl val sourceFile = VirtualFileManager.getInstance().findFileByUrl(sourceFileUrl) ?: return null if (sourceFile.getSourceRoot(project) == null) return null val psiDocumentManager = PsiDocumentManager.getInstance(project) psiDocumentManager.commitAllDocuments() val targetPsiFile = psiDocumentManager.getPsiFile(editor.document) as? KtFile ?: return null if (targetPsiFile.virtualFile.getSourceRoot(project) == null) return null val sourcePsiFile = PsiManager.getInstance(project).findFile(sourceFile) as? KtFile ?: return null val sourceObject = data.sourceObjectFqName?.let { fqName -> sourcePsiFile.findDescendantOfType<KtObjectDeclaration> { it.fqName?.asString() == fqName } ?: return null } val sourceContainer: KtDeclarationContainer = sourceObject ?: sourcePsiFile if (targetPsiFile == sourceContainer) return null val declarations = MoveDeclarationsCopyPasteProcessor.rangeToDeclarations(targetPsiFile, range.startOffset, range.endOffset) if (declarations.isEmpty() || declarations.any { it.parent !is KtFile }) return null if (sourceContainer == sourcePsiFile && sourcePsiFile.packageFqName == targetPsiFile.packageFqName) return null // check that declarations were cut (not copied) if (sourceContainer.declarations.any { declaration -> declaration.text in data.declarationTexts }) { return null } return MoveDeclarationsProcessor( project, sourceContainer, targetPsiFile, declarations, data.imports, data.declarationTexts ) } } private val sourcePsiFile = (sourceContainer as KtElement).containingKtFile private val psiDocumentManager = PsiDocumentManager.getInstance(project) private val sourceDocument = psiDocumentManager.getDocument(sourcePsiFile)!! fun performRefactoring() { psiDocumentManager.commitAllDocuments() val commandName = KotlinBundle.message("action.usage.update.command") val commandGroupId = Any() // we need to group both commands for undo // temporary revert imports to the state before they have been changed val importsSubstitution = if (sourcePsiFile.importDirectives.size != imports.size) { val startOffset = sourcePsiFile.importDirectives.minOfOrNull { it.startOffset } ?: 0 val endOffset = sourcePsiFile.importDirectives.minOfOrNull { it.endOffset } ?: 0 val importsDeclarationsText = sourceDocument.getText(TextRange(startOffset, endOffset)) val tempImportsText = imports.joinToString(separator = "\n") project.executeWriteCommand(commandName, commandGroupId) { sourceDocument.deleteString(startOffset, endOffset) sourceDocument.insertString(startOffset, tempImportsText) } psiDocumentManager.commitDocument(sourceDocument) ImportsSubstitution(importsDeclarationsText, tempImportsText, startOffset) } else { null } val tmpRangeAndDeclarations = insertStubDeclarations(commandName, commandGroupId, sourceDeclarationsText) assert(tmpRangeAndDeclarations.second.size == pastedDeclarations.size) val stubTexts = tmpRangeAndDeclarations.second.map { STUB_RENDERER.render(it.unsafeResolveToDescriptor()) } project.executeWriteCommand(commandName, commandGroupId) { sourceDocument.deleteString(tmpRangeAndDeclarations.first.startOffset, tmpRangeAndDeclarations.first.endOffset) } psiDocumentManager.commitDocument(sourceDocument) val stubRangeAndDeclarations = insertStubDeclarations(commandName, commandGroupId, stubTexts) val stubDeclarations = stubRangeAndDeclarations.second assert(stubDeclarations.size == pastedDeclarations.size) importsSubstitution?.let { project.executeWriteCommand(commandName, commandGroupId) { sourceDocument.deleteString(it.startOffset, it.startOffset + it.tempImportsText.length) sourceDocument.insertString(it.startOffset, it.originalImportsText) } psiDocumentManager.commitDocument(sourceDocument) } val mover = object : Mover { override fun invoke(declaration: KtNamedDeclaration, targetContainer: KtElement): KtNamedDeclaration { val index = stubDeclarations.indexOf(declaration) assert(index >= 0) declaration.delete() return pastedDeclarations[index] } } val declarationProcessor = MoveKotlinDeclarationsProcessor( MoveDeclarationsDescriptor( moveSource = MoveSource(stubDeclarations), moveTarget = KotlinMoveTargetForExistingElement(targetPsiFile), delegate = MoveDeclarationsDelegate.TopLevel, project = project ), mover ) val declarationUsages = project.runSynchronouslyWithProgress(RefactoringBundle.message("progress.text"), true) { runReadAction { declarationProcessor.findUsages().toList() } } ?: return project.executeWriteCommand(commandName, commandGroupId) { project.runRefactoringAndKeepDelayedRequests { declarationProcessor.execute(declarationUsages) } psiDocumentManager.doPostponedOperationsAndUnblockDocument(sourceDocument) val insertedStubRange = stubRangeAndDeclarations.first assert(insertedStubRange.isValid) sourceDocument.deleteString(insertedStubRange.startOffset, insertedStubRange.endOffset) } } private data class ImportsSubstitution(val originalImportsText: String, val tempImportsText: String, val startOffset: Int) private fun insertStubDeclarations( @NlsContexts.Command commandName: String, commandGroupId: Any?, values: List<String> ): Pair<RangeMarker, List<KtNamedDeclaration>> { val insertedRange = project.executeWriteCommand(commandName, commandGroupId) { val insertionOffset = sourceContainer.declarations.firstOrNull()?.startOffset ?: when (sourceContainer) { is KtFile -> sourceContainer.textLength is KtObjectDeclaration -> sourceContainer.getBody()?.rBrace?.startOffset ?: sourceContainer.endOffset else -> error("Unknown sourceContainer: $sourceContainer") } val textToInsert = "\n//start\n\n${values.joinToString(separator = "\n")}\n//end\n" sourceDocument.insertString(insertionOffset, textToInsert) sourceDocument.createRangeMarker(TextRange(insertionOffset, insertionOffset + textToInsert.length)) } psiDocumentManager.commitDocument(sourceDocument) val declarations = MoveDeclarationsCopyPasteProcessor.rangeToDeclarations( sourcePsiFile, insertedRange.startOffset, insertedRange.endOffset ) return Pair(insertedRange, declarations) } }
apache-2.0
d5c8cb897f9a6703da96f8e88086a0b2
47.350254
158
0.707161
5.835784
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/service/webrtc/AndroidCallConnection.kt
1
3436
package org.thoughtcrime.securesms.service.webrtc import android.content.Context import android.content.Intent import android.telecom.CallAudioState import android.telecom.Connection import androidx.annotation.RequiresApi import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.WebRtcCallActivity import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.permissions.Permissions import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.webrtc.CallNotificationBuilder import org.thoughtcrime.securesms.webrtc.audio.AudioManagerCommand import org.thoughtcrime.securesms.webrtc.audio.SignalAudioManager /** * Signal implementation for the telecom system connection. Provides an interaction point for the system to * inform us about changes in the telecom system. Created and returned by [AndroidCallConnectionService]. */ @RequiresApi(26) class AndroidCallConnection(private val context: Context, val recipientId: RecipientId, val isOutgoing: Boolean = false) : Connection() { init { connectionProperties = PROPERTY_SELF_MANAGED connectionCapabilities = CAPABILITY_SUPPORTS_VT_LOCAL_BIDIRECTIONAL or CAPABILITY_SUPPORTS_VT_REMOTE_BIDIRECTIONAL or CAPABILITY_MUTE } override fun onShowIncomingCallUi() { Log.i(TAG, "onShowIncomingCallUi()") WebRtcCallService.update(context, CallNotificationBuilder.TYPE_INCOMING_CONNECTING, recipientId) setRinging() } override fun onCallAudioStateChanged(state: CallAudioState) { Log.i(TAG, "onCallAudioStateChanged($state)") val activeDevice = state.route.toDevices().firstOrNull() ?: SignalAudioManager.AudioDevice.EARPIECE val availableDevices = state.supportedRouteMask.toDevices() ApplicationDependencies.getSignalCallManager().onAudioDeviceChanged(activeDevice, availableDevices) } override fun onAnswer(videoState: Int) { Log.i(TAG, "onAnswer($videoState)") if (Permissions.hasAll(context, android.Manifest.permission.RECORD_AUDIO)) { ApplicationDependencies.getSignalCallManager().acceptCall(false) } else { val intent = Intent(context, WebRtcCallActivity::class.java) intent.action = WebRtcCallActivity.ANSWER_ACTION intent.flags = intent.flags or Intent.FLAG_ACTIVITY_NEW_TASK context.startActivity(intent) } } override fun onSilence() { WebRtcCallService.sendAudioManagerCommand(context, AudioManagerCommand.SilenceIncomingRinger()) } override fun onReject() { Log.i(TAG, "onReject()") WebRtcCallService.denyCall(context) } override fun onDisconnect() { Log.i(TAG, "onDisconnect()") WebRtcCallService.hangup(context) } companion object { private val TAG: String = Log.tag(AndroidCallConnection::class.java) } } private fun Int.toDevices(): Set<SignalAudioManager.AudioDevice> { val devices = mutableSetOf<SignalAudioManager.AudioDevice>() if (this and CallAudioState.ROUTE_BLUETOOTH != 0) { devices += SignalAudioManager.AudioDevice.BLUETOOTH } if (this and CallAudioState.ROUTE_EARPIECE != 0) { devices += SignalAudioManager.AudioDevice.EARPIECE } if (this and CallAudioState.ROUTE_WIRED_HEADSET != 0) { devices += SignalAudioManager.AudioDevice.WIRED_HEADSET } if (this and CallAudioState.ROUTE_SPEAKER != 0) { devices += SignalAudioManager.AudioDevice.SPEAKER_PHONE } return devices }
gpl-3.0
b32b3711c60209e9f8fff66cf136d133
34.42268
137
0.77532
4.439276
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/page/StoryViewerPlaybackState.kt
1
1508
package org.thoughtcrime.securesms.stories.viewer.page data class StoryViewerPlaybackState( val areSegmentsInitialized: Boolean = false, val isUserTouching: Boolean = false, val isDisplayingForwardDialog: Boolean = false, val isDisplayingDeleteDialog: Boolean = false, val isDisplayingContextMenu: Boolean = false, val isDisplayingViewsAndRepliesDialog: Boolean = false, val isDisplayingDirectReplyDialog: Boolean = false, val isDisplayingCaptionOverlay: Boolean = false, val isUserScrollingParent: Boolean = false, val isSelectedPage: Boolean = false, val isDisplayingSlate: Boolean = false, val isFragmentResumed: Boolean = false, val isDisplayingLinkPreviewTooltip: Boolean = false, val isDisplayingReactionAnimation: Boolean = false, val isRunningSharedElementAnimation: Boolean = false ) { val hideChromeImmediate: Boolean = isRunningSharedElementAnimation val hideChrome: Boolean = isRunningSharedElementAnimation || isUserTouching val isPaused: Boolean = !areSegmentsInitialized || isUserTouching || isDisplayingCaptionOverlay || isDisplayingForwardDialog || isDisplayingDeleteDialog || isDisplayingContextMenu || isDisplayingViewsAndRepliesDialog || isDisplayingDirectReplyDialog || isDisplayingCaptionOverlay || isUserScrollingParent || !isSelectedPage || isDisplayingSlate || !isFragmentResumed || isDisplayingLinkPreviewTooltip || isDisplayingReactionAnimation || isRunningSharedElementAnimation }
gpl-3.0
63eb15ab08d6bb7efc29b6fe9ed38b50
36.7
77
0.785809
4.976898
false
false
false
false
DeskChan/DeskChan
src/main/kotlin/info/deskchan/external_loader/ExternalPlugin.kt
2
12986
package info.deskchan.external_loader import info.deskchan.core.* import info.deskchan.external_loader.streams.ExternalStream import info.deskchan.external_loader.streams.HTTPStream import info.deskchan.external_loader.streams.ProcessIOStream import info.deskchan.external_loader.wrappers.InlineMessageWrapper import info.deskchan.external_loader.wrappers.JSONMessageWrapper import info.deskchan.external_loader.wrappers.MessageWrapper import org.json.JSONException import java.io.File import java.io.IOException import java.security.InvalidKeyException import java.util.* class ExternalPlugin(private val pluginFile: File) : Plugin { private lateinit var pluginProxy: PluginProxyInterface private lateinit var processThread: Thread private lateinit var stream: ExternalStream private lateinit var wrapper: MessageWrapper private var ping = 200L private var messagesToWrite = mutableListOf<MessageWrapper.Message>() private var messagesLock = Any() override fun initialize(pluginProxy: PluginProxyInterface):Boolean { this.pluginProxy = pluginProxy //println("type: "+pluginProxy.getConfigField("type")) when(pluginProxy.getConfigField("type")){ "Python" -> { var pip = "pip"; if (pluginFile.absolutePath.endsWith(".py2")) { stream = ProcessIOStream(pluginFile, "python2") pip = "pip2" } else if (pluginFile.absolutePath.endsWith(".py3")) { stream = ProcessIOStream(pluginFile, "python3") pip = "pip3" } else { stream = ProcessIOStream(pluginFile, "python") } val deps = pluginProxy.getConfigField("python-dependencies") if (deps != null && deps is List<*>){ val deps = deps.toMutableList() deps.replaceAll { t -> t.toString().toLowerCase() } ProcessIOStream.getInstalledLibs(pip).forEach { val lib = it.split(" ")[0].toLowerCase() for (dep in deps){ if (lib == dep){ deps.remove(dep) break } } if (deps.isEmpty()) return@forEach } if (deps.isNotEmpty()){ pluginProxy.log(Exception("Python dependencies not satisfied: " + deps.toString() + " not installed by pip. Remove 'python-dependencies' inside plugin manifest to discard this exception.")) return false } } wrapper = InlineMessageWrapper() } "HttpServer" -> { val file = Properties() file.load(pluginFile.reader()) ping = file.getProperty("delay", ping.toString()).toLong() wrapper = JSONMessageWrapper() stream = HTTPStream( file.getProperty("ip"), file.getProperty("port", "3640").toInt(), file.getProperty("context", "/"), file.getProperty("key", null), wrapper ) } else -> return false } try { stream.start() pluginProxy.log("Started "+stream.toString()) stream.write(MessageWrapper.Message( "setInfo", mutableListOf(), mutableMapOf( "id" to pluginProxy.getId(), "dataDirPath" to pluginProxy.dataDirPath.absolutePath.toString(), "pluginDirPath" to pluginProxy.pluginDirPath.absolutePath.toString(), "assetsDirPath" to pluginProxy.assetsDirPath.absolutePath.toString(), "rootDirPath" to pluginProxy.rootDirPath.absolutePath.toString(), "locale" to CoreInfo.getCoreProperties().getString("locale") ) ), wrapper) } catch (e: IOException){ if (stream.canReadError()){ val error = stream.readError() pluginProxy.log(Exception(error)) } else { pluginProxy.log(IOException("Cannot run external plugin of type " + pluginProxy.getConfigField("type") + ": " + e.message, e)) } return false } processThread = Thread{ activated = true checkThread() } processThread.name = pluginProxy.getId() + " plugin thread" processThread.start() return true } private var activated = false private fun checkThread() { while (activated){ if (!stream.canRead() && !stream.canReadError()) { if (!stream.isAlive()) { pluginProxy.log(Exception("Process stopped working by unknown reason")) return } if (messagesToWrite.size == 0) { Thread.sleep(ping) continue } } if (messagesToWrite.size > 0) { synchronized(messagesLock) { stream.write(messagesToWrite[0], wrapper) messagesToWrite.removeAt(0) } Thread.sleep(ping) continue } var message : MessageWrapper.Message try { //println("waiting for another message") message = stream.read(wrapper) //println("==== got: "+message.type) } catch (e: IOException){ //println("breaking with exception "+e) val error = stream.readError() pluginProxy.log(Exception(error)) break } catch (e: InvalidKeyException){ pluginProxy.log(e) continue } catch (e: JSONException){ pluginProxy.log(e) continue } catch (e: Throwable){ pluginProxy.log(e) break } try { when (message.type) { "sendMessage" -> { val result: Any val args = message.requiredArguments val msg = args[0].toString() val ret = message.additionalArguments["return"]?.toString() val resp = message.additionalArguments["response"]?.toString() val data = args[1] if (resp != null) { if (ret != null) result = pluginProxy.sendMessage(msg, data, ExternListener(resp), ExternListener(ret)) else result = pluginProxy.sendMessage(msg, data, ExternListener(resp)) } else result = pluginProxy.sendMessage(msg, data) confirm(result) } "callNextAlternative" -> { pluginProxy.callNextAlternative( message.getRequiredAsString(0), message.getRequiredAsString(1), message.getRequiredAsString(2), message.requiredArguments[3] ) confirm(null) } "addMessageListener" -> { pluginProxy.addMessageListener( message.getRequiredAsString(0), ExternListener(message.getRequiredAsString(1)) ) confirm(null) } "removeMessageListener" -> { val id = message.getRequiredAsString(1) if (id in listeners) pluginProxy.addMessageListener( message.getRequiredAsString(0), listeners.remove(id)!! ) confirm(null) } "setTimer" -> { val listener = ExternListener(message.getRequiredAsString(2), false) val r = pluginProxy.setTimer( message.getRequiredAsLong(0), message.getRequiredAsInt(1), listener ) listeners["timer" + r] = listener confirm(r) } "cancelTimer" -> { val id = message.getRequiredAsInt(0) pluginProxy.cancelTimer(id) listeners.remove("timer" + id) confirm(null) } "setAlternative" -> { pluginProxy.setAlternative( message.getRequiredAsString(0), message.getRequiredAsString(1), message.getRequiredAsInt(2) ) confirm(null) } "deleteAlternative" -> { pluginProxy.deleteAlternative( message.getRequiredAsString(0), message.getRequiredAsString(1) ) confirm(null) } "setProperty" -> { val last = when (message.requiredArguments[1]) { null -> pluginProxy.getProperties().remove(message.getRequiredAsString(0)) else -> pluginProxy.getProperties().put( message.getRequiredAsString(0), message.requiredArguments[1]!! ) } confirm(last) } "getProperty" -> { val ret = pluginProxy.getProperties().get( message.getRequiredAsString(0) ) confirm(ret) } "setConfigField" -> { val last = pluginProxy.setConfigField( message.getRequiredAsString(0), message.requiredArguments[1]!! ) confirm(last) } "getConfigField" -> { val ret = pluginProxy.getConfigField( message.getRequiredAsString(0) ) confirm(ret) } "getString" -> { val ret = pluginProxy.getString( message.getRequiredAsString(0) ) confirm(ret) } "log" -> { pluginProxy.log( message.getRequiredAsString(0) ) confirm(null) } "error" -> { pluginProxy.sendMessage("core-events:error", mapOf( "class" to message.additionalArguments.getOrDefault("class", "Error"), "message" to message.getRequiredAsString(0), "stacktrace" to message.additionalArguments.getOrDefault("stacktrace", listOf("No traceback specified")) )) confirm(null) } "initializationCompleted" -> { pluginProxy.log("Client initialization confirmed") confirm(null) } } } catch (e: Throwable){ pluginProxy.log(e) } } } fun confirm(data: Any?){ if (!stream.isAlive()) return val message = when (data){ null, Unit -> MessageWrapper.Message("confirm") else -> MessageWrapper.Message("confirm", mutableListOf(data)) } stream.write(message, wrapper) } override fun unload(){ activated = false stream.write(MessageWrapper.Message("unload"), wrapper) pluginProxy.log("Waiting for process exit") stream.close() pluginProxy.getProperties().save() } /* Handling messages */ val listeners = mutableMapOf<String, ExternListener>() open inner class ExternListener : ResponseListener, MessageListener { protected val seq:String constructor(seq:String, add:Boolean = true) { this.seq = seq if (add) listeners[seq] = this } override fun handle(sender:String, data: Any?){ val message = MessageWrapper.Message( "call", mutableListOf(seq, sender, data) ) synchronized(messagesLock) { messagesToWrite.add(message) } } override fun handleMessage(sender: String?, tag: String?, data: Any?) { val message = MessageWrapper.Message( "call", mutableListOf(seq, sender, data), mutableMapOf("tag" to tag) ) synchronized(messagesLock) { messagesToWrite.add(message) } } } }
lgpl-3.0
49a74974a8544e031c0a27254c23322c
35.378151
207
0.496535
5.619212
false
false
false
false
abertschi/ad-free
app/src/main/java/ch/abertschi/adfree/view/mod/GenericTextDetectorPresenter.kt
1
1551
package ch.abertschi.adfree.view.mod import android.content.Context import android.content.Intent import android.net.Uri import ch.abertschi.adfree.AdFreeApplication import ch.abertschi.adfree.model.TextRepository import ch.abertschi.adfree.model.TextRepositoryData class GenericTextDetectorPresenter(val ctx: Context, val view: GenericTextDetectorActivity) { private var data: ArrayList<TextRepositoryData> private var textRepository: TextRepository init { var app = ctx.applicationContext as AdFreeApplication textRepository = app.textRepository data = textRepository.getAllEntries() } fun getData(): List<TextRepositoryData> { return data; } fun addNewEntry(): TextRepositoryData { var d = textRepository.createNewEntry() data.add(d) textRepository.updateEntry(d) view.insertData() return d } fun updateEntry(d: TextRepositoryData) { if (data.contains(d)){ textRepository.updateEntry(d) } } fun deleteEntry(d: TextRepositoryData) { textRepository.removeEntry(d) data.remove(d) view.insertData() } fun browseHelp() { val url = "https://abertschi.github.io/ad-free/troubleshooting/troubleshooting.html#generic-text-detector" val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) this.view.startActivity(browserIntent) } fun onMoreClicked(entry: TextRepositoryData) { view.showOptionDialog(entry) } }
apache-2.0
09fa332319728691648ff84b7578332b
27.218182
114
0.688588
4.249315
false
false
false
false
mistapostle/HSSBC
core/src/main/kotlin/com/appspot/mistapostle/hssbc/core/BCSystem.kt
1
3833
package com.appspot.mistapostle.hssbc.core import com.appspot.mistapostle.hssbc.core.model.Block import com.appspot.mistapostle.hssbc.core.model.Transaction import com.appspot.mistapostle.hssbc.core.model.TransactionHeader import com.appspot.mistapostle.hssbc.core.model.UnsignedTransation import com.google.common.base.Preconditions import com.google.common.base.Preconditions.checkArgument import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableMap import com.google.common.hash.HashFunction import com.google.common.hash.Hashing import com.google.common.io.BaseEncoding import java.nio.charset.Charset import java.security.* import java.security.spec.PKCS8EncodedKeySpec import com.oracle.util.Checksums.update /** * Created by mistapostle on 17/7/30. * BC System is the base of the while system, one should config the system as first thing to statup the system */ private fun simpleSign(transation: UnsignedTransation, signerPrivateKeys:ImmutableList<String>) : Transaction{ checkArgument(transation.signerPublicKeys.size == signerPrivateKeys.size , "size of signerPublicKeys and size of signerPrivateKeys are not matched : " + "${transation.signerPublicKeys.size} != ${ signerPrivateKeys.size}") val sb = StringBuilder() val publicKeysStr = transation.signerPublicKeys.joinToString(",") val signContent = "${transation.version} $publicKeysStr ${transation.content}".toByteArray(Charsets.UTF_8) for( privateKey in signerPrivateKeys){ val signature = Signature.getInstance("SHA256withRSA") val pkcs8EncodedBytes = BaseEncoding.base64().decode(privateKey) val keySpec = PKCS8EncodedKeySpec(pkcs8EncodedBytes) val kf = KeyFactory.getInstance("RSA") val privKey = kf.generatePrivate(keySpec) signature.initSign(privKey, SecureRandom()) signature.update(signContent) val sigBytes = signature.sign( ) sb.append(BaseEncoding.base64().encode(sigBytes)) sb.append("\r\n") //signature.initVerify(keyPair.getPublic()) //signature.update(message) // System.out.println(signature.verify(sigBytes)) } return transation.toTransation(sb.toString()) } object BCSystem{ private var hashFunction: HashFunction = Hashing.sha512() private var powFuncton: (Block)-> Boolean = { block -> val h = Math.abs( hashAsLong(block.header.pow + block.header.version + block.id)) %2 ; println("h=$h") ; h ==0L } private var signatureFunction : (transation: UnsignedTransation, signerPrivateKeys:ImmutableList<String>) -> Transaction = ::simpleSign // { transation, signerPrivateKeys -> simpleSign(transation,signerPrivateKeys) } fun config( options : ImmutableMap<String, String>){ //TODO: config able hashing function etc // val hashMethod = options.get("hachMethod" ) // if ( hashMethod !=null) { // if (hashMethod !in arrayOf("sha512", "sha256")) { // throw IllegalArgumentException("Invalid hash method : ${hashMethod}") // } // hashFunction = Hashing.sha512() // } } fun hash(value : String ) : String { val hc = hashFunction.newHasher().putString(value, Charset.forName("UTF8")).hash() return BaseEncoding.base64().encode(hc.asBytes()) } //TODO: it seems this always return 0 or 1 fun hashAsLong(value : String ) : Long { val hc = hashFunction.newHasher().putString(value, Charset.forName("UTF8")).hash() return hc.asLong() } fun verifyPow(block:Block) : Boolean{ return powFuncton(block) } fun sign(transation: UnsignedTransation, signerPrivateKeys:ImmutableList<String>): Transaction { return signatureFunction(transation,signerPrivateKeys) } }
mit
1cef62e7f80f88e2b9025c9fc5c668bf
41.120879
220
0.709627
3.959711
false
false
false
false
syrop/GPS-Texter
texter/src/main/kotlin/pl/org/seva/texter/ui/SlidingTabStrip.kt
1
5049
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pl.org.seva.texter.ui import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.TypedValue import android.widget.LinearLayout internal class SlidingTabStrip(ctx: Context) : LinearLayout(ctx, null) { private val bottomBorderThickness: Int private val bottomBorderPaint: Paint private val selectedIndicatorThickness: Int private val selectedIndicatorPaint: Paint private var selectedPosition: Int = 0 private var selectionOffset: Float = 0.toFloat() private lateinit var customTabColorizer: (Any) -> Int init { setWillNotDraw(false) val density = resources.displayMetrics.density val outValue = TypedValue() context.theme.resolveAttribute(android.R.attr.colorForeground, outValue, true) val themeForegroundColor = outValue.data val defaultBottomBorderColor = setColorAlpha(themeForegroundColor) bottomBorderThickness = (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density).toInt() bottomBorderPaint = Paint() bottomBorderPaint.color = defaultBottomBorderColor selectedIndicatorThickness = (SELECTED_INDICATOR_THICKNESS_DIPS * density).toInt() selectedIndicatorPaint = Paint() } fun setCustomTabColorizer(customTabColorizer: (Any) -> Int) { this.customTabColorizer = customTabColorizer invalidate() } fun onViewPagerPageChanged(position: Int, positionOffset: Float) { selectedPosition = position selectionOffset = positionOffset invalidate() } override fun onDraw(canvas: Canvas) { val height = height val childCount = childCount val tabColorizer = customTabColorizer // Thick colored underline below the current selection if (childCount > 0) { val selectedTitle = getChildAt(selectedPosition) var left = selectedTitle.left var right = selectedTitle.right var color = tabColorizer.invoke(selectedPosition) if (selectionOffset > 0f && selectedPosition < getChildCount() - 1) { val nextColor = tabColorizer.invoke(selectedPosition + 1) if (color != nextColor) { color = blendColors(nextColor, color, selectionOffset) } // Draw the selection partway between the tabs val nextTitle = getChildAt(selectedPosition + 1) left = (selectionOffset * nextTitle.left + (1.0f - selectionOffset) * left).toInt() right = (selectionOffset * nextTitle.right + (1.0f - selectionOffset) * right).toInt() } selectedIndicatorPaint.color = color canvas.drawRect(left.toFloat(), (height - selectedIndicatorThickness).toFloat(), right.toFloat(), height.toFloat(), selectedIndicatorPaint) } // Thin underline along the entire bottom edge canvas.drawRect(0f, (height - bottomBorderThickness).toFloat(), width.toFloat(), height.toFloat(), bottomBorderPaint) } companion object { private const val DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0 private const val DEFAULT_BOTTOM_BORDER_COLOR_ALPHA: Byte = 0x26 private const val SELECTED_INDICATOR_THICKNESS_DIPS = 3 /** * Set the alpha value of the `color` to be the given `alpha` value. */ private fun setColorAlpha(color: Int): Int = Color.argb( DEFAULT_BOTTOM_BORDER_COLOR_ALPHA.toInt(), Color.red(color), Color.green(color), Color.blue(color)) /** * Blend `color1` and `color2` using the given ratio. * @param ratio of which to blend. 1.0 will return `color1`, 0.5 will give an even blend, * * 0.0 will return `color2`. */ private fun blendColors(color1: Int, color2: Int, ratio: Float): Int { val inverseRation = 1f - ratio val r = Color.red(color1) * ratio + Color.red(color2) * inverseRation val g = Color.green(color1) * ratio + Color.green(color2) * inverseRation val b = Color.blue(color1) * ratio + Color.blue(color2) * inverseRation return Color.rgb(r.toInt(), g.toInt(), b.toInt()) } } }
gpl-3.0
47d9f198b3a2cc05da38325f2ceb04f4
36.125
125
0.647653
4.602552
false
false
false
false
Kerooker/rpg-npc-generator
app/src/main/java/me/kerooker/rpgnpcgenerator/repository/model/random/npc/EnumGenerators.kt
1
6163
@file:Suppress("MagicNumber") package me.kerooker.rpgnpcgenerator.repository.model.random.npc import androidx.annotation.StringRes import me.kerooker.rpgnpcgenerator.R import kotlin.random.Random interface RandomDistributed { val distribution: Double } interface NamedResource { val nameResource: Int } enum class Age( @StringRes override val nameResource: Int, override val distribution: Double ) : RandomDistributed, NamedResource { Child(R.string.age_child, 5.0), Teenager(R.string.age_teenager, 10.0), YoungAdult(R.string.age_young_adult, 35.0), Adult(R.string.age_adult, 35.0), Old(R.string.age_old, 10.0), VeryOld(R.string.age_very_old, 5.0); companion object { fun distributedRandom() = values().toList().distributedRandom() fun random() = values().random() } } enum class Alignment( @StringRes override val nameResource: Int, override val distribution: Double ) : RandomDistributed, NamedResource { LawfulGood(R.string.alignment_lawful_good, 2.0), LawfulNeutral(R.string.alignment_lawful_neutral, 10.0), LawfulEvil(R.string.alignment_lawful_evil, 2.0), NeutralGood(R.string.alignment_neutral_good, 10.0), Neutral(R.string.alignment_neutral, 52.0), NeutralEvil(R.string.alignment_neutral_evil, 10.0), ChaoticGood(R.string.alignment_chaotic_good, 2.0), ChaoticNeutral(R.string.alignment_chaotic_neutral, 10.0), ChaoticEvil(R.string.alignment_chaotic_evil, 2.0); companion object { fun distributedRandom() = values().toList().distributedRandom() fun random() = values().random() } } enum class Gender( @StringRes override val nameResource: Int, override val distribution: Double ) : RandomDistributed, NamedResource { Male(R.string.gender_male, 50.0), Female(R.string.gender_female, 50.0); companion object { fun distributedRandom() = values().toList().distributedRandom() fun random() = values().random() } } interface Language : NamedResource { companion object { fun values(): List<Language> = CommonLanguage.values().toList() + ExoticLanguage.values().toList() fun random() = (CommonLanguage.values().toList() + ExoticLanguage.values()).random() as Language } } enum class CommonLanguage( @StringRes override val nameResource: Int ) : Language { Common(R.string.language_common), Dwarvish(R.string.language_dwarvish), Elvish(R.string.language_elvish), Giant(R.string.language_giant), Gnomish(R.string.language_gnomish), Goblin(R.string.language_goblin), Halfling(R.string.language_halfling), Orc(R.string.language_orc); companion object { fun random(excluding: List<Language>) = values().filter { it !in excluding }.random() } } enum class ExoticLanguage( @StringRes override val nameResource: Int ) : Language { Celestial(R.string.language_celestial), Abyssal(R.string.language_abyssal), Infernal(R.string.language_infernal), Druidic(R.string.language_druidic), Draconic(R.string.language_draconic); companion object { fun random(excluding: List<Language>) = values().filter { it !in excluding }.random() } } enum class Race( @StringRes override val nameResource: Int, override val distribution: Double, val racialLanguage: Language? ) : RandomDistributed, NamedResource { HillDwarf(R.string.race_hill_dwarf, 8.75, CommonLanguage.Dwarvish), MountainDwarf(R.string.race_mountain_dwarf, 8.75, CommonLanguage.Dwarvish), HighElf(R.string.race_high_elf, 5.84, CommonLanguage.Elvish), WoodElf(R.string.race_wood_elf, 5.83, CommonLanguage.Elvish), Drow(R.string.race_drow, 5.83, CommonLanguage.Elvish), StoutHalfling(R.string.race_stout_halfling, 8.75, CommonLanguage.Halfling), LightfootHalfling(R.string.race_lightfoot_halfling, 8.75, CommonLanguage.Halfling), Human(R.string.race_human, 17.5, null), Dragonborn(R.string.race_dragonborn, 6.0, ExoticLanguage.Draconic), ForestGnome(R.string.race_forest_gnome, 3.0, CommonLanguage.Gnomish), RockGnome(R.string.race_rock_gnome, 3.0, CommonLanguage.Gnomish), HalfElf(R.string.race_half_elf, 6.0, CommonLanguage.Elvish), HalfOrc(R.string.race_half_orc, 6.0, CommonLanguage.Orc), Tiefling(R.string.race_tiefling, 6.0, ExoticLanguage.Infernal); companion object { fun distributedRandom() = values().toList().distributedRandom() fun random() = values().random() } } enum class Sexuality( @StringRes override val nameResource: Int, override val distribution: Double ) : RandomDistributed, NamedResource { Homosexual(R.string.sexuality_homosexual, 2.0), Bisexual(R.string.sexuality_bisexual, 2.0), Asexual(R.string.sexuality_asexual, 1.0), Heterosexual(R.string.sexuality_heterosexual, 95.0); companion object { fun distributedRandom() = values().toList().distributedRandom() fun random() = values().random() } } // Code inspired from https://github.com/thomasnield/kotlin-statistics/blob/master/src/main/kotlin/org/nield/kotlinstatistics/Random.kt#L111 fun <T : RandomDistributed> List<T>.distributedRandom(): T { val probabilities = associateWith { it.distribution } val sum = probabilities.values.sum() val rangedDistribution = probabilities.run { var binStart = 0.0 asSequence().sortedBy { it.value } .map { it.key to OpenDoubleRange( binStart, it.value + binStart ) } .onEach { binStart = it.second.endExclusive } .toMap() } return Random.nextDouble(0.0, sum).let { rangedDistribution.asIterable().first { rng -> it in rng.value }.key } } private data class OpenDoubleRange(val start: Double, val endExclusive: Double) { operator fun contains(it: Double): Boolean { return it >= start && it < endExclusive } }
apache-2.0
946c8fc976252e1f26e209dae7701aee
29.969849
140
0.669966
3.479955
false
false
false
false
cdietze/klay
tripleklay/src/main/kotlin/tripleklay/ui/bgs/Scale9Background.kt
1
4196
package tripleklay.ui.bgs import klay.core.Surface import klay.core.Tile import klay.core.Tint import klay.scene.Layer import euklid.f.IDimension import tripleklay.ui.Background import tripleklay.ui.util.Scale9 /** * A background constructed by scaling the parts of a source image to fit the target width and * height. Uses [Scale9]. */ class Scale9Background /** Creates a new background using the given texture. The texture is assumed to be divided into * aa 3x3 grid of 9 equal pieces. */ (private var _tile: Tile) : Background() { private var _s9: Scale9 = Scale9(_tile.width, _tile.height) private var _destScale = 1f private var _tint = Tint.NOOP_TINT /** Returns the scale 9 instance for mutation. Be sure to finish mutation prior to binding. */ fun scale9(): Scale9 { return _s9 } /** Sets the width of the left and right edges of the source axes to the given value. NOTE: * `xborder` may be zero, to indicate that the source image has no left or right pieces, * i.e. just three total pieces: top, bottom and center. */ fun xborder(xborder: Float): Scale9Background { _s9.xaxis.resize(0, xborder) _s9.xaxis.resize(2, xborder) return this } /** Sets the height of the top and bottom edges of the source axes to the given value. NOTE: * `yborder` may be zero, to indicate that the source image has no top or bottom pieces, * i.e. just three pieces: left, right and center. */ fun yborder(yborder: Float): Scale9Background { _s9.yaxis.resize(0, yborder) _s9.yaxis.resize(2, yborder) return this } /** Sets all edges of the source axes to the given value. Equivalent of calling `xborder(border).yborder(border)`. */ fun corners(size: Float): Scale9Background { return xborder(size).yborder(size) } /** Sets an overall destination scale for the background. When instantiated, the target width * and height are divided by this value, and when rendering the layer scale is multiplied by * this value. This allows games to use high res images with smaller screen sizes. */ fun destScale(scale: Float): Scale9Background { _destScale = scale return this } override fun instantiate(size: IDimension): Background.Instance { return LayerInstance(size, object : Layer() { // The destination scale 9. internal var dest = Scale9(size.width / _destScale, size.height / _destScale, _s9) override fun paintImpl(surf: Surface) { surf.saveTx() surf.scale(_destScale, _destScale) val alpha = [email protected] if (alpha != null) surf.setAlpha(alpha) if (_tint != Tint.NOOP_TINT) surf.setTint(_tint) // issue the 9 draw calls for (yy in 0..2) for (xx in 0..2) { drawPart(surf, xx, yy) } if (alpha != null) surf.setAlpha(1f) // alpha is not part of save/restore surf.restoreTx() } private fun drawPart(surf: Surface, x: Int, y: Int) { val dw = dest.xaxis.size(x) val dh = dest.yaxis.size(y) if (dw == 0f || dh == 0f) return surf.draw(_tile, dest.xaxis.coord(x), dest.yaxis.coord(y), dw, dh, _s9.xaxis.coord(x), _s9.yaxis.coord(y), _s9.xaxis.size(x), _s9.yaxis.size(y)) } }) } /** * Sets the tint for this background, as `ARGB`. * * *NOTE:* this will overwrite any value configured via [.alpha]. Either * include your desired alpha in the high bits of `tint` or set [.alpha] after * calling this method. * * *NOTE:* the RGB components of a layer's tint only work on GL-based backends. It * is not possible to tint layers using the HTML5 canvas and Flash backends. */ fun setTint(tint: Int): Scale9Background { _tint = tint this.alpha = (tint shr 24 and 0xFF) / 255f return this } }
apache-2.0
311ae4176e9a4a9ab93df39994d9cc1e
36.132743
118
0.606053
3.870849
false
false
false
false
dahlstrom-g/intellij-community
plugins/git4idea/src/git4idea/index/GitStageLineStatusTracker.kt
8
35435
// 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 git4idea.index import com.intellij.diff.DiffApplicationSettings import com.intellij.diff.DiffContentFactory import com.intellij.diff.DiffManager import com.intellij.diff.comparison.ByWord import com.intellij.diff.comparison.ComparisonPolicy import com.intellij.diff.contents.DiffContent import com.intellij.diff.fragments.DiffFragment import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.diff.util.* import com.intellij.diff.util.DiffDrawUtil.InlineHighlighterBuilder import com.intellij.diff.util.DiffDrawUtil.LineHighlighterBuilder import com.intellij.ide.lightEdit.LightEditCompatible import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diff.DiffBundle import com.intellij.openapi.diff.LineStatusMarkerDrawUtil import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.markup.MarkupEditorFilter import com.intellij.openapi.editor.markup.MarkupEditorFilterFactory import com.intellij.openapi.editor.markup.RangeHighlighter import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.VerticalSeparatorComponent import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.ex.* import com.intellij.openapi.vcs.ex.Range import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.EditorTextField import com.intellij.ui.components.JBLabel import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.scale.JBUIScale import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.containers.PeekableIteratorWrapper import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import git4idea.GitUtil import git4idea.i18n.GitBundle import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import java.awt.* import java.util.* import javax.swing.* import kotlin.math.max class GitStageLineStatusTracker( override val project: Project, override val virtualFile: VirtualFile, override val document: Document ) : LocalLineStatusTracker<StagedRange> { override val vcsDocument: Document = LineStatusTrackerBase.createVcsDocument(document) var stagedDocument: Document = LineStatusTrackerBase.createVcsDocument(document) private set override val disposable: Disposable = Disposer.newDisposable() private val LOCK: DocumentTracker.Lock = DocumentTracker.Lock() private val blockOperations: LineStatusTrackerBlockOperations<StagedRange, StagedRange> = MyBlockOperations(LOCK) private val stagedBlockOperations: LineStatusTrackerBlockOperations<Range, BlockI> = MyStagedBlockOperations(LOCK) private val stagedTracker: DocumentTracker private val unstagedTracker: DocumentTracker override var isReleased: Boolean = false private set protected var isInitialized: Boolean = false private set private val renderer = MyLineStatusMarkerPopupRenderer(this) // FIXME override var mode: LocalLineStatusTracker.Mode = LocalLineStatusTracker.Mode(true, true, false) init { stagedTracker = DocumentTracker(vcsDocument, stagedDocument, LOCK) Disposer.register(disposable, stagedTracker) unstagedTracker = DocumentTracker(stagedDocument, document, LOCK) Disposer.register(disposable, unstagedTracker) stagedTracker.addHandler(MyDocumentTrackerHandler(false)) unstagedTracker.addHandler(MyDocumentTrackerHandler(true)) } @RequiresEdt fun setBaseRevision(vcsContent: CharSequence, newStagedDocument: Document) { ApplicationManager.getApplication().assertIsDispatchThread() if (isReleased) return if (stagedDocument != newStagedDocument) { stagedTracker.replaceDocument(Side.RIGHT, newStagedDocument) unstagedTracker.replaceDocument(Side.LEFT, newStagedDocument) stagedDocument = newStagedDocument } stagedTracker.doFrozen(Side.LEFT) { updateDocument(ThreeSide.LEFT, null) { vcsDocument.setText(vcsContent) } } if (!isInitialized) { isInitialized = true updateHighlighters() } } @RequiresEdt fun dropBaseRevision() { ApplicationManager.getApplication().assertIsDispatchThread() if (isReleased) return isInitialized = false updateHighlighters() } override fun release() { val runnable = Runnable { if (isReleased) return@Runnable isReleased = true Disposer.dispose(disposable) } if (!ApplicationManager.getApplication().isDispatchThread || LOCK.isHeldByCurrentThread) { ApplicationManager.getApplication().invokeLater(runnable) } else { runnable.run() } } @RequiresEdt private fun updateDocument(side: ThreeSide, commandName: @NlsContexts.Command String?, task: (Document) -> Unit): Boolean { val affectedDocument = side.selectNotNull(vcsDocument, stagedDocument, document) return LineStatusTrackerBase.updateDocument(project, affectedDocument, commandName, task) } private var cachedBlocks: List<StagedRange>? = null private val blocks: List<StagedRange> get() { var blocks = cachedBlocks if (blocks == null) { blocks = BlockMerger(stagedTracker.blocks, unstagedTracker.blocks).run() cachedBlocks = blocks } return blocks } private fun updateHighlighters() { renderer.scheduleUpdate() } override fun isOperational(): Boolean = LOCK.read { return isInitialized && !isReleased } override fun isValid(): Boolean = LOCK.read { isOperational() && !stagedTracker.isFrozen() && !unstagedTracker.isFrozen() } override fun getRanges(): List<StagedRange>? = blockOperations.getRanges() override fun findRange(range: Range): StagedRange? = blockOperations.findRange(range) override fun getNextRange(line: Int): StagedRange? = blockOperations.getNextRange(line) override fun getPrevRange(line: Int): StagedRange? = blockOperations.getPrevRange(line) override fun getRangesForLines(lines: BitSet): List<StagedRange>? = blockOperations.getRangesForLines(lines) override fun getRangeForLine(line: Int): StagedRange? = blockOperations.getRangeForLine(line) override fun isLineModified(line: Int): Boolean = blockOperations.isLineModified(line) override fun isRangeModified(startLine: Int, endLine: Int): Boolean = blockOperations.isRangeModified(startLine, endLine) override fun transferLineFromVcs(line: Int, approximate: Boolean): Int = blockOperations.transferLineFromVcs(line, approximate) override fun transferLineToVcs(line: Int, approximate: Boolean): Int = blockOperations.transferLineToVcs(line, approximate) fun transferLineFromLocalToStaged(line: Int, approximate: Boolean): Int = stagedBlockOperations.transferLineToVcs(line, approximate) fun transferLineFromStagedToLocal(line: Int, approximate: Boolean): Int = stagedBlockOperations.transferLineFromVcs(line, approximate) override fun scrollAndShowHint(range: Range, editor: Editor) { renderer.scrollAndShow(editor, range) } override fun showHint(range: Range, editor: Editor) { renderer.showAfterScroll(editor, range) } override fun <T> readLock(task: () -> T): T { LOCK.read { return task() } } override fun doFrozen(task: Runnable) { stagedTracker.doFrozen { unstagedTracker.doFrozen { task.run() } } } override fun freeze() { unstagedTracker.freeze(Side.LEFT) unstagedTracker.freeze(Side.RIGHT) stagedTracker.freeze(Side.LEFT) stagedTracker.freeze(Side.RIGHT) } override fun unfreeze() { unstagedTracker.unfreeze(Side.LEFT) unstagedTracker.unfreeze(Side.RIGHT) stagedTracker.unfreeze(Side.LEFT) stagedTracker.unfreeze(Side.RIGHT) } override fun rollbackChanges(range: Range) { val newRange = blockOperations.findBlock(range) ?: return runBulkRollback(listOf(newRange)) } override fun rollbackChanges(lines: BitSet) { val toRevert = blockOperations.getRangesForLines(lines) ?: return runBulkRollback(toRevert) } @RequiresEdt private fun runBulkRollback(toRevert: List<StagedRange>) { if (!isValid()) return val filter = BlockFilter.create(toRevert, Side.RIGHT) updateDocument(ThreeSide.RIGHT, GitBundle.message("stage.revert.unstaged.range.command.name")) { unstagedTracker.partiallyApplyBlocks(Side.RIGHT) { filter.matches(it) } } } fun stageChanges(range: Range) { val newRange = blockOperations.findBlock(range) ?: return runBulkStage(listOf(newRange)) } @RequiresEdt private fun runBulkStage(toRevert: List<StagedRange>) { if (!isValid()) return val filter = BlockFilter.create(toRevert, Side.RIGHT) updateDocument(ThreeSide.BASE, GitBundle.message("stage.add.range.command.name")) { unstagedTracker.partiallyApplyBlocks(Side.LEFT) { filter.matches(it) } } } fun unstageChanges(range: Range) { val newRange = blockOperations.findBlock(range) ?: return runBulkUnstage(listOf(newRange)) } @RequiresEdt private fun runBulkUnstage(toRevert: List<StagedRange>) { if (!isValid()) return val filter = BlockFilter.create(toRevert, Side.LEFT) updateDocument(ThreeSide.BASE, GitBundle.message("stage.revert.staged.range.command.name")) { stagedTracker.partiallyApplyBlocks(Side.RIGHT) { filter.matches(it) } } } private class BlockFilter(private val bitSet1: BitSet, private val bitSet2: BitSet) { fun matches(block: DocumentTracker.Block): Boolean { return matches(block, Side.LEFT, bitSet1) || matches(block, Side.RIGHT, bitSet2) } private fun matches(block: DocumentTracker.Block, blockSide: Side, bitSet: BitSet): Boolean { val start = blockSide.select(block.range.start1, block.range.start2) val end = blockSide.select(block.range.end1, block.range.end2) val next: Int = bitSet.nextSetBit(start) return next != -1 && next < end } companion object { fun create(ranges: List<StagedRange>, targetTracker: Side): BlockFilter { val bitSet1 = collectAffectedLines(ranges, targetTracker.selectNotNull(ThreeSide.LEFT, ThreeSide.BASE)) val bitSet2 = collectAffectedLines(ranges, targetTracker.selectNotNull(ThreeSide.BASE, ThreeSide.RIGHT)) return BlockFilter(bitSet1, bitSet2) } private fun collectAffectedLines(ranges: List<StagedRange>, side: ThreeSide): BitSet { return BitSet().apply { for (stagedRange in ranges) { val line1 = side.select(stagedRange.vcsLine1, stagedRange.stagedLine1, stagedRange.line1) val line2 = side.select(stagedRange.vcsLine2, stagedRange.stagedLine2, stagedRange.line2) this.set(line1, line2) } } } } } private inner class MyDocumentTrackerHandler(private val unstaged: Boolean) : DocumentTracker.Handler { override fun afterBulkRangeChange(isDirty: Boolean) { cachedBlocks = null updateHighlighters() if (isOperational()) { if (unstaged) { if (unstagedTracker.blocks.isEmpty()) { saveDocumentWhenUnchanged(project, document) } } else { if (stagedTracker.blocks.isEmpty()) { saveDocumentWhenUnchanged(project, stagedDocument) } } } } override fun onUnfreeze(side: Side) { updateHighlighters() } } private class MyLineStatusMarkerPopupRenderer(val tracker: GitStageLineStatusTracker) : LineStatusMarkerPopupRenderer(tracker) { override fun getEditorFilter(): MarkupEditorFilter? = MarkupEditorFilterFactory.createIsNotDiffFilter() override fun shouldPaintGutter(): Boolean { return tracker.mode.isVisible } override fun shouldPaintErrorStripeMarkers(): Boolean { return tracker.mode.isVisible && tracker.mode.showErrorStripeMarkers } override fun paint(editor: Editor, g: Graphics) { val ranges = tracker.getRanges() ?: return val blocks: List<ChangesBlock<StageLineFlags>> = VisibleRangeMerger.merge(editor, ranges, MyLineFlagProvider, g.clipBounds) for (block in blocks) { paintStageLines(g as Graphics2D, editor, block.changes) } } private fun paintStageLines(g: Graphics2D, editor: Editor, block: List<ChangedLines<StageLineFlags>>) { val borderColor = LineStatusMarkerDrawUtil.getGutterBorderColor(editor) val area = LineStatusMarkerDrawUtil.getGutterArea(editor) val x = area.first val endX = area.second val midX = (endX + x + 3) / 2 val y = block.first().y1 val endY = block.last().y2 for (change in block) { if (change.y1 != change.y2 && change.flags.isUnstaged) { val start = change.y1 val end = change.y2 val gutterColor = LineStatusMarkerDrawUtil.getGutterColor(change.type, editor) if (change.flags.isStaged) { LineStatusMarkerDrawUtil.paintRect(g, gutterColor, null, x, start, midX, end) } else { LineStatusMarkerDrawUtil.paintRect(g, gutterColor, null, x, start, endX, end) } } } if (borderColor == null) { for (change in block) { if (change.y1 != change.y2 && change.flags.isStaged) { val start = change.y1 val end = change.y2 val stagedBorderColor = LineStatusMarkerDrawUtil.getIgnoredGutterBorderColor(change.type, editor) LineStatusMarkerDrawUtil.paintRect(g, null, stagedBorderColor, x, start, endX, end) } } } else if (y != endY) { LineStatusMarkerDrawUtil.paintRect(g, null, borderColor, x, y, endX, endY) } for (change in block) { if (change.y1 == change.y2) { val start = change.y1 val gutterColor = LineStatusMarkerDrawUtil.getGutterColor(change.type, editor) val stagedBorderColor = borderColor ?: LineStatusMarkerDrawUtil.getIgnoredGutterBorderColor(change.type, editor) if (change.flags.isUnstaged && change.flags.isStaged) { paintStripeTriangle(g, editor, gutterColor, stagedBorderColor, x, endX, start) } else if (change.flags.isStaged) { LineStatusMarkerDrawUtil.paintTriangle(g, editor, null, stagedBorderColor, x, endX, start) } else { LineStatusMarkerDrawUtil.paintTriangle(g, editor, gutterColor, borderColor, x, endX, start) } } } } private fun paintStripeTriangle(g: Graphics2D, editor: Editor, color: Color?, borderColor: Color?, x1: Int, x2: Int, y: Int) { @Suppress("NAME_SHADOWING") var y = y val editorScale = if (editor is EditorImpl) editor.scale else 1.0f val size = JBUIScale.scale(5 * editorScale).toInt() if (y < size) y = size val xPoints = intArrayOf(x1, x1, x2) val yPointsBorder = intArrayOf(y - size, y + size, y) val yPointsFill = intArrayOf(y - size, y, y) if (color != null) { g.color = color g.fillPolygon(xPoints, yPointsFill, xPoints.size) } if (borderColor != null) { g.color = borderColor val oldStroke = g.stroke g.stroke = BasicStroke(JBUIScale.scale(1).toFloat()) g.drawPolygon(xPoints, yPointsBorder, xPoints.size) g.stroke = oldStroke } } class StageLineFlags(val isStaged: Boolean, val isUnstaged: Boolean) object MyLineFlagProvider : VisibleRangeMerger.FlagsProvider<StageLineFlags> { override fun getFlags(range: Range): StageLineFlags { range as StagedRange return StageLineFlags(range.hasStaged, range.hasUnstaged) } override fun mergeFlags(flags1: StageLineFlags, flags2: StageLineFlags): StageLineFlags = StageLineFlags(flags1.isStaged || flags2.isStaged, flags1.isUnstaged || flags2.isUnstaged) } override fun createAdditionalInfoPanel(editor: Editor, range: Range, mousePosition: Point?, disposable: Disposable): JComponent? { return createStageLinksPanel(editor, range, mousePosition, disposable) } override fun showHintAt(editor: Editor, range: Range, mousePosition: Point?) { if (!myTracker.isValid()) return myTracker as GitStageLineStatusTracker range as StagedRange if (!range.hasStaged || !range.hasUnstaged) { super.showHintAt(editor, range, mousePosition) return } val disposable = Disposer.newDisposable() val stagedTextField = createTextField(editor, myTracker.stagedDocument, range.stagedLine1, range.stagedLine2) val vcsTextField = createTextField(editor, myTracker.vcsDocument, range.vcsLine1, range.vcsLine2) installWordDiff(editor, stagedTextField, vcsTextField, range, disposable) val editorsPanel = createEditorComponent(editor, stagedTextField, vcsTextField) val actions = createToolbarActions(editor, range, mousePosition) val toolbar = LineStatusMarkerPopupPanel.buildToolbar(editor, actions, disposable) val additionalPanel = createStageLinksPanel(editor, range, mousePosition, disposable) LineStatusMarkerPopupPanel.showPopupAt(editor, toolbar, editorsPanel, additionalPanel, mousePosition, disposable, null) } fun createEditorComponent(editor: Editor, stagedTextField: EditorTextField, vcsTextField: EditorTextField): JComponent { val stagedEditorPane = createEditorPane(editor, GitBundle.message("stage.content.staged"), stagedTextField, true) val vcsEditorPane = createEditorPane(editor, GitUtil.HEAD, vcsTextField, false) val editorsPanel = JPanel(StagePopupVerticalLayout()) editorsPanel.add(stagedEditorPane) editorsPanel.add(vcsEditorPane) editorsPanel.background = LineStatusMarkerPopupPanel.getEditorBackgroundColor(editor) return editorsPanel } private fun createEditorPane(editor: Editor, @Nls text: String, textField: EditorTextField, topBorder: Boolean): JComponent { val label = JBLabel(text) label.border = JBUI.Borders.emptyBottom(2) label.font = UIUtil.getLabelFont(UIUtil.FontSize.SMALL) label.foreground = UIUtil.getLabelDisabledForeground() val borderColor = LineStatusMarkerPopupPanel.getBorderColor() val outerLineBorder = JBUI.Borders.customLine(borderColor, if (topBorder) 1 else 0, 1, 1, 1) val innerEmptyBorder = JBUI.Borders.empty(2) val border = BorderFactory.createCompoundBorder(outerLineBorder, innerEmptyBorder) return JBUI.Panels.simplePanel(textField) .addToTop(label) .withBackground(LineStatusMarkerPopupPanel.getEditorBackgroundColor(editor)) .withBorder(border) } private fun createTextField(editor: Editor, document: Document, line1: Int, line2: Int): EditorTextField { val textRange = DiffUtil.getLinesRange(document, line1, line2) val content = textRange.subSequence(document.immutableCharSequence).toString() val textField = LineStatusMarkerPopupPanel.createTextField(editor, content) LineStatusMarkerPopupPanel.installBaseEditorSyntaxHighlighters(myTracker.project, textField, document, textRange, fileType) return textField } private fun installWordDiff(editor: Editor, stagedTextField: EditorTextField, vcsTextField: EditorTextField, range: StagedRange, disposable: Disposable) { myTracker as GitStageLineStatusTracker if (!DiffApplicationSettings.getInstance().SHOW_LST_WORD_DIFFERENCES) return if (!range.hasLines()) return val currentContent = DiffUtil.getLinesContent(myTracker.document, range.line1, range.line2) val stagedContent = DiffUtil.getLinesContent(myTracker.stagedDocument, range.stagedLine1, range.stagedLine2) val vcsContent = DiffUtil.getLinesContent(myTracker.vcsDocument, range.vcsLine1, range.vcsLine2) val (stagedWordDiff, vcsWordDiff) = BackgroundTaskUtil.tryComputeFast( { indicator -> Pair(if (range.hasStagedLines()) ByWord.compare(stagedContent, currentContent, ComparisonPolicy.DEFAULT, indicator) else null, if (range.hasVcsLines()) ByWord.compare(vcsContent, currentContent, ComparisonPolicy.DEFAULT, indicator) else null) }, 200) ?: return if (stagedWordDiff != null) { LineStatusMarkerPopupPanel.installPopupEditorWordHighlighters(stagedTextField, stagedWordDiff) } if (vcsWordDiff != null) { LineStatusMarkerPopupPanel.installPopupEditorWordHighlighters(vcsTextField, vcsWordDiff) } if (stagedWordDiff != null || vcsWordDiff != null) { installMasterEditorWordHighlighters(editor, range.line1, range.line2, stagedWordDiff.orEmpty(), vcsWordDiff.orEmpty(), disposable) } } private fun installMasterEditorWordHighlighters(editor: Editor, startLine: Int, endLine: Int, wordDiff1: List<DiffFragment>, wordDiff2: List<DiffFragment>, parentDisposable: Disposable) { val currentTextRange = DiffUtil.getLinesRange(editor.document, startLine, endLine) DiffDrawUtil.setupLayeredRendering(editor, startLine, endLine, DiffDrawUtil.LAYER_PRIORITY_LST, parentDisposable) val highlighters = mutableListOf<RangeHighlighter>() highlighters += LineHighlighterBuilder(editor, startLine, endLine, TextDiffType.MODIFIED) .withLayerPriority(DiffDrawUtil.LAYER_PRIORITY_LST) .withIgnored(true) .withHideStripeMarkers(true) .withHideGutterMarkers(true) .done() highlighters += WordDiffMerger(editor, currentTextRange.startOffset, wordDiff1, wordDiff2).run() Disposer.register(parentDisposable, Disposable { highlighters.forEach(RangeHighlighter::dispose) }) } private class WordDiffMerger(private val editor: Editor, private val currentStartOffset: Int, private val wordDiff1: List<DiffFragment>, private val wordDiff2: List<DiffFragment>) { val highlighters: MutableList<RangeHighlighter> = ArrayList() private var dirtyStart = -1 private var dirtyEnd = -1 private val affectedFragments: MutableList<DiffFragment> = mutableListOf() fun run(): List<RangeHighlighter> { val it1 = PeekableIteratorWrapper(wordDiff1.iterator()) val it2 = PeekableIteratorWrapper(wordDiff2.iterator()) while (it1.hasNext() || it2.hasNext()) { if (!it2.hasNext()) { handleFragment(it1.next()) continue } if (!it1.hasNext()) { handleFragment(it2.next()) continue } val fragment1 = it1.peek() val fragment2 = it2.peek() if (fragment1.startOffset2 <= fragment2.startOffset2) { handleFragment(it1.next()) } else { handleFragment(it2.next()) } } flush(Int.MAX_VALUE) return highlighters } private fun handleFragment(fragment: DiffFragment) { flush(fragment.startOffset2) markDirtyRange(fragment.startOffset2, fragment.endOffset2) affectedFragments.add(fragment) } private fun markDirtyRange(start: Int, end: Int) { if (dirtyEnd == -1) { dirtyStart = start dirtyEnd = end } else { dirtyEnd = max(dirtyEnd, end) } } private fun flush(nextLine: Int) { if (dirtyEnd != -1 && dirtyEnd < nextLine) { val currentStart = currentStartOffset + dirtyStart val currentEnd = currentStartOffset + dirtyEnd val type = affectedFragments.map { DiffUtil.getDiffType(it) }.distinct().singleOrNull() ?: TextDiffType.MODIFIED highlighters.addAll(InlineHighlighterBuilder(editor, currentStart, currentEnd, type) .withLayerPriority(DiffDrawUtil.LAYER_PRIORITY_LST) .done()) dirtyStart = -1 dirtyEnd = -1 affectedFragments.clear() } } } private fun createStageLinksPanel(editor: Editor, range: Range, mousePosition: Point?, disposable: Disposable): JComponent? { if (range !is StagedRange) return null val panel = JPanel() panel.layout = BoxLayout(panel, BoxLayout.X_AXIS) panel.border = JBUI.Borders.emptyRight(10) panel.isOpaque = false panel.add(VerticalSeparatorComponent()) panel.add(Box.createHorizontalStrut(JBUI.scale(10))) if (range.hasUnstaged) { val stageLink = createStageLinkButton(editor, disposable, "Git.Stage.Add", GitBundle.message("action.label.add.unstaged.range"), GitBundle.message("action.label.add.unstaged.range.tooltip")) { tracker.stageChanges(range) reopenRange(editor, range, mousePosition) } panel.add(stageLink) } if (range.hasStaged) { if (range.hasUnstaged) panel.add(Box.createHorizontalStrut(JBUI.scale(16))) val unstageLink = createStageLinkButton(editor, disposable, "Git.Stage.Reset", GitBundle.message("action.label.reset.staged.range"), GitBundle.message("action.label.reset.staged.range.tooltip")) { tracker.unstageChanges(range) reopenRange(editor, range, mousePosition) } panel.add(unstageLink) } return panel } private fun createStageLinkButton(editor: Editor, disposable: Disposable, actionId: @NonNls String, text: @Nls String, tooltipText: @Nls String, callback: () -> Unit): LinkLabel<*> { val shortcut = ActionManager.getInstance().getAction(actionId).shortcutSet val shortcuts = shortcut.shortcuts val link = LinkLabel.create(text, callback) link.toolTipText = DiffUtil.createTooltipText(tooltipText, StringUtil.nullize(KeymapUtil.getShortcutsText(shortcuts))) if (shortcuts.isNotEmpty()) { object : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { link.doClick() } }.registerCustomShortcutSet(shortcut, editor.component, disposable) } return link } override fun createToolbarActions(editor: Editor, range: Range, mousePosition: Point?): List<AnAction> { val actions = ArrayList<AnAction>() actions.add(ShowPrevChangeMarkerAction(editor, range)) actions.add(ShowNextChangeMarkerAction(editor, range)) actions.add(RollbackLineStatusRangeAction(editor, range)) actions.add(StageShowDiffAction(editor, range)) actions.add(CopyLineStatusRangeAction(editor, range)) actions.add(ToggleByWordDiffAction(editor, range, mousePosition)) return actions } private inner class RollbackLineStatusRangeAction(editor: Editor, range: Range) : RangeMarkerAction(editor, range, IdeActions.SELECTED_CHANGES_ROLLBACK) { override fun isEnabled(editor: Editor, range: Range): Boolean = (range as StagedRange).hasUnstaged override fun actionPerformed(editor: Editor, range: Range) { RollbackLineStatusAction.rollback(tracker, range, editor) } } private inner class StageShowDiffAction(editor: Editor, range: Range) : RangeMarkerAction(editor, range, IdeActions.ACTION_SHOW_DIFF_COMMON), LightEditCompatible { override fun isEnabled(editor: Editor, range: Range): Boolean = true override fun actionPerformed(editor: Editor, range: Range) { range as StagedRange myTracker as GitStageLineStatusTracker val canExpandBefore = range.line1 != 0 && range.stagedLine1 != 0 && range.vcsLine1 != 0 val canExpandAfter = range.line2 < DiffUtil.getLineCount(myTracker.document) && range.stagedLine2 < DiffUtil.getLineCount(myTracker.stagedDocument) && range.vcsLine2 < DiffUtil.getLineCount(myTracker.vcsDocument) val currentContent = createDiffContent(myTracker.document, range.line1, range.line2, canExpandBefore, canExpandAfter) val stagedContent = createDiffContent(myTracker.stagedDocument, range.stagedLine1, range.stagedLine2, canExpandBefore, canExpandAfter) val vcsContent = createDiffContent(myTracker.vcsDocument, range.vcsLine1, range.vcsLine2, canExpandBefore, canExpandAfter) val request = SimpleDiffRequest( DiffBundle.message("dialog.title.diff.for.range"), vcsContent, stagedContent, currentContent, GitUtil.HEAD, GitBundle.message("stage.content.staged"), GitBundle.message("stage.content.local")) request.putUserData(DiffUserDataKeysEx.VCS_DIFF_ACCEPT_RIGHT_TO_BASE_ACTION_TEXT, GitBundle.message("action.label.add.unstaged.range")) request.putUserData(DiffUserDataKeysEx.VCS_DIFF_ACCEPT_BASE_TO_RIGHT_ACTION_TEXT, DiffBundle.message("action.presentation.diff.revert.text")) request.putUserData(DiffUserDataKeysEx.VCS_DIFF_ACCEPT_LEFT_TO_BASE_ACTION_TEXT, GitBundle.message("action.label.reset.staged.range")) DiffManager.getInstance().showDiff(myTracker.project, request) } private fun createDiffContent(document: Document, line1: Int, line2: Int, canExpandBefore: Boolean, canExpandAfter: Boolean): DiffContent { val textRange = DiffUtil.getLinesRange(document, line1 - if (canExpandBefore) 1 else 0, line2 + if (canExpandAfter) 1 else 0) val content = DiffContentFactory.getInstance().create(myTracker.project, document, myTracker.virtualFile) return DiffContentFactory.getInstance().createFragment(myTracker.project, content, textRange) } } } private inner class MyBlockOperations(lock: DocumentTracker.Lock) : LineStatusTrackerBlockOperations<StagedRange, StagedRange>(lock) { override fun getBlocks(): List<StagedRange>? = if (isValid()) blocks else null override fun StagedRange.toRange(): StagedRange = this } private inner class MyStagedBlockOperations(lock: DocumentTracker.Lock) : LineStatusTrackerBlockOperations<Range, BlockI>(lock) { override fun getBlocks(): List<BlockI>? = if (isValid()) unstagedTracker.blocks else null override fun BlockI.toRange(): Range = Range(start, end, vcsStart, vcsEnd) } } class StagedRange(line1: Int, line2: Int, val stagedLine1: Int, val stagedLine2: Int, headLine1: Int, headLine2: Int, val hasStaged: Boolean, val hasUnstaged: Boolean) : Range(line1, line2, headLine1, headLine2, null), BlockI { override val start: Int get() = line1 override val end: Int get() = line2 override val vcsStart: Int get() = vcsLine1 override val vcsEnd: Int get() = vcsLine2 override val isEmpty: Boolean get() = line1 == line2 && stagedLine1 == stagedLine2 && vcsLine1 == vcsLine2 fun hasStagedLines(): Boolean = stagedLine1 != stagedLine2 } private class BlockMerger(private val staged: List<DocumentTracker.Block>, private val unstaged: List<DocumentTracker.Block>) { private val ranges: MutableList<StagedRange> = mutableListOf() private var dirtyStart = -1 private var dirtyEnd = -1 private var hasStaged: Boolean = false private var hasUnstaged: Boolean = false private var stagedShift: Int = 0 private var unstagedShift: Int = 0 private var dirtyStagedShift: Int = 0 private var dirtyUnstagedShift: Int = 0 fun run(): List<StagedRange> { val it1 = PeekableIteratorWrapper(staged.iterator()) val it2 = PeekableIteratorWrapper(unstaged.iterator()) while (it1.hasNext() || it2.hasNext()) { if (!it2.hasNext()) { handleStaged(it1.next()) continue } if (!it1.hasNext()) { handleUnstaged(it2.next()) continue } val block1 = it1.peek() val block2 = it2.peek() if (block1.range.start2 <= block2.range.start1) { handleStaged(it1.next()) } else { handleUnstaged(it2.next()) } } flush(Int.MAX_VALUE) return ranges } private fun handleStaged(block: DocumentTracker.Block) { val range = block.range flush(range.start2) dirtyStagedShift -= getRangeDelta(range) markDirtyRange(range.start2, range.end2) hasStaged = true } private fun handleUnstaged(block: DocumentTracker.Block) { val range = block.range flush(range.start1) dirtyUnstagedShift += getRangeDelta(range) markDirtyRange(range.start1, range.end1) hasUnstaged = true } private fun markDirtyRange(start: Int, end: Int) { if (dirtyEnd == -1) { dirtyStart = start dirtyEnd = end } else { dirtyEnd = max(dirtyEnd, end) } } private fun flush(nextLine: Int) { if (dirtyEnd != -1 && dirtyEnd < nextLine) { ranges.add(StagedRange(dirtyStart + unstagedShift, dirtyEnd + unstagedShift + dirtyUnstagedShift, dirtyStart, dirtyEnd, dirtyStart + stagedShift, dirtyEnd + stagedShift + dirtyStagedShift, hasStaged, hasUnstaged)) dirtyStart = -1 dirtyEnd = -1 hasStaged = false hasUnstaged = false stagedShift += dirtyStagedShift unstagedShift += dirtyUnstagedShift dirtyStagedShift = 0 dirtyUnstagedShift = 0 } } private fun getRangeDelta(range: com.intellij.diff.util.Range): Int { val deleted = range.end1 - range.start1 val inserted = range.end2 - range.start2 return inserted - deleted } }
apache-2.0
ef862532a66c9863f4de88d94837dd91
38.680851
140
0.681219
4.512863
false
false
false
false
Killian-LeClainche/Java-Base-Application-Engine
src/polaris/okapi/render/Texture.kt
1
1558
package polaris.okapi.render import jdk.nashorn.internal.objects.NativeFunction.function import org.lwjgl.opengl.GL11 import org.lwjgl.opengl.GL11.* import org.lwjgl.stb.STBImage.stbi_image_free import java.nio.ByteBuffer /** * Created by Killian Le Clainche on 12/12/2017. */ open class Texture @JvmOverloads constructor(var name: String, val width: Int, val height: Int, val composite: Int, var mipmapMaxLevel: Int, val image: ByteBuffer, var id: Int = glGenTextures()) { fun use(function: () -> Unit) { glBindTexture(GL_TEXTURE_2D, this.id) function() } fun bind() = glBindTexture(GL_TEXTURE_2D, id) fun destroy() { if (id != 0) GL11.glDeleteTextures(id) id = 0 } fun close() { destroy() stbi_image_free(image) } companion object { fun enable() = glEnable(GL_TEXTURE_2D) fun disable() = glDisable(GL_TEXTURE_2D) } } class TextureArray constructor(texture: Texture, texCoords: ByteBuffer) : Texture(texture.name, texture.width, texture.height, texture.composite, texture.mipmapMaxLevel, texture.image, texture.id) { var textures: Array<TexCoord?> private set init { textures = arrayOfNulls(texCoords.int) var index = 0 while (texCoords.hasRemaining()) { textures[index] = TexCoord(texCoords.float, texCoords.float, texCoords.float, texCoords.float) index++ } } } data class TexCoord(val minU: Float, val minV: Float, val maxU: Float, val maxV: Float)
gpl-2.0
f2b29e9c7f4d44592b5949f5ac1f5cf6
26.333333
198
0.655327
3.754217
false
false
false
false
Seancheey/Ark-Sonah
src/com/seancheey/scene/controller/BattleController.kt
1
2112
package com.seancheey.scene.controller import com.seancheey.game.Config import com.seancheey.game.Game import com.seancheey.game.battlefield.TestBattlefield import com.seancheey.gui.BattleInspectPane import com.seancheey.gui.RobotModelSlot import com.seancheey.scene.Scenes import com.seancheey.scene.Stages import javafx.fxml.FXML import javafx.fxml.Initializable import javafx.scene.control.Label import javafx.scene.layout.HBox import javafx.scene.layout.StackPane import java.net.URL import java.util.* /** * Created by Seancheey on 22/05/2017. * GitHub: https://github.com/Seancheey */ class BattleController : Initializable { companion object { var battleController: BattleController? = null } var battleController: BattleController? get() = Companion.battleController set(value) { Companion.battleController = value } @FXML var botGroupBox: HBox? = null @FXML var battleContainer: StackPane? = null @FXML var moneyLabel: Label? = null var battlePane: BattleInspectPane val game = Game(2000, mutableMapOf(Config.player to 1), TestBattlefield()) init { // make sure there is a empty battlefield battlePane = BattleInspectPane(game, 0.0, 0.0) } override fun initialize(location: URL?, resources: ResourceBundle?) { battleController = this // init selection slots RobotModelSlot.addAllTo(botGroupBox!!.children, Config.player.robotGroups[0], { battlePane.clickRobot(it) }, true) // init battle field battlePane = BattleInspectPane(game, Stages.primaryStage!!.width, Stages.primaryStage!!.height - botGroupBox!!.height - 200) battleContainer!!.children.add(battlePane) botGroupBox!!.toFront() // init money label moneyLabel!!.text = "money: ${game.gamePlayers[0].money}" } fun menu() { Stages.switchScene(Scenes.menu) battlePane.battleCanvas.stop() } fun start() { battlePane.battleCanvas.start() } fun pause() { battlePane.battleCanvas.stop() } }
mit
2eb5255d5d1f2a919b52f09464817d1e
27.554054
132
0.690814
4.116959
false
false
false
false
gmariotti/kotlin-koans
lesson2/task5/src/DateUtil.kt
2
694
import java.util.Calendar fun MyDate.addTimeIntervals(timeInterval: TimeInterval, number: Int): MyDate { val c = Calendar.getInstance() c.set(year + if (timeInterval == TimeInterval.YEAR) number else 0, month, dayOfMonth) var timeInMillis = c.getTimeInMillis() val millisecondsInADay = 24 * 60 * 60 * 1000L timeInMillis += number * when (timeInterval) { TimeInterval.DAY -> millisecondsInADay TimeInterval.WEEK -> 7 * millisecondsInADay TimeInterval.YEAR -> 0L } val result = Calendar.getInstance() result.setTimeInMillis(timeInMillis) return MyDate(result.get(Calendar.YEAR), result.get(Calendar.MONTH), result.get(Calendar.DATE)) }
mit
a74c2637459a632bc260193fccfd807a
42.4375
99
0.710375
4.3375
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/bukkit/SpigotModuleType.kt
1
1557
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.bukkit import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.AbstractModuleType import com.demonwav.mcdev.platform.PlatformType import com.demonwav.mcdev.platform.bukkit.generation.BukkitEventGenerationPanel import com.demonwav.mcdev.platform.bukkit.util.BukkitConstants import com.demonwav.mcdev.platform.bungeecord.util.BungeeCordConstants import com.demonwav.mcdev.util.CommonColors import com.intellij.psi.PsiClass object SpigotModuleType : AbstractModuleType<BukkitModule<SpigotModuleType>>("org.spigotmc", "spigot-api") { private const val ID = "SPIGOT_MODULE_TYPE" init { CommonColors.applyStandardColors(colorMap, BukkitConstants.CHAT_COLOR_CLASS) CommonColors.applyStandardColors(colorMap, BungeeCordConstants.CHAT_COLOR_CLASS) } override val platformType = PlatformType.SPIGOT override val icon = PlatformAssets.SPIGOT_ICON override val id = ID override val ignoredAnnotations = BukkitModuleType.IGNORED_ANNOTATIONS override val listenerAnnotations = BukkitModuleType.LISTENER_ANNOTATIONS override val isEventGenAvailable = true override fun generateModule(facet: MinecraftFacet): BukkitModule<SpigotModuleType> = BukkitModule(facet, this) override fun getEventGenerationPanel(chosenClass: PsiClass) = BukkitEventGenerationPanel(chosenClass) }
mit
07e8c3787f4c3452af742dbe0a8fb8e4
36.97561
114
0.802184
4.325
false
false
false
false
google/intellij-community
platform/build-scripts/testFramework/src/org/jetbrains/intellij/build/testFramework/buildScriptTestUtils.kt
1
8547
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build.testFramework import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.NioFiles import com.intellij.rt.execution.junit.FileComparisonData import com.intellij.testFramework.TestLoggerFactory import com.intellij.util.ExceptionUtil import io.opentelemetry.api.trace.StatusCode import io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporter import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.intellij.build.impl.BuildContextImpl import org.jetbrains.intellij.build.impl.logging.BuildMessagesImpl import org.jetbrains.intellij.build.testFramework.binaryReproducibility.BuildArtifactsReproducibilityTest import org.opentest4j.TestAbortedException import java.net.http.HttpConnectTimeoutException import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path import java.nio.file.StandardCopyOption import java.util.function.Supplier private val initializeTracer by lazy { val endpoint = System.getenv("JAEGER_ENDPOINT") if (endpoint != null) { val defaultExporters = TracerProviderManager.spanExporterProvider.get() TracerProviderManager.spanExporterProvider = Supplier { defaultExporters + JaegerGrpcSpanExporter.builder().setEndpoint(endpoint).build() } } } fun customizeBuildOptionsForTest(options: BuildOptions, productProperties: ProductProperties, skipDependencySetup: Boolean = false) { options.skipDependencySetup = skipDependencySetup options.isTestBuild = true options.buildStepsToSkip.addAll(listOf( BuildOptions.TEAMCITY_ARTIFACTS_PUBLICATION_STEP, BuildOptions.OS_SPECIFIC_DISTRIBUTIONS_STEP, BuildOptions.LINUX_TAR_GZ_WITHOUT_BUNDLED_RUNTIME_STEP, BuildOptions.WIN_SIGN_STEP, BuildOptions.MAC_SIGN_STEP, )) options.buildMacArtifactsWithRuntime = false options.buildMacArtifactsWithoutRuntime = false options.buildUnixSnaps = false options.outputRootPath = FileUtil.createTempDirectory("test-build-${productProperties.baseFileName}", null, false).absolutePath options.useCompiledClassesFromProjectOutput = true options.compilationLogEnabled = false } fun createBuildContext( homePath: Path, productProperties: ProductProperties, buildTools: ProprietaryBuildTools = ProprietaryBuildTools.DUMMY, communityHomePath: BuildDependenciesCommunityRoot, skipDependencySetup: Boolean = false, buildOptionsCustomizer: (BuildOptions) -> Unit = {}, ): BuildContext { val options = BuildOptions() customizeBuildOptionsForTest(options, productProperties, skipDependencySetup) buildOptionsCustomizer(options) return BuildContextImpl.createContext(communityHome = communityHomePath, projectHome = homePath, productProperties = productProperties, proprietaryBuildTools = buildTools, options = options) } // don't expose BuildDependenciesCommunityRoot fun runTestBuild(homePath: Path, productProperties: ProductProperties, buildTools: ProprietaryBuildTools) { runTestBuild(homePath, productProperties, buildTools, traceSpanName = null) } fun runTestBuild( homePath: Path, productProperties: ProductProperties, buildTools: ProprietaryBuildTools = ProprietaryBuildTools.DUMMY, communityHomePath: BuildDependenciesCommunityRoot = BuildDependenciesCommunityRoot(homePath.resolve("community")), traceSpanName: String? = null, onFinish: suspend (context: BuildContext) -> Unit = {}, buildOptionsCustomizer: (BuildOptions) -> Unit = {} ) { val buildArtifactsReproducibilityTest = BuildArtifactsReproducibilityTest() if (!buildArtifactsReproducibilityTest.isEnabled) { testBuild(homePath, productProperties, buildTools, communityHomePath, traceSpanName, onFinish, buildOptionsCustomizer) } else { testBuild(homePath, productProperties, buildTools, communityHomePath, traceSpanName, buildOptionsCustomizer = { buildOptionsCustomizer(it) buildArtifactsReproducibilityTest.configure(it) }, onFinish = { firstIteration -> onFinish(firstIteration) testBuild(homePath, productProperties, buildTools, communityHomePath, traceSpanName, buildOptionsCustomizer = { buildOptionsCustomizer(it) buildArtifactsReproducibilityTest.configure(it) }, onFinish = { nextIteration -> onFinish(nextIteration) buildArtifactsReproducibilityTest.compare(firstIteration, nextIteration) }) }) } } private fun testBuild( homePath: Path, productProperties: ProductProperties, buildTools: ProprietaryBuildTools, communityHomePath: BuildDependenciesCommunityRoot, traceSpanName: String?, onFinish: suspend (context: BuildContext) -> Unit, buildOptionsCustomizer: (BuildOptions) -> Unit, ) { val context = createBuildContext( homePath = homePath, productProperties = productProperties, buildTools = buildTools, skipDependencySetup = false, communityHomePath = communityHomePath, buildOptionsCustomizer = buildOptionsCustomizer, ) runTestBuild( buildContext = context, traceSpanName = traceSpanName, onFinish = onFinish, ) } // FIXME: test reproducibility fun runTestBuild( buildContext: BuildContext, traceSpanName: String? = null, onFinish: suspend (context: BuildContext) -> Unit = {}, ) { initializeTracer val productProperties = buildContext.productProperties // to see in Jaeger as a one trace val traceFileName = "${productProperties.baseFileName}-trace.json" val span = TraceManager.spanBuilder(traceSpanName ?: "test build of ${productProperties.baseFileName}").startSpan() var spanEnded = false val spanScope = span.makeCurrent() try { val outDir = buildContext.paths.buildOutputDir span.setAttribute("outDir", outDir.toString()) val messages = buildContext.messages as BuildMessagesImpl try { runBlocking(Dispatchers.Default) { BuildTasks.create(buildContext).runTestBuild() onFinish(buildContext) } } catch (e: Throwable) { if (e !is FileComparisonData) { span.recordException(e) } span.setStatus(StatusCode.ERROR) copyDebugLog(productProperties, messages) if (ExceptionUtil.causedBy(e, HttpConnectTimeoutException::class.java)) { //todo use com.intellij.platform.testFramework.io.ExternalResourcesChecker after next update of jps-bootstrap library throw TestAbortedException("failed to load data for build scripts", e) } else { throw e } } finally { // redirect debug logging to some other file to prevent locking of output directory on Windows val newDebugLog = FileUtil.createTempFile("debug-log-", ".log", true) messages.setDebugLogPath(newDebugLog.toPath()) spanScope.close() span.end() spanEnded = true copyPerfReport(traceFileName) try { NioFiles.deleteRecursively(outDir) } catch (e: Throwable) { System.err.println("cannot cleanup $outDir:") e.printStackTrace(System.err) } } } finally { if (!spanEnded) { spanScope.close() span.end() } } } private fun copyDebugLog(productProperties: ProductProperties, messages: BuildMessagesImpl) { try { val targetFile = TestLoggerFactory.getTestLogDir().resolve("${productProperties.baseFileName}-test-build-debug.log") Files.createDirectories(targetFile.parent) Files.copy(messages.debugLogFile!!, targetFile, StandardCopyOption.REPLACE_EXISTING) messages.info("Debug log copied to $targetFile") } catch (e: Throwable) { messages.warning("Failed to copy debug log: ${e.message}") } } private fun copyPerfReport(traceFileName: String) { val targetFile = TestLoggerFactory.getTestLogDir().resolve(traceFileName) Files.createDirectories(targetFile.parent) val file = TraceManager.finish() ?: return try { Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING) println("Performance report is written to $targetFile") } catch (ignore: NoSuchFileException) { } catch (e: Throwable) { System.err.println("cannot write performance report: ${e.message}") } }
apache-2.0
8f6df9ca3e78656ecf2be7a0e0de66fe
36.656388
133
0.747163
4.872862
false
true
false
false
apache/isis
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/demo2_0_0/OBJECT_ICON.kt
2
1899
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.snapshots.demo2_0_0 import org.apache.causeway.client.kroviz.snapshots.Response object OBJECT_ICON : Response() { val VMT = "\$vmT" override val url = "http://localhost:8080/restful/objects/demo.JavaLangStringEntity/1/object-icon" override val str = """ "�PNG  IHDR�w=�sBIT|d� pHYs  ��~�tEXtSoftwareAdobe Fireworks CS5q��6_IDATH���i�0�?��7${'$'}��TP� �N��� ���l �����C�Z�bZ�P�c,_�s����� ���@+9"`���/ �${'$'}+�ߴ0ƴ�� ���ɽ'�w ,���a�{G v${VMT}�6��N ��C_�Mwbұ�J+P�[��Իf��P����B+� �'��h20IVo��+{��{`�IV�ZI=�Ⱥ\k�� ߹u�G���${'$'}+�ǡ+_���6�Y�ӡ}>���7���?8;hZ�N'sL�kA+����w +`���h\���]�����iȂ�!�����ֆ���Q�6�.�̨�U�����0b&bs�:���o�맺y��IEND�B`�" """ }
apache-2.0
9edc73646e50227ac914ac223cf886a4
31.428571
102
0.614852
2.471229
false
false
false
false
RuneSuite/client
plugins/src/main/java/org/runestar/client/plugins/smoothanimations/Widget.kt
1
2826
package org.runestar.client.plugins.smoothanimations import org.runestar.client.raw.CLIENT import org.runestar.client.raw.access.XModel import org.runestar.client.raw.access.XSeqType import org.runestar.client.raw.access.XComponent import org.runestar.client.raw.base.MethodEvent internal fun widgetGetModelEnter(event: MethodEvent<XComponent, XModel>) { val widget = event.instance event.arguments[1] = packFrame(widget.modelFrame, widget.modelFrameCycle) } internal fun animateWidgetEnter(event: MethodEvent<XSeqType, XModel>) { val frameArg = event.arguments[1] as Int val frame = frameArg and 0xFFFF event.arguments[1] = frame val seq = event.instance val nextFrame = frame + 1 val frameCycle = (frameArg xor Int.MIN_VALUE) shr 16 if (seq == null || frameArg >= -1 || nextFrame > seq.frameIds.lastIndex || frameCycle == 0) return val frameId1 = seq.frameIds[frame] val frames1 = CLIENT.getAnimFrameset(frameId1 shr 16) ?: return val nextFrameId1 = seq.frameIds[nextFrame] val nextFrames1 = CLIENT.getAnimFrameset(nextFrameId1 shr 16) ?: return val model = event.arguments[0] as XModel val frameIdx1 = frameId1 and 0xFFFF val nextFrameIdx1 = nextFrameId1 and 0xFFFF event.skipBody = true val frameIds2 = seq.frameIds2 if (frameIds2 != null && frame <= frameIds2.lastIndex) { val frameId2 = seq.frameIds2[frame] val frames2 = CLIENT.getAnimFrameset(frameId1 shr 16) val frameIdx2 = frameId2 and 0xFFFF if (frames2 != null && nextFrame <= seq.frameIds2.lastIndex) { val nextFrameId2 = seq.frameIds2[nextFrame] val nextFrames2 = CLIENT.getAnimFrameset(nextFrameId2 shr 16) val nextFrameIdx2 = nextFrameId2 and 0xFFFF if (nextFrames2 != null && nextFrameIdx2 != 0xFFFF) { val animatedModel = model.toSharedSequenceModel(!frames1.hasAlphaTransform(frameIdx1) && !nextFrames1.hasAlphaTransform(nextFrameIdx1) && !frames2.hasAlphaTransform(frameIdx2) && !nextFrames2.hasAlphaTransform(nextFrameIdx2)) animatedModel.animateInterpolated(frames1.frames[frameIdx1], nextFrames1.frames[nextFrameIdx1], frameCycle, seq.frameLengths[frame] + 1) animatedModel.animateInterpolated(frames2.frames[frameIdx2], nextFrames2.frames[nextFrameIdx2], frameCycle, seq.frameLengths[frame] + 1) event.returned = animatedModel return } } } val animatedModel = model.toSharedSequenceModel(!frames1.hasAlphaTransform(frameIdx1) && !nextFrames1.hasAlphaTransform(nextFrameIdx1)) animatedModel.animateInterpolated(frames1.frames[frameIdx1], nextFrames1.frames[nextFrameIdx1], frameCycle, seq.frameLengths[frame] + 1) event.returned = animatedModel }
mit
4b86593d90db3e6f0c0fdaf963ad5827
46.915254
153
0.715145
3.839674
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/ServerProt.kt
1
1176
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Instruction2 import org.objectweb.asm.Opcodes import org.objectweb.asm.Type.* class ServerProt : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == Any::class.type } .and { it.interfaces.isEmpty() } .and { it.instanceFields.size == 2 } .and { it.instanceFields.all { it.type == INT_TYPE } } .and { it.staticFields.size >= 20 } class id : OrderMapper.InConstructor.Field(ServerProt::class, 0, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.PUTFIELD } } class length : OrderMapper.InConstructor.Field(ServerProt::class, 1, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.PUTFIELD } } }
mit
c8699c9d6e9d3f7d4006e1d8098840de
41.035714
92
0.72534
3.959596
false
false
false
false
oryanm/TrelloWidget
app/src/main/kotlin/com/github/oryanmat/trellowidget/util/PrefUtil.kt
1
2471
package com.github.oryanmat.trellowidget.util import android.content.Context import android.preference.PreferenceManager.getDefaultSharedPreferences import androidx.annotation.ColorInt import com.github.oryanmat.trellowidget.R internal fun Context.getPrefTextScale(): Float { val def: String = getString(R.string.pref_text_size_default) val string: String = sharedPreferences().getString( getString(R.string.pref_text_size_key), def) return java.lang.Float.parseFloat(string) } internal fun Context.getInterval() = Integer.parseInt(sharedPreferences().getString( getString(R.string.pref_update_interval_key), getString(R.string.pref_update_interval_default))) @ColorInt internal fun Context.getCardBackgroundColor() = getColor( getString(R.string.pref_back_color_key), resources.getInteger(R.integer.pref_back_color_default)) @ColorInt internal fun Context.getCardForegroundColor() = getColor( getString(R.string.pref_fore_color_key), resources.getInteger(R.integer.pref_fore_color_default)) internal fun Context.displayBoardName() = sharedPreferences().getBoolean( getString(R.string.pref_display_board_name_key), resources.getBoolean(R.bool.pref_display_board_name_default)) internal fun Context.isTitleUniqueColor() = sharedPreferences().getBoolean( getString(R.string.pref_title_use_unique_color_key), resources.getBoolean(R.bool.pref_title_use_unique_color_default)) @ColorInt internal fun Context.getTitleBackgroundColor(): Int = when { isTitleUniqueColor() -> getColor( getString(R.string.pref_title_back_color_key), resources.getInteger(R.integer.pref_title_back_color_default)) else -> getCardBackgroundColor() } @ColorInt internal fun Context.getTitleForegroundColor(): Int = when { isTitleUniqueColor() -> getColor( getString(R.string.pref_title_fore_color_key), resources.getInteger(R.integer.pref_title_fore_color_default)) else -> getCardForegroundColor() } @ColorInt private fun Context.getColor(key: String, defValue: Int) = sharedPreferences().getInt(key, defValue) internal fun Context.isTitleEnabled() = sharedPreferences().getBoolean( getString(R.string.pref_title_onclick_key), resources.getBoolean(R.bool.pref_title_onclick_default)) private fun Context.sharedPreferences() = getDefaultSharedPreferences(this)
mit
8a50a753eb9b86a8d1b17c75cfd6f772
38.238095
75
0.733711
4.097844
false
false
false
false
glodanif/BluetoothChat
app/src/main/kotlin/com/glodanif/bluetoothchat/data/service/connection/DataTransferThread.kt
1
12265
package com.glodanif.bluetoothchat.data.service.connection import android.bluetooth.BluetoothSocket import com.glodanif.bluetoothchat.data.service.message.TransferringFile import com.glodanif.bluetoothchat.utils.safeLet import java.io.* import kotlin.concurrent.thread abstract class DataTransferThread(private val socket: BluetoothSocket, private val type: ConnectionType, private val transferListener: TransferEventsListener, private val filesDirectory: File, private val fileListener: OnFileListener, private val eventsStrategy: EventsStrategy) : Thread() { private var inputStream: InputStream? = null private var outputStream: OutputStream? = null private val bufferSize = 2048 private val buffer = ByteArray(bufferSize) private var skipEvents = false @Volatile private var isConnectionPrepared = false @Volatile private var isFileTransferCanceledByMe = false @Volatile private var isFileTransferCanceledByPartner = false @Volatile private var isFileDownloading = false @Volatile private var isFileUploading = false @Volatile private var fileName: String? = null private var fileMessageId: Long = 0 private var fileSize: Long = 0 fun prepare() { try { inputStream = socket.inputStream outputStream = socket.outputStream isConnectionPrepared = true transferListener.onConnectionPrepared(type) } catch (e: IOException) { e.printStackTrace() } } abstract fun shouldRun(): Boolean override fun start() { require(isConnectionPrepared) { "Connection is not prepared yet." } super.start() } override fun run() { while (shouldRun()) { try { readString()?.let { message -> val potentialFile = eventsStrategy.isFileStart(message) if (potentialFile != null) { isFileDownloading = true fileMessageId = potentialFile.uid fileName = potentialFile.name fileSize = potentialFile.size transferListener.onMessageReceived(message) safeLet(inputStream, fileName) { stream, name -> readFile(stream, name, fileSize) } } else if (eventsStrategy.isMessage(message)) { val cancelInfo = eventsStrategy.isFileCanceled(message) if (cancelInfo == null) { transferListener.onMessageReceived(message) } else { fileListener.onFileTransferCanceled(cancelInfo.byPartner) isFileTransferCanceledByPartner = cancelInfo.byPartner } } } } catch (e: IOException) { e.printStackTrace() if (!skipEvents) { transferListener.onConnectionLost() skipEvents = false } break } } } private fun readString(): String? { return inputStream?.read(buffer)?.let { try { String(buffer, 0, it) } catch (e: StringIndexOutOfBoundsException) { null } } } fun write(message: String) { write(message, false) } fun write(message: String, skipEvents: Boolean) { this.skipEvents = skipEvents try { outputStream?.write(message.toByteArray(Charsets.UTF_8)) outputStream?.flush() transferListener.onMessageSent(message) } catch (e: Exception) { transferListener.onMessageSendingFailed() e.printStackTrace() } } fun writeFile(uid: Long, file: File) { if (!file.exists()) { fileListener.onFileSendingFailed() resetFileTransferState() return } fileMessageId = uid fileName = file.absolutePath fileSize = file.length() isFileUploading = true isFileTransferCanceledByMe = false isFileTransferCanceledByPartner = false val transferringFile = TransferringFile(fileName, fileSize, TransferringFile.TransferType.SENDING) fileListener.onFileSendingStarted(transferringFile) thread { val fileStream = FileInputStream(file) BufferedInputStream(fileStream).use { val bufferedOutputStream = BufferedOutputStream(outputStream) try { var sentBytes: Long = 0 var length: Int val buffer = ByteArray(bufferSize) length = it.read(buffer) while (length > -1) { if (length > 0) { try { bufferedOutputStream.write(buffer, 0, length) bufferedOutputStream.flush() } catch (e: IOException) { Thread.sleep(200) fileListener.onFileSendingFailed() break } sentBytes += length.toLong() } length = it.read(buffer) fileListener.onFileSendingProgress(transferringFile, sentBytes) if (isFileTransferCanceledByMe || isFileTransferCanceledByPartner) { bufferedOutputStream.flush() break } } Thread.sleep(250) if (!isFileTransferCanceledByMe && !isFileTransferCanceledByPartner) { fileListener.onFileSendingFinished(fileMessageId, file.absolutePath) } else { if (isFileTransferCanceledByMe) { write(eventsStrategy.getCancellationMessage(true)) } } } catch (e: Exception) { e.printStackTrace() fileListener.onFileSendingFailed() } finally { fileStream.close() resetFileTransferState() } } } } private fun resetFileTransferState() { isFileUploading = false isFileTransferCanceledByMe = false isFileTransferCanceledByPartner = false fileName = null fileSize = 0 fileMessageId = 0 } fun cancel() { cancel(false) } fun cancel(skipEvents: Boolean) { this.skipEvents = skipEvents try { socket.close() isConnectionPrepared = false transferListener.onConnectionCanceled() } catch (e: IOException) { e.printStackTrace() } } fun cancelFileTransfer() { isFileTransferCanceledByMe = true } fun getTransferringFile(): TransferringFile? { return fileName?.let { when { isFileDownloading -> TransferringFile(it, fileSize, TransferringFile.TransferType.RECEIVING) isFileUploading -> TransferringFile(it, fileSize, TransferringFile.TransferType.SENDING) else -> null } } } private fun readFile(stream: InputStream, name: String, size: Long) { isFileTransferCanceledByMe = false isFileTransferCanceledByPartner = false if (!filesDirectory.exists()) { filesDirectory.mkdirs() } val file = File(filesDirectory, name) val bis = BufferedInputStream(stream) BufferedOutputStream(FileOutputStream(file)).use { val transferringFile = TransferringFile(name, size, TransferringFile.TransferType.RECEIVING) fileListener.onFileReceivingStarted(transferringFile) try { var bytesRead: Long = 0 val buffer = ByteArray(bufferSize) var timeOut = 0 val maxTimeOut = 16 var isCanceled = false while (bytesRead < size) { while (bis.available() == 0 && timeOut < maxTimeOut) { timeOut++ Thread.sleep(250) } val remainingSize = size - bytesRead val byteCount = Math.min(remainingSize, bufferSize.toLong()).toInt() val len = bis.read(buffer, 0, byteCount) val str = String(buffer, 0, byteCount) if (eventsStrategy.isFileFinish(str)) { break } val cancelInfo = eventsStrategy.isFileCanceled(str) if (cancelInfo != null) { isCanceled = true fileListener.onFileTransferCanceled(cancelInfo.byPartner) file.delete() break } if (isFileTransferCanceledByMe || isFileTransferCanceledByPartner) { it.flush() break } if (len > 0) { timeOut = 0 it.write(buffer, 0, len) it.flush() bytesRead += len.toLong() fileListener.onFileReceivingProgress(transferringFile, bytesRead) } } Thread.sleep(250) if (!isCanceled && !isFileTransferCanceledByMe && !isFileTransferCanceledByPartner) { fileListener.onFileReceivingFinished(fileMessageId, file.absolutePath) } } catch (e: Exception) { fileListener.onFileReceivingFailed() throw e } finally { if (isFileTransferCanceledByMe || isFileTransferCanceledByPartner) { isFileTransferCanceledByMe = false isFileTransferCanceledByPartner = false file.delete() write(eventsStrategy.getCancellationMessage(true)) } isFileDownloading = false fileName = null fileSize = 0 fileMessageId = 0 } } } interface TransferEventsListener { fun onMessageReceived(message: String) fun onMessageSent(message: String) fun onMessageSendingFailed() fun onConnectionPrepared(type: ConnectionType) fun onConnectionCanceled() fun onConnectionLost() } interface OnFileListener { fun onFileSendingStarted(file: TransferringFile) fun onFileSendingProgress(file: TransferringFile, sentBytes: Long) fun onFileSendingFinished(uid: Long, path: String) fun onFileSendingFailed() fun onFileReceivingStarted(file: TransferringFile) fun onFileReceivingProgress(file: TransferringFile, receivedBytes: Long) fun onFileReceivingFinished(uid: Long, path: String) fun onFileReceivingFailed() fun onFileTransferCanceled(byPartner: Boolean) } interface EventsStrategy { fun isMessage(message: String?): Boolean fun isFileStart(message: String?): FileInfo? fun isFileCanceled(message: String?): CancelInfo? fun isFileFinish(message: String?): Boolean fun getCancellationMessage(byPartner: Boolean): String } data class FileInfo(val uid: Long, val name: String, val size: Long) data class CancelInfo(val byPartner: Boolean) }
apache-2.0
31b6dc6203c1e7c31342620be958fe64
31.533156
106
0.532654
5.96837
false
false
false
false
square/okio
okio/src/commonMain/kotlin/okio/ForwardingFileSystem.kt
1
8759
/* * Copyright (C) 2020 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 okio import kotlin.jvm.JvmName /** * A [FileSystem] that forwards calls to another, intended for subclassing. * * ### Fault Injection * * You can use this to deterministically trigger file system failures in tests. This is useful to * confirm that your program behaves correctly even if its file system operations fail. For example, * this subclass fails every access of files named `unlucky.txt`: * * ``` * val faultyFileSystem = object : ForwardingFileSystem(FileSystem.SYSTEM) { * override fun onPathParameter(path: Path, functionName: String, parameterName: String): Path { * if (path.name == "unlucky.txt") throw IOException("synthetic failure!") * return path * } * } * ``` * * You can fail specific operations by overriding them directly: * * ``` * val faultyFileSystem = object : ForwardingFileSystem(FileSystem.SYSTEM) { * override fun delete(path: Path) { * throw IOException("synthetic failure!") * } * } * ``` * * ### Observability * * You can extend this to verify which files your program accesses. This is a testing file system * that records accesses as they happen: * * ``` * class LoggingFileSystem : ForwardingFileSystem(FileSystem.SYSTEM) { * val log = mutableListOf<String>() * * override fun onPathParameter(path: Path, functionName: String, parameterName: String): Path { * log += "$functionName($parameterName=$path)" * return path * } * } * ``` * * This makes it easy for tests to assert exactly which files were accessed. * * ``` * @Test * fun testMergeJsonReports() { * createSampleJsonReports() * loggingFileSystem.log.clear() * * mergeJsonReports() * * assertThat(loggingFileSystem.log).containsExactly( * "list(dir=json_reports)", * "source(file=json_reports/2020-10.json)", * "source(file=json_reports/2020-12.json)", * "source(file=json_reports/2020-11.json)", * "sink(file=json_reports/2020-all.json)" * ) * } * ``` * * ### Transformations * * Subclasses can transform file names and content. * * For example, your program may be written to operate on a well-known directory like `/etc/` or * `/System`. You can rewrite paths to make such operations safer to test. * * You may also transform file content to apply application-layer encryption or compression. This * is particularly useful in situations where it's difficult or impossible to enable those features * in the underlying file system. * * ### Abstract Functions Only * * Some file system functions like [copy] are implemented by using other features. These are the * non-abstract functions in the [FileSystem] interface. * * **This class forwards only the abstract functions;** non-abstract functions delegate to the * other functions of this class. If desired, subclasses may override non-abstract functions to * forward them. */ abstract class ForwardingFileSystem( /** [FileSystem] to which this instance is delegating. */ @get:JvmName("delegate") val delegate: FileSystem ) : FileSystem() { /** * Invoked each time a path is passed as a parameter to this file system. This returns the path to * pass to [delegate], which should be [path] itself or a path on [delegate] that corresponds to * it. * * Subclasses may override this to log accesses, fail on unexpected accesses, or map paths across * file systems. * * The base implementation returns [path]. * * Note that this function will be called twice for calls to [atomicMove]; once for the source * file and once for the target file. * * @param path the path passed to any of the functions of this. * @param functionName a string like "canonicalize", "metadataOrNull", or "appendingSink". * @param parameterName a string like "path", "file", "source", or "target". * @return the path to pass to [delegate] for the same parameter. */ open fun onPathParameter(path: Path, functionName: String, parameterName: String): Path = path /** * Invoked each time a path is returned by [delegate]. This returns the path to return to the * caller, which should be [path] itself or a path on this that corresponds to it. * * Subclasses may override this to log accesses, fail on unexpected path accesses, or map * directories or path names. * * The base implementation returns [path]. * * @param path the path returned by any of the functions of this. * @param functionName a string like "canonicalize" or "list". * @return the path to return to the caller. */ open fun onPathResult(path: Path, functionName: String): Path = path @Throws(IOException::class) override fun canonicalize(path: Path): Path { val path = onPathParameter(path, "canonicalize", "path") val result = delegate.canonicalize(path) return onPathResult(result, "canonicalize") } @Throws(IOException::class) override fun metadataOrNull(path: Path): FileMetadata? { val path = onPathParameter(path, "metadataOrNull", "path") val metadataOrNull = delegate.metadataOrNull(path) ?: return null if (metadataOrNull.symlinkTarget == null) return metadataOrNull val symlinkTarget = onPathResult(metadataOrNull.symlinkTarget, "metadataOrNull") return metadataOrNull.copy(symlinkTarget = symlinkTarget) } @Throws(IOException::class) override fun list(dir: Path): List<Path> { val dir = onPathParameter(dir, "list", "dir") val result = delegate.list(dir) val paths = result.mapTo(mutableListOf()) { onPathResult(it, "list") } paths.sort() return paths } override fun listOrNull(dir: Path): List<Path>? { val dir = onPathParameter(dir, "listOrNull", "dir") val result = delegate.listOrNull(dir) ?: return null val paths = result.mapTo(mutableListOf()) { onPathResult(it, "listOrNull") } paths.sort() return paths } override fun listRecursively(dir: Path, followSymlinks: Boolean): Sequence<Path> { val dir = onPathParameter(dir, "listRecursively", "dir") val result = delegate.listRecursively(dir, followSymlinks) return result.map { onPathResult(it, "listRecursively") } } @Throws(IOException::class) override fun openReadOnly(file: Path): FileHandle { val file = onPathParameter(file, "openReadOnly", "file") return delegate.openReadOnly(file) } @Throws(IOException::class) override fun openReadWrite(file: Path, mustCreate: Boolean, mustExist: Boolean): FileHandle { val file = onPathParameter(file, "openReadWrite", "file") return delegate.openReadWrite(file, mustCreate, mustExist) } @Throws(IOException::class) override fun source(file: Path): Source { val file = onPathParameter(file, "source", "file") return delegate.source(file) } @Throws(IOException::class) override fun sink(file: Path, mustCreate: Boolean): Sink { val file = onPathParameter(file, "sink", "file") return delegate.sink(file, mustCreate) } @Throws(IOException::class) override fun appendingSink(file: Path, mustExist: Boolean): Sink { val file = onPathParameter(file, "appendingSink", "file") return delegate.appendingSink(file, mustExist) } @Throws(IOException::class) override fun createDirectory(dir: Path, mustCreate: Boolean) { val dir = onPathParameter(dir, "createDirectory", "dir") delegate.createDirectory(dir, mustCreate) } @Throws(IOException::class) override fun atomicMove(source: Path, target: Path) { val source = onPathParameter(source, "atomicMove", "source") val target = onPathParameter(target, "atomicMove", "target") delegate.atomicMove(source, target) } @Throws(IOException::class) override fun delete(path: Path, mustExist: Boolean) { val path = onPathParameter(path, "delete", "path") delegate.delete(path, mustExist) } @Throws(IOException::class) override fun createSymlink(source: Path, target: Path) { val source = onPathParameter(source, "createSymlink", "source") val target = onPathParameter(target, "createSymlink", "target") delegate.createSymlink(source, target) } override fun toString() = "${this::class.simpleName}($delegate)" }
apache-2.0
1706b466d1c215fb699d7200b00ace45
35.194215
100
0.704989
4.027126
false
false
false
false
ursjoss/sipamato
core/core-web/src/main/java/ch/difty/scipamato/core/web/paper/common/PaperPanel.kt
1
42074
package ch.difty.scipamato.core.web.paper.common import ch.difty.scipamato.common.entity.CodeClassId import ch.difty.scipamato.common.entity.FieldEnumType import ch.difty.scipamato.common.web.LABEL_RESOURCE_TAG import ch.difty.scipamato.common.web.LABEL_TAG import ch.difty.scipamato.common.web.Mode import ch.difty.scipamato.common.web.component.SerializableSupplier import ch.difty.scipamato.core.AttachmentAware import ch.difty.scipamato.core.NewsletterAware import ch.difty.scipamato.core.entity.Code import ch.difty.scipamato.core.entity.CodeBoxAware import ch.difty.scipamato.core.entity.CodeClass import ch.difty.scipamato.core.entity.CoreEntity import ch.difty.scipamato.core.entity.IdScipamatoEntity import ch.difty.scipamato.core.entity.Paper.PaperFields import ch.difty.scipamato.core.entity.PaperAttachment import ch.difty.scipamato.core.entity.newsletter.NewsletterTopic import ch.difty.scipamato.core.web.common.BasePanel import ch.difty.scipamato.core.web.common.SelfUpdateBroadcastingBehavior import ch.difty.scipamato.core.web.common.SelfUpdateEvent import ch.difty.scipamato.core.web.model.CodeClassModel import ch.difty.scipamato.core.web.model.CodeModel import ch.difty.scipamato.core.web.model.NewsletterTopicModel import ch.difty.scipamato.core.web.paper.jasper.JasperPaperDataSource import ch.difty.scipamato.core.web.paper.jasper.summary.PaperSummaryDataSource import ch.difty.scipamato.core.web.paper.jasper.summaryshort.PaperSummaryShortDataSource import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapAjaxLink import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapButton import de.agilecoders.wicket.core.markup.html.bootstrap.button.ButtonBehavior import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons import de.agilecoders.wicket.core.markup.html.bootstrap.image.GlyphIconType import de.agilecoders.wicket.core.markup.html.bootstrap.image.IconType import de.agilecoders.wicket.core.markup.html.bootstrap.tabs.BootstrapTabbedPanel import de.agilecoders.wicket.extensions.markup.html.bootstrap.fileUpload.DropZoneFileUpload import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.checkboxx.CheckBoxX import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.select.BootstrapMultiSelect import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.select.BootstrapSelect import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.select.BootstrapSelectConfig import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType import org.apache.wicket.AttributeModifier import org.apache.wicket.PageReference import org.apache.wicket.ajax.AjaxRequestTarget import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior import org.apache.wicket.ajax.form.OnChangeAjaxBehavior import org.apache.wicket.bean.validation.PropertyValidator import org.apache.wicket.behavior.AttributeAppender import org.apache.wicket.event.Broadcast import org.apache.wicket.event.IEvent import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable import org.apache.wicket.extensions.markup.html.tabs.AbstractTab import org.apache.wicket.extensions.markup.html.tabs.ITab import org.apache.wicket.markup.html.basic.Label import org.apache.wicket.markup.html.form.CheckBox import org.apache.wicket.markup.html.form.ChoiceRenderer import org.apache.wicket.markup.html.form.Form import org.apache.wicket.markup.html.form.FormComponent import org.apache.wicket.markup.html.form.IChoiceRenderer import org.apache.wicket.markup.html.form.TextArea import org.apache.wicket.markup.html.form.TextField import org.apache.wicket.markup.html.form.validation.AbstractFormValidator import org.apache.wicket.markup.html.form.validation.IFormValidator import org.apache.wicket.markup.html.link.ResourceLink import org.apache.wicket.markup.html.panel.Panel import org.apache.wicket.model.ChainingModel import org.apache.wicket.model.CompoundPropertyModel import org.apache.wicket.model.IModel import org.apache.wicket.model.Model import org.apache.wicket.model.PropertyModel import org.apache.wicket.model.StringResourceModel import org.apache.wicket.validation.IValidator private const val CODES_CLASS_BASE_NAME = "codesClass" @Suppress("SameParameterValue") abstract class PaperPanel<T>( id: String, model: IModel<T>?, mode: Mode, val callingPage: PageReference?, protected val tabIndexModel: IModel<Int>, ) : BasePanel<T>( id, model, mode ) where T : CodeBoxAware, T : NewsletterAware, T : AttachmentAware { private var summaryLink: ResourceLink<Void>? = null private var summaryShortLink: ResourceLink<Void>? = null var authors: TextArea<String>? = null var firstAuthor: TextField<String>? = null var title: TextArea<Any>? = null var location: TextField<Any>? = null var publicationYear: TextField<Any>? = null var pmId: TextField<Any>? = null var doi: TextField<Any>? = null var originalAbstract: TextArea<String>? = null private var pubmedRetrieval: BootstrapAjaxLink<Void>? = null private var attachments: DataTable<PaperAttachment, String>? = null private var submit: BootstrapButton? = null private val newsletterTopicChoice = NewsletterTopicModel(localization) private lateinit var form: Form<T> internal constructor( id: String, model: IModel<T>?, mode: Mode, ) : this( id = id, model = model, mode = mode, callingPage = null, tabIndexModel = Model.of<Int>(0) ) protected fun getAttachments(): DataTable<PaperAttachment, String> = attachments!! public override fun onInitialize() { super.onInitialize() form = object : Form<T>("form", CompoundPropertyModel(model)) { override fun onSubmit() { super.onSubmit() onFormSubmit() } }.apply { setMultiPart(true) }.also { queue(it) } queueHeaderFields() queueTabPanel("tabs") queuePubmedRetrievalLink("pubmedRetrieval") } protected abstract fun onFormSubmit() fun getForm(): Form<T> = form private fun queueHeaderFields() { queueAuthorComplex(PaperFields.AUTHORS.fieldName, PaperFields.FIRST_AUTHOR.fieldName, PaperFields.FIRST_AUTHOR_OVERRIDDEN.fieldName) title = TextArea(PaperFields.TITLE.fieldName) val pm = paperIdManager queue(newNavigationButton("previous", GlyphIconType.stepbackward, { pm.hasPrevious() }) { pm.previous() pm.itemWithFocus }) queue(newNavigationButton("next", GlyphIconType.stepforward, { pm.hasNext() }) { pm.next() pm.itemWithFocus }) queueFieldAndLabel(title!!, PropertyValidator<Any>()) location = TextField(PaperFields.LOCATION.fieldName) queueFieldAndLabel(location!!, PropertyValidator<Any>()) publicationYear = TextField(PaperFields.PUBL_YEAR.fieldName) queueFieldAndLabel(publicationYear!!, PropertyValidator<Any>()) pmId = TextField(PaperFields.PMID.fieldName) pmId!!.add(newPmIdChangeBehavior()) queueFieldAndLabel(pmId!!) doi = TextField(PaperFields.DOI.fieldName) queueFieldAndLabel(doi!!, PropertyValidator<Any>()) addDisableBehavior(title!!, location!!, publicationYear!!, pmId!!, doi!!) queueNumberField(PaperFields.NUMBER.fieldName) val id = newSelfUpdatingTextField<Int>(IdScipamatoEntity.IdScipamatoEntityFields.ID.fieldName) id.isEnabled = isSearchMode queueFieldAndLabel(id) val created = newSelfUpdatingTextField<String>(CoreEntity.CoreEntityFields.CREATED_DV.fieldName) created.isEnabled = isSearchMode queueFieldAndLabel(created) val modified = newSelfUpdatingTextField<String>(CoreEntity.CoreEntityFields.MODIFIED_DV.fieldName) modified.isEnabled = isSearchMode queueFieldAndLabel(modified) makeAndQueueBackButton("back") { paperIdManager.isModified } queue(newExcludeButton("exclude")) makeAndQueueSubmitButton("submit") summaryLink = makeSummaryLink("summary") form.addOrReplace(summaryLink) summaryShortLink = makeSummaryShortLink("summaryShort") form.addOrReplace(summaryShortLink) considerAddingMoreValidation() val addRemoveNewsletter: BootstrapAjaxLink<Void> = object : BootstrapAjaxLink<Void>("modAssociation", Buttons.Type.Primary) { override fun onInitialize() { super.onInitialize() add(ButtonBehavior() .setType(Buttons.Type.Info) .setSize(Buttons.Size.Medium)) } override fun onClick(target: AjaxRequestTarget) { modifyNewsletterAssociation(target) } override fun onConfigure() { super.onConfigure() isVisible = shallBeVisible() isEnabled = shallBeEnabled() add(AttributeModifier(TITLE_ATTR, titleResourceModel)) setIconType(iconType) } // Hide if in EditMode // Otherwise show if we have an open newsletter or if it is already assigned to a (closed) newsletter private fun shallBeVisible(): Boolean = isEditMode && (isaNewsletterInStatusWip() || isAssociatedWithNewsletter) private fun shallBeEnabled(): Boolean = !isAssociatedWithNewsletter || isAssociatedWithWipNewsletter private val titleResourceModel: StringResourceModel get() = StringResourceModel("modNewsletterAssociation-$titleKey.title", this, [email protected]) private val titleKey: String get() { if (!isAssociatedWithNewsletter) return "add" return if (isAssociatedWithWipNewsletter) "del" else "closed" } // Show the + icon if not assigned to a newsletter yet // Otherwise: Show the open envelope if assigned to current, closed envelope if assigned to closed nl. private val iconType: IconType get() = if (!isAssociatedWithNewsletter) FontAwesome5IconType.plus_square_s else if (isAssociatedWithWipNewsletter) FontAwesome5IconType.envelope_open_r else FontAwesome5IconType.envelope_r } addRemoveNewsletter.outputMarkupPlaceholderTag = true queue(addRemoveNewsletter) } private fun <U> newSelfUpdatingTextField(id: String): TextField<U> = object : TextField<U>(id) { override fun onEvent(event: IEvent<*>) { super.onEvent(event) if (event.payload.javaClass == SelfUpdateEvent::class.java) { (event.payload as SelfUpdateEvent).target.add(this) event.dontBroadcastDeeper() } } } private fun queueNumberField(id: String) { val labelModel: IModel<String> = Model.of( "${firstWordOfBrand()}-${StringResourceModel("$id$LABEL_RESOURCE_TAG", this, null).string}") queue(Label("$id$LABEL_TAG", labelModel)) TextField<Int>(id).apply { label = labelModel outputMarkupId = true if (isEditMode) add(PropertyValidator<Int>() as IValidator<Int>) }.also { queue(it) addDisableBehavior(it) } } private fun firstWordOfBrand(): String { val brand = properties.brand val divider = " " return if (brand.contains(divider)) brand.substring(0, brand.indexOf(divider)) else brand } /** * If more validators are required, override this */ protected open fun considerAddingMoreValidation() { // no default implementation } private fun newPmIdChangeBehavior(): OnChangeAjaxBehavior = object : OnChangeAjaxBehavior() { override fun onUpdate(target: AjaxRequestTarget) { target.add(pubmedRetrieval) } } private fun queueTabPanel(tabId: String) { mutableListOf<ITab>().apply { add(object : AbstractTab(StringResourceModel("tab1$LABEL_RESOURCE_TAG", this@PaperPanel, null)) { override fun getPanel(panelId: String): Panel = TabPanel1(panelId, form.model) }) add(object : AbstractTab(StringResourceModel("tab2$LABEL_RESOURCE_TAG", this@PaperPanel, null)) { override fun getPanel(panelId: String): Panel = TabPanel2(panelId, form.model) }) add(object : AbstractTab(StringResourceModel("tab3$LABEL_RESOURCE_TAG", this@PaperPanel, null)) { override fun getPanel(panelId: String): Panel = TabPanel3(panelId, form.model) }) add(object : AbstractTab(StringResourceModel("tab4$LABEL_RESOURCE_TAG", this@PaperPanel, null)) { override fun getPanel(panelId: String): Panel = TabPanel4(panelId, form.model) }) add(object : AbstractTab(StringResourceModel("tab5$LABEL_RESOURCE_TAG", this@PaperPanel, null)) { override fun getPanel(panelId: String): Panel = TabPanel5(panelId, form.model) }) add(object : AbstractTab(StringResourceModel("tab6$LABEL_RESOURCE_TAG", this@PaperPanel, null)) { override fun getPanel(panelId: String): Panel = TabPanel6(panelId, form.model) }) add(object : AbstractTab(StringResourceModel("tab7$LABEL_RESOURCE_TAG", this@PaperPanel, null)) { override fun getPanel(panelId: String): Panel = TabPanel7(panelId, form.model) }) }.also { queue(BootstrapTabbedPanel(tabId, it, tabIndexModel)) } } /* * The authors field determines the firstAuthor field, but only unless overridden. * Changes in the author field (if not overridden) or in the override checkbox * can have an effect on the firstAuthor field (enabled, content) */ private fun queueAuthorComplex(authorsId: String, firstAuthorId: String, firstAuthorOverriddenId: String) { authors = TextArea(authorsId) authors!!.escapeModelStrings = false queueFieldAndLabel(authors!!, PropertyValidator<Any>()) val firstAuthorOverriddenModel = PropertyModel<Boolean>(model, firstAuthorOverriddenId) val firstAuthorOverridden = CheckBoxX(firstAuthorOverriddenId, firstAuthorOverriddenModel) firstAuthorOverridden .config .withThreeState(isSearchMode) .withUseNative(true) queueCheckBoxAndLabel(firstAuthorOverridden) firstAuthor = makeFirstAuthor(firstAuthorId, firstAuthorOverridden) firstAuthor!!.outputMarkupId = true queueFieldAndLabel(firstAuthor!!) addAuthorBehavior(authors!!, firstAuthorOverridden, firstAuthor!!) addDisableBehavior(authors!!, firstAuthor!!) } private fun addDisableBehavior(vararg components: FormComponent<*>) { if (isEditMode || isSearchMode) for (fc in components) { fc.add(object : AjaxFormComponentUpdatingBehavior("input") { override fun onUpdate(target: AjaxRequestTarget) { disableButton(target, submit!!) } }) } } private fun disableButton(target: AjaxRequestTarget, vararg buttons: BootstrapButton) { for (b in buttons) { if (b.isEnabled) { b.isEnabled = false target.add(b) } } } /** * override if special behavior is required * * @param firstAuthorId the firstAuthorId as string * @param firstAuthorOverridden the checkbox for firstAuthorOverridden * @return the first author TextField */ protected open fun makeFirstAuthor(firstAuthorId: String, firstAuthorOverridden: CheckBox): TextField<String> = TextField(firstAuthorId) /** * override if special behavior is required * * @param authors text area for the authors field * @param firstAuthorOverridden checkbox for firstAuthorOverridden * @param firstAuthor text field for firstAuthor */ protected open fun addAuthorBehavior( authors: TextArea<String>, firstAuthorOverridden: CheckBox, firstAuthor: TextField<String>, ) { // not default implementation } protected abstract fun newNavigationButton( id: String, icon: GlyphIconType, isEnabled: SerializableSupplier<Boolean>, idSupplier: SerializableSupplier<Long?>?, ): BootstrapButton private fun makeAndQueueBackButton(id: String, forceRequerySupplier: SerializableSupplier<Boolean>) { object : BootstrapButton(id, StringResourceModel("button.back.label"), Buttons.Type.Default) { override fun onSubmit() { if (java.lang.Boolean.TRUE == forceRequerySupplier.get()) restartSearchInPaperSearchPage() else if (callingPage != null) setResponsePage(callingPage.page) } override fun onConfigure() { super.onConfigure() isVisible = callingPage != null } }.apply { defaultFormProcessing = false add(AttributeModifier(TITLE_ATTR, StringResourceModel("button.back.title", this@PaperPanel, null).string)) }.also { queue(it) } } protected abstract fun restartSearchInPaperSearchPage() protected abstract fun newExcludeButton(id: String): BootstrapButton private fun makeAndQueueSubmitButton(id: String) { submit = object : BootstrapButton(id, StringResourceModel(submitLinkResourceLabel), Buttons.Type.Default) { override fun onSubmit() { super.onSubmit() onFormSubmit() doOnSubmit() } /** * Refresh the summary link to use the updated model */ override fun onAfterSubmit() { super.onAfterSubmit() summaryLink = makeSummaryLink("summary") form.addOrReplace(summaryLink) summaryShortLink = makeSummaryShortLink("summaryShort") form.addOrReplace(summaryShortLink) } override fun onEvent(event: IEvent<*>) { super.onEvent(event) enableButton(this, !isViewMode, event) } }.apply { defaultFormProcessing = true isEnabled = !isViewMode setVisible(!isViewMode) }.also { queue(it) } } protected abstract fun doOnSubmit() private fun enableButton(button: BootstrapButton, enabled: Boolean, event: IEvent<*>) { if (event .payload .javaClass == SelfUpdateEvent::class.java && button.isVisible) { button.isEnabled = enabled (event.payload as SelfUpdateEvent) .target .add(button) event.dontBroadcastDeeper() } } private fun makeSummaryLink(id: String): ResourceLink<Void> { return makePdfResourceLink(id, summaryDataSource) } /** * @return [PaperSummaryDataSource] */ protected abstract val summaryDataSource: PaperSummaryDataSource? private fun makeSummaryShortLink(id: String): ResourceLink<Void> { return makePdfResourceLink(id, summaryShortDataSource) } /** * @return [PaperSummaryShortDataSource] */ protected abstract val summaryShortDataSource: PaperSummaryShortDataSource? private fun makePdfResourceLink(id: String, dataSource: JasperPaperDataSource<*>?): ResourceLink<Void> { val button = "button." val link: ResourceLink<Void> = object : ResourceLink<Void>(id, dataSource) { override fun onInitialize() { super.onInitialize() if (isVisible) add(ButtonBehavior() .setType(Buttons.Type.Info) .setBlock(true) .setSize(Buttons.Size.Medium)) } override fun onEvent(event: IEvent<*>) { super.onEvent(event) if (event .payload .javaClass == SelfUpdateEvent::class.java) { if (isVisible) { isEnabled = false add(AttributeModifier(TITLE_ATTR, StringResourceModel("$button$id.title.disabled", this, null).string)) (event.payload as SelfUpdateEvent) .target .add(this) } event.dontBroadcastDeeper() } } } link.outputMarkupId = true link.outputMarkupPlaceholderTag = true link.body = StringResourceModel("$button$id.label") link.isVisible = !isSearchMode link.add(AttributeModifier(TITLE_ATTR, StringResourceModel("$button$id.title", this, null).string)) return link } private abstract inner class AbstractTabPanel(id: String, model: IModel<*>) : Panel(id, model) { abstract fun tabIndex(): Int fun queueTo(fieldType: FieldEnumType): TextArea<String> = queueTo(fieldType, false, null) fun queueTo(fieldType: FieldEnumType, pv: PropertyValidator<*>?) { queueTo(fieldType, false, pv) } fun queueNewFieldTo(fieldType: FieldEnumType) { queueTo(fieldType, true, null) } fun queueTo(fieldType: FieldEnumType, newField: Boolean, pv: PropertyValidator<*>?): TextArea<String> { val id = fieldType.fieldName val field = makeField(id, newField) field.outputMarkupId = true val labelModel = StringResourceModel(id + LABEL_RESOURCE_TAG, this, null) queue(Label(id + LABEL_TAG, labelModel)) field.label = labelModel if (newField) { addNewFieldSpecificAttributes(field) } if (pv != null && isEditMode) { field.add(pv) } addDisableBehavior(field) queue(field) return field } /** * The new fields are present on the page more than once, they need to be able * to handle the [NewFieldChangeEvent]. */ fun makeField(id: String, newField: Boolean): TextArea<String> = if (!newField) { TextArea(id) } else { object : TextArea<String>(id) { override fun onEvent(event: IEvent<*>) { if (event.payload.javaClass == NewFieldChangeEvent::class.java) { (event.payload as NewFieldChangeEvent).considerAddingToTarget(this) event.dontBroadcastDeeper() } } } } /** * New fields need to broadcast the [NewFieldChangeEvent] and have a * special visual indication that they are a new field. */ private fun addNewFieldSpecificAttributes(field: TextArea<String>) { field.add(AttributeAppender("class", " newField")) field.add(object : AjaxFormComponentUpdatingBehavior(CHANGE) { override fun onUpdate(target: AjaxRequestTarget) { val id = field.id val markupId = field.markupId send(page, Broadcast.BREADTH, NewFieldChangeEvent(target, id, markupId)) } }) } override fun onConfigure() { super.onConfigure() tabIndexModel.setObject(tabIndex()) } fun queueSearchOnlyTextFieldName(field: FieldEnumType) { val labelModel = StringResourceModel("${field.fieldName}$LABEL_RESOURCE_TAG", this, null) object : TextField<String>(field.fieldName) { override fun onConfigure() { super.onConfigure() isVisible = isSearchMode } }.apply { outputMarkupId = true label = labelModel }.also { queue(it) queue(object : Label("${field.fieldName}$LABEL_TAG", labelModel) { override fun onConfigure() { super.onConfigure() isVisible = isSearchMode } }) } } } private inner class TabPanel1(id: String, model: IModel<T>) : AbstractTabPanel(id, model) { override fun tabIndex(): Int = 0 override fun onInitialize() { super.onInitialize() val tab1Form: Form<T> = object : Form<T>("tab1Form", CompoundPropertyModel(model)) { override fun onSubmit() { super.onSubmit() onFormSubmit() } } tab1Form.add(SelfUpdateBroadcastingBehavior(page)) queue(tab1Form) queueTo(PaperFields.GOALS, PropertyValidator<Any>()) queueTo(PaperFields.POPULATION) queueTo(PaperFields.METHODS) queueNewFieldTo(PaperFields.POPULATION_PLACE) queueNewFieldTo(PaperFields.POPULATION_PARTICIPANTS) queueNewFieldTo(PaperFields.POPULATION_DURATION) queueNewFieldTo(PaperFields.EXPOSURE_POLLUTANT) queueNewFieldTo(PaperFields.EXPOSURE_ASSESSMENT) queueNewFieldTo(PaperFields.METHOD_STUDY_DESIGN) queueNewFieldTo(PaperFields.METHOD_OUTCOME) queueNewFieldTo(PaperFields.METHOD_STATISTICS) queueNewFieldTo(PaperFields.METHOD_CONFOUNDERS) } } private inner class TabPanel2(id: String, model: IModel<T>) : AbstractTabPanel(id, model) { override fun tabIndex(): Int = 1 override fun onInitialize() { super.onInitialize() val tab2Form: Form<T> = object : Form<T>("tab2Form", CompoundPropertyModel(model)) { override fun onSubmit() { super.onSubmit() onFormSubmit() } } tab2Form.add(SelfUpdateBroadcastingBehavior(page)) queue(tab2Form) queueTo(PaperFields.RESULT) queueTo(PaperFields.COMMENT) queueTo(PaperFields.INTERN) queueNewFieldTo(PaperFields.RESULT_MEASURED_OUTCOME) queueNewFieldTo(PaperFields.RESULT_EXPOSURE_RANGE) queueNewFieldTo(PaperFields.RESULT_EFFECT_ESTIMATE) queueNewFieldTo(PaperFields.CONCLUSION) } } private inner class TabPanel3 constructor(id: String, model: IModel<T?>) : AbstractTabPanel(id, model) { override fun tabIndex(): Int = 2 override fun onInitialize() { super.onInitialize() val tab3Form: Form<T> = object : Form<T>("tab3Form", CompoundPropertyModel(model)) { override fun onSubmit() { super.onSubmit() onFormSubmit() } } tab3Form.isMultiPart = true tab3Form.add(SelfUpdateBroadcastingBehavior(page)) queue(tab3Form) val codeClassModel = CodeClassModel(localization) val codeClasses = codeClassModel.getObject() makeCodeClass1Complex(codeClasses, tab3Form) makeCodeClassComplex(CodeClassId.CC2, codeClasses) makeCodeClassComplex(CodeClassId.CC3, codeClasses) makeCodeClassComplex(CodeClassId.CC4, codeClasses) makeCodeClassComplex(CodeClassId.CC5, codeClasses) makeCodeClassComplex(CodeClassId.CC6, codeClasses) makeCodeClassComplex(CodeClassId.CC7, codeClasses) makeCodeClassComplex(CodeClassId.CC8, codeClasses) } private fun makeCodeClass1Complex(codeClasses: List<CodeClass>, form: Form<T>) { val mainCodeOfCodeClass1 = TextField<String>(PaperFields.MAIN_CODE_OF_CODECLASS1.fieldName) val codeClass1 = makeCodeClassComplex(CodeClassId.CC1, codeClasses) addCodeClass1ChangeBehavior(mainCodeOfCodeClass1, codeClass1) addMainCodeOfClass1(mainCodeOfCodeClass1) if (isEditMode) form.add(CodeClass1ConsistencyValidator(codeClass1, mainCodeOfCodeClass1) as IFormValidator) addDisableBehavior(codeClass1) } private fun addMainCodeOfClass1(field: TextField<String>) { val id = field.id val labelModel = StringResourceModel("$id$LABEL_RESOURCE_TAG", this, null) queue(Label(id + LABEL_TAG, labelModel)) field.add(PropertyValidator<String>() as IValidator<String>) field.outputMarkupId = true field.label = labelModel field.isEnabled = isSearchMode queue(field) } private fun makeCodeClassComplex(codeClassId: CodeClassId, codeClasses: List<CodeClass?>): BootstrapMultiSelect<Code> { val id = codeClassId.id val className = codeClasses.filterNotNull().filter { it.id != null && it.id == id }.map { it.name }.firstOrNull() ?: codeClassId.name queue(Label("$CODES_CLASS_BASE_NAME${id}Label", Model.of(className))) val model: ChainingModel<List<Code>> = object : ChainingModel<List<Code>>([email protected]) { @Suppress("UNCHECKED_CAST") val modelObject: CodeBoxAware get() = (target as IModel<CodeBoxAware>).`object` override fun getObject(): List<Code> = modelObject.getCodesOf(codeClassId) override fun setObject(codes: List<Code>) { modelObject.clearCodesOf(codeClassId) if (codes.isNotEmpty()) modelObject.addCodes(codes) } } val choices = CodeModel(codeClassId, localization) val choiceRenderer: IChoiceRenderer<Code> = ChoiceRenderer(CoreEntity.CoreEntityFields.DISPLAY_VALUE.fieldName, Code.CodeFields.CODE.fieldName) val noneSelectedModel = StringResourceModel("codes.noneSelected", this, null) val selectAllModel = StringResourceModel(SELECT_ALL_RESOURCE_TAG, this, null) val deselectAllModel = StringResourceModel(DESELECT_ALL_RESOURCE_TAG, this, null) val config = BootstrapSelectConfig() .withMultiple(true) .withActionsBox(choices.getObject().size > properties.multiSelectBoxActionBoxWithMoreEntriesThan) .withSelectAllText(selectAllModel.string) .withDeselectAllText(deselectAllModel.string) .withNoneSelectedText(noneSelectedModel.getObject()) .withLiveSearch(true) .withLiveSearchStyle("contains") val multiSelect = BootstrapMultiSelect(CODES_CLASS_BASE_NAME + id, model, choices, choiceRenderer).with(config) multiSelect.add(AttributeModifier("data-width", "100%")) queue(multiSelect) addDisableBehavior(multiSelect) return multiSelect } } private inner class TabPanel4(id: String, model: IModel<T?>) : AbstractTabPanel(id, model) { override fun tabIndex(): Int = 3 override fun onInitialize() { super.onInitialize() val tab4Form: Form<T> = object : Form<T>("tab4Form", CompoundPropertyModel(model)) { override fun onSubmit() { super.onSubmit() onFormSubmit() } } tab4Form.add(SelfUpdateBroadcastingBehavior(page)) queue(tab4Form) queueNewFieldTo(PaperFields.METHOD_STUDY_DESIGN) queueNewFieldTo(PaperFields.METHOD_OUTCOME) queueNewFieldTo(PaperFields.POPULATION_PLACE) queueNewFieldTo(PaperFields.POPULATION_PARTICIPANTS) queueNewFieldTo(PaperFields.POPULATION_DURATION) queueNewFieldTo(PaperFields.EXPOSURE_POLLUTANT) queueNewFieldTo(PaperFields.EXPOSURE_ASSESSMENT) queueNewFieldTo(PaperFields.METHOD_STATISTICS) queueNewFieldTo(PaperFields.METHOD_CONFOUNDERS) queueNewFieldTo(PaperFields.RESULT_MEASURED_OUTCOME) queueNewFieldTo(PaperFields.RESULT_EXPOSURE_RANGE) queueNewFieldTo(PaperFields.RESULT_EFFECT_ESTIMATE) queueNewFieldTo(PaperFields.CONCLUSION) } } private inner class TabPanel5(id: String, model: IModel<T?>) : AbstractTabPanel(id, model) { override fun tabIndex(): Int = 4 override fun onInitialize() { super.onInitialize() val tab5Form: Form<T> = object : Form<T>("tab5Form", CompoundPropertyModel(model)) { override fun onSubmit() { super.onSubmit() onFormSubmit() } } tab5Form.add(SelfUpdateBroadcastingBehavior(page)) queue(tab5Form) originalAbstract = queueTo(PaperFields.ORIGINAL_ABSTRACT) addDisableBehavior(originalAbstract!!) } } private inner class TabPanel6(id: String, model: IModel<T?>) : AbstractTabPanel(id, model) { override fun tabIndex(): Int = 5 override fun onInitialize() { super.onInitialize() val tab6Form: Form<T> = object : Form<T>("tab6Form", CompoundPropertyModel(model)) { override fun onSubmit() { super.onSubmit() onFormSubmit() } } tab6Form.outputMarkupId = true tab6Form.isMultiPart = true tab6Form.add(SelfUpdateBroadcastingBehavior(page)) queue(tab6Form) queue(newDropZoneFileUpload()) attachments = newAttachmentTable("attachments") queue(attachments) queueSearchOnlyTextFieldName(PaperFields.ATTACHMENT_NAME_MASK) queueHasAttachments(PaperFields.HAS_ATTACHMENTS) } private fun queueHasAttachments(field: FieldEnumType) { val labelModel = StringResourceModel("${field.fieldName}$LABEL_RESOURCE_TAG", this, null) val checkBoxModel = PropertyModel<Boolean>(model, field.fieldName) object : CheckBoxX(field.fieldName, checkBoxModel) { override fun onConfigure() { super.onConfigure() isVisible = isSearchMode add(AttributeModifier(TITLE_ATTR, checkBoxModel)) } }.apply { config .withThreeState(true) .withUseNative(true) outputMarkupId = true label = labelModel }.also { queue(it) queue(object : Label("${field.fieldName}$LABEL_TAG", labelModel) { override fun onConfigure() { super.onConfigure() isVisible = isSearchMode } }) } } } private inner class TabPanel7(id: String, model: IModel<T?>) : AbstractTabPanel(id, model) { override fun tabIndex(): Int = 6 override fun onInitialize() { super.onInitialize() val tab7Form: Form<T> = object : Form<T>("tab7Form", CompoundPropertyModel(model)) { override fun onSubmit() { super.onSubmit() onFormSubmit() } } tab7Form.add(SelfUpdateBroadcastingBehavior(page)) queue(tab7Form) queueHeadline(PaperFields.NEWSLETTER_HEADLINE) makeAndQueueNewsletterTopicSelectBox("newsletterTopic") queueSearchOnlyTextFieldName(PaperFields.NEWSLETTER_ISSUE) } private fun queueHeadline(fieldType: FieldEnumType) { val id = fieldType.fieldName val field: TextArea<String> = object : TextArea<String>(id) { override fun onConfigure() { super.onConfigure() isEnabled = isSearchMode || isAssociatedWithNewsletter } } field.outputMarkupId = true val labelModel = StringResourceModel(id + LABEL_RESOURCE_TAG, this, null) queue(Label(id + LABEL_TAG, labelModel)) field.label = labelModel addDisableBehavior(field) queue(field) } private fun makeAndQueueNewsletterTopicSelectBox(id: String) { val model: ChainingModel<NewsletterTopic> = object : ChainingModel<NewsletterTopic>([email protected]) { @Suppress("UNCHECKED_CAST") val modelObject: NewsletterAware get() = (target as IModel<NewsletterAware>).`object` private val topics = newsletterTopicChoice.load() override fun getObject(): NewsletterTopic? = modelObject.newsletterTopicId?.let { topics.first { it.id == modelObject.newsletterTopicId } } override fun setObject(topic: NewsletterTopic) { modelObject.setNewsletterTopic(topic) } } val choiceRenderer: IChoiceRenderer<NewsletterTopic> = ChoiceRenderer(NewsletterTopic.NewsletterTopicFields.TITLE.fieldName, NewsletterTopic.NewsletterTopicFields.ID.fieldName) val noneSelectedModel = StringResourceModel("$id.noneSelected", this, null) val config = BootstrapSelectConfig() .withNoneSelectedText(noneSelectedModel.getObject()) .withLiveSearch(true) val topic = object : BootstrapSelect<NewsletterTopic>(id, model, newsletterTopicChoice, choiceRenderer) { override fun onConfigure() { super.onConfigure() isEnabled = isSearchMode || isAssociatedWithNewsletter } }.with(config) topic.isNullValid = true queue(topic) queue(Label(id + LABEL_TAG, StringResourceModel(id + LABEL_RESOURCE_TAG, this, null))) addDisableBehavior(topic) } } abstract val isAssociatedWithNewsletter: Boolean abstract val isAssociatedWithWipNewsletter: Boolean abstract fun isaNewsletterInStatusWip(): Boolean abstract fun modifyNewsletterAssociation(target: AjaxRequestTarget) abstract fun newAttachmentTable(id: String): DataTable<PaperAttachment, String> abstract fun newDropZoneFileUpload(): DropZoneFileUpload /** * override if needed * * @param mainCodeOfCodeClass1 * text field with mainCode of code class1 * @param codeClass1 * bootstrap multi-select for the codes of code class 1 */ protected open fun addCodeClass1ChangeBehavior( mainCodeOfCodeClass1: TextField<String>, codeClass1: BootstrapMultiSelect<Code>, ) { } internal class CodeClass1ConsistencyValidator(codeClass1: BootstrapMultiSelect<Code>, mainCodeOfCodeClass1: TextField<String>) : AbstractFormValidator() { private val components: Array<FormComponent<*>> = arrayOf(codeClass1, mainCodeOfCodeClass1) override fun getDependentFormComponents(): Array<FormComponent<*>> = components @Suppress("UNCHECKED_CAST") override fun validate(form: Form<*>) { val codeClass1 = components[0] as BootstrapMultiSelect<Code> val mainCode = components[1] if (!codeClass1.modelObject.isEmpty() && mainCode.modelObject == null) { val key = resourceKey() error(mainCode, "$key.mainCodeOfCodeclass1Required") } } companion object { private const val serialVersionUID = 1L } } private fun queuePubmedRetrievalLink(linkId: String) { pubmedRetrieval = object : BootstrapAjaxLink<Void>(linkId, Buttons.Type.Primary) { override fun onInitialize() { super.onInitialize() add(ButtonBehavior() .setType(Buttons.Type.Info) .setSize(Buttons.Size.Medium)) } override fun onClick(target: AjaxRequestTarget) { getPubmedArticleAndCompare(target) } override fun onConfigure() { super.onConfigure() isVisible = isEditMode if (hasPubMedId()) { isEnabled = true add(AttributeModifier(TITLE_ATTR, StringResourceModel("pubmedRetrieval.title", this, null).string)) } else { isEnabled = false add(AttributeModifier(TITLE_ATTR, StringResourceModel("pubmedRetrieval.title.disabled", this, null).string)) } } }.apply { outputMarkupPlaceholderTag = true setLabel(StringResourceModel("pubmedRetrieval.label", this, null)) }.also { queue(it) } } protected abstract fun hasPubMedId(): Boolean /** * override to do something with the pasted content * * @param target * the ajax request target */ protected open fun getPubmedArticleAndCompare(target: AjaxRequestTarget) { // no default implementation } companion object { private const val serialVersionUID = 1L protected const val TITLE_ATTR = "title" private const val CHANGE = "change" } }
gpl-3.0
56cf333cf3f34f4acd3a8e06408f35d2
42.509824
170
0.630936
4.879842
false
false
false
false
bitsydarel/DBWeather
dbweatherdata/src/main/java/com/dbeginc/dbweatherdata/proxies/local/weather/LocalWeather.kt
1
1783
/* * Copyright (C) 2017 Darel Bitsy * 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.dbeginc.dbweatherdata.proxies.local.weather import android.arch.persistence.room.Embedded import android.arch.persistence.room.Entity import android.support.annotation.RestrictTo import com.dbeginc.dbweatherdata.WEATHER_TABLE /** * Created by darel on 16.09.17. * * Local Weather Implementation * Primary keys are two fields from [LocalLocation] pojo * because setting the full pojo as primary key * will lead to bug like the coordinates may be different for the same location channelName */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @Entity( tableName = WEATHER_TABLE, primaryKeys = ["location_name", "country_code"] ) data class LocalWeather( @Embedded() var location: LocalLocation, val latitude: Double, val longitude: Double, val timezone: String, @Embedded(prefix = "current") val currently: LocalCurrently, @Embedded(prefix = "minutely") val minutely: LocalMinutely?, @Embedded(prefix = "hourly") val hourly: LocalHourly, @Embedded(prefix = "daily") var daily: LocalDaily, val alerts: List<LocalAlert>?, @Embedded(prefix = "flags") val flags: LocalFlags )
gpl-3.0
36b6cdfc00923df4f68451801587ce49
36.957447
91
0.720135
4.127315
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/delegatedProperty/genericDelegateUncheckedCast1.kt
1
824
// IGNORE_BACKEND: JS, NATIVE import kotlin.reflect.KProperty class Delegate<T>(var inner: T) { operator fun getValue(t: Any?, p: KProperty<*>): T = inner operator fun setValue(t: Any?, p: KProperty<*>, i: T) { inner = i } } val del = Delegate("zzz") class A { inner class B { var prop: String by del } } inline fun asFailsWithCCE(block: () -> Unit) { try { block() } catch (e: ClassCastException) { return } catch (e: Throwable) { throw AssertionError("Should throw ClassCastException, got $e") } throw AssertionError("Should throw ClassCastException, no exception thrown") } fun box(): String { val c = A().B() (del as Delegate<Int>).inner = 10 asFailsWithCCE { c.prop } // does not fail in JS due KT-8135. return "OK" }
apache-2.0
275d85aaf65a953f8ea924805b4f1ad0
20.684211
80
0.604369
3.678571
false
false
false
false
psenchanka/comant
comant-site/src/main/kotlin/com/psenchanka/comant/controller/LoginController.kt
1
1734
package com.psenchanka.comant.controller import com.psenchanka.comant.auth.BadCredentialsException import com.psenchanka.comant.dto.AuthenticationTokenDto import com.psenchanka.comant.dto.AuthorizationDto import com.psenchanka.comant.service.UserService import io.swagger.annotations.ApiOperation import io.swagger.annotations.ApiParam import io.swagger.annotations.ApiResponse import io.swagger.annotations.ApiResponses import org.springframework.beans.factory.annotation.Autowired import org.springframework.transaction.annotation.Transactional import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/api/login") open class LoginController @Autowired constructor(val userService: UserService) { @RequestMapping("", method = arrayOf(RequestMethod.POST)) @ApiOperation("Log in", notes = "Returns a JWT token that can be used for accessing protected API methods.") @ApiResponses( ApiResponse(code = 200, message = "OK"), ApiResponse(code = 403, message = "Bad credentials") ) @Transactional open fun login( @ApiParam("User credentials") @RequestBody credentials: AuthorizationDto ) : AuthenticationTokenDto { val (username, password) = credentials val user = userService.findById(username) if (user != null && user.passwordMatches(password)) { return AuthenticationTokenDto(userService.generateAccessToken(user)) } else { throw BadCredentialsException() } } }
mit
7e0a937a178be43ec6f57721f45129d5
40.309524
102
0.757209
4.926136
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/src/git4idea/rebase/GitAutoSquashCommitAction.kt
12
2490
// 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 git4idea.rebase import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog import com.intellij.vcs.log.VcsShortCommitDetails import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager internal abstract class GitAutoSquashCommitAction : GitSingleCommitEditingAction() { override fun actionPerformedAfterChecks(commitEditingData: SingleCommitEditingData) { val commit = commitEditingData.selectedCommit val project = commitEditingData.project val changeList = ChangeListManager.getInstance(project).defaultChangeList val repository = commitEditingData.repository val gitRepositoryManager = GitRepositoryManager.getInstance(project) val changes = changeList.changes.filter { gitRepositoryManager.getRepositoryForFileQuick(ChangesUtil.getFilePath(it)) == repository } val executors = repository.vcs.commitExecutors + if (getProhibitedStateMessage(commitEditingData, GitBundle.message("rebase.log.action.operation.rebase.name")) == null) { listOf(GitRebaseAfterCommitExecutor(project, repository, commit.id.asString() + "~")) } else { listOf() } CommitChangeListDialog.commitChanges(project, changes, changes, changeList, executors, true, null, getCommitMessage(commit), null, true) } protected abstract fun getCommitMessage(commit: VcsShortCommitDetails): String class GitRebaseAfterCommitExecutor(val project: Project, val repository: GitRepository, val hash: String) : CommitExecutor { override fun getActionText(): String = GitBundle.message("commit.action.commit.and.rebase.text") override fun createCommitSession(commitContext: CommitContext): CommitSession = CommitSession.VCS_COMMIT override fun supportsPartialCommit() = true } }
apache-2.0
bb6938b274efcf941d30a13ba1d66995
46
141
0.64498
5.737327
false
false
false
false
smmribeiro/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/data/VcsLogStatusBarProgress.kt
7
4185
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.data import com.intellij.CommonBundle import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.TaskInfo import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.ex.StatusBarEx import com.intellij.openapi.wm.ex.WindowManagerEx import com.intellij.util.Alarm import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.vcs.log.VcsLogBundle import com.intellij.vcs.log.VcsLogProvider import com.intellij.vcs.log.data.index.VcsLogBigRepositoriesList import com.intellij.vcs.log.data.index.VcsLogPersistentIndex import com.intellij.vcs.log.util.VcsLogUtil class VcsLogStatusBarProgress(project: Project, logProviders: Map<VirtualFile, VcsLogProvider>, vcsLogProgress: VcsLogProgress) : Disposable { private val disposableFlag = Disposer.newCheckedDisposable() private val roots = VcsLogPersistentIndex.getRootsForIndexing(logProviders) private val vcsName = VcsLogUtil.getVcsDisplayName(project, roots.mapNotNull { logProviders[it] }) private val statusBar: StatusBarEx by lazy { (WindowManager.getInstance() as WindowManagerEx).findFrameFor(project)!!.statusBar as StatusBarEx } private val alarm = lazy { Alarm(Alarm.ThreadToUse.SWING_THREAD, this) } private var progress: MyProgressIndicator? = null init { vcsLogProgress.addProgressIndicatorListener(MyProgressListener(), this) Disposer.register(this, disposableFlag) } @RequiresEdt fun start() { alarm.value.addRequest(Runnable { if (progress == null) { progress = MyProgressIndicator().also { statusBar.addProgress(it, it.taskInfo) } } }, Registry.intValue("vcs.log.index.progress.delay.millis")) } @RequiresEdt fun stop() { if (alarm.isInitialized()) alarm.value.cancelAllRequests() progress?.let { it.finish(it.taskInfo) } progress = null } override fun dispose() { stop() } inner class MyProgressListener : VcsLogProgress.ProgressListener { override fun progressStarted(keys: MutableCollection<out VcsLogProgress.ProgressKey>) { if (disposableFlag.isDisposed) return if (keys.contains(VcsLogPersistentIndex.INDEXING)) { start() } } override fun progressStopped() { if (disposableFlag.isDisposed) return stop() } override fun progressChanged(keys: MutableCollection<out VcsLogProgress.ProgressKey>) { if (disposableFlag.isDisposed) return if (keys.contains(VcsLogPersistentIndex.INDEXING)) { start() } else { stop() } } } inner class MyProgressIndicator : AbstractProgressIndicatorExBase() { internal val taskInfo = MyTaskInfo() init { setOwnerTask(taskInfo) dontStartActivity() } override fun cancel() { val bigRepositoriesList = service<VcsLogBigRepositoriesList>() roots.forEach { bigRepositoriesList.addRepository(it) } text2 = VcsLogBundle.message("vcs.log.status.bar.indexing.cancel.cancelling") LOG.info("Indexing for ${roots.map { it.presentableUrl }} was cancelled from the status bar.") super.cancel() } } inner class MyTaskInfo : TaskInfo { override fun getTitle(): String = VcsLogBundle.message("vcs.log.status.bar.indexing", vcsName.capitalize()) override fun getCancelText(): String = CommonBundle.getCancelButtonText() override fun getCancelTooltipText(): String = VcsLogBundle.message("vcs.log.status.bar.indexing.cancel.tooltip", vcsName.capitalize()) override fun isCancellable(): Boolean = true } companion object { private val LOG = Logger.getInstance(VcsLogStatusBarProgress::class.java) } }
apache-2.0
011aeca0907daabc4d081834f063680d
35.4
140
0.745281
4.428571
false
false
false
false
google/intellij-community
java/java-impl-refactorings/src/com/intellij/refactoring/extractMethod/newImpl/CallBuilder.kt
5
6837
// 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.psi.* import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.impl.source.resolve.JavaResolveUtil import com.intellij.psi.util.PsiUtil import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.createDeclaration import com.intellij.refactoring.extractMethod.newImpl.structures.DataOutput import com.intellij.refactoring.extractMethod.newImpl.structures.DataOutput.* import com.intellij.refactoring.extractMethod.newImpl.structures.ExtractOptions import com.intellij.refactoring.extractMethod.newImpl.structures.FlowOutput import com.intellij.refactoring.extractMethod.newImpl.structures.FlowOutput.* import com.intellij.refactoring.util.RefactoringChangeUtil class CallBuilder(private val context: PsiElement) { private val factory: PsiElementFactory = PsiElementFactory.getInstance(context.project) private fun expressionOf(expression: String) = factory.createExpressionFromText(expression, context) private fun statementsOf(vararg statements: String) = statements.map { statement -> factory.createStatementFromText(statement, context) } private fun createDeclaration(type: PsiType?, name: String, initializer: String): PsiStatement { return if (type != null) { factory.createVariableDeclarationStatement(name, type, expressionOf(initializer)) } else { factory.createStatementFromText("$name = $initializer;", context) } } private fun variableDeclaration(methodCall: String, dataOutput: DataOutput): List<PsiStatement> { val declaration = when (dataOutput) { is VariableOutput -> createDeclaration(dataOutput.type.takeIf { dataOutput.declareType }, dataOutput.name, methodCall) is ExpressionOutput -> createDeclaration(dataOutput.type, dataOutput.name!!, methodCall) ArtificialBooleanOutput, is EmptyOutput -> null } val declarationStatement = declaration as? PsiDeclarationStatement val declaredVariable = declarationStatement?.declaredElements?.firstOrNull() as? PsiVariable if (dataOutput is VariableOutput && declaredVariable != null) { val needsFinal = dataOutput.variable.hasModifierProperty(PsiModifier.FINAL) PsiUtil.setModifierProperty(declaredVariable, PsiModifier.FINAL, needsFinal) } return listOfNotNull(declaration) } private fun conditionalExit(methodCall: String, flow: ConditionalFlow, dataOutput: DataOutput): List<PsiStatement> { val exit = when (dataOutput) { is VariableOutput -> "if (${dataOutput.name} == null) ${flow.statements.first().text}" is ExpressionOutput -> "if (${dataOutput.name} != null) ${exitStatementOf(flow)} ${dataOutput.name};" ArtificialBooleanOutput -> "if ($methodCall) ${flow.statements.first().text}" is EmptyOutput -> throw IllegalArgumentException() } return statementsOf(exit) } private fun exitStatementOf(flow: FlowOutput): String { return if (flow.statements.firstOrNull() is PsiYieldStatement) "yield" else "return" } private fun unconditionalExit(methodCall: String, flow: UnconditionalFlow, dataOutput: DataOutput): List<PsiStatement> { return when (dataOutput) { is VariableOutput -> statementsOf( flow.statements.first().text ) is ExpressionOutput -> statementsOf( "${exitStatementOf(flow)} $methodCall;" ) ArtificialBooleanOutput -> throw IllegalStateException() is EmptyOutput -> when { flow.isDefaultExit -> statementsOf("$methodCall;") else -> statementsOf( "$methodCall;", flow.statements.first().text ) } } } private fun createFlowStatements(methodCall: String, flowOutput: FlowOutput, dataOutput: DataOutput): List<PsiStatement> { return when (flowOutput) { is ConditionalFlow -> conditionalExit(methodCall, flowOutput, dataOutput) is UnconditionalFlow -> unconditionalExit(methodCall, flowOutput, dataOutput) EmptyFlow -> if (dataOutput !is VariableOutput) statementsOf("$methodCall;") else emptyList() } } fun buildCall(methodCall: String, flowOutput: FlowOutput, dataOutput: DataOutput, exposedDeclarations: List<PsiVariable>): List<PsiStatement> { val variableDeclaration = if (flowOutput !is ConditionalFlow && dataOutput is ExpressionOutput) emptyList() else variableDeclaration(methodCall, dataOutput) return variableDeclaration + createFlowStatements(methodCall, flowOutput, dataOutput) + exposedDeclarations.map { createDeclaration(it) } } fun buildExpressionCall(methodCall: String, dataOutput: DataOutput): List<PsiElement> { require(dataOutput is ExpressionOutput) val expression = if (dataOutput.name != null) "${dataOutput.name} = $methodCall" else methodCall return listOf(factory.createExpressionFromText(expression, context)) } fun createMethodCall(method: PsiMethod, parameters: List<PsiExpression>): PsiMethodCallExpression { val name = if (method.isConstructor) "this" else method.name val callText = name + "(" + parameters.joinToString { it.text } + ")" val factory = PsiElementFactory.getInstance(method.project) val callElement = factory.createExpressionFromText(callText, context) as PsiMethodCallExpression val methodClass = findParentClass(method)!! if (methodClass != findParentClass( context) && callElement.resolveMethod() != null && callElement.resolveMethod() != method && !method.isConstructor) { val ref = if (method.hasModifierProperty(PsiModifier.STATIC)) { factory.createReferenceExpression(methodClass) } else { RefactoringChangeUtil.createThisExpression(PsiManager.getInstance(method.project), methodClass) } callElement.methodExpression.qualifierExpression = ref } return callElement } private fun findParentClass(context: PsiElement): PsiClass? { return JavaResolveUtil.findParentContextOfClass(context, PsiClass::class.java, false) as? PsiClass } fun createCall(method: PsiMethod, dependencies: ExtractOptions): List<PsiElement> { val parameters = dependencies.inputParameters.map { it.references.first() } val methodCall = createMethodCall(method, parameters).text val expressionElement = (dependencies.elements.singleOrNull() as? PsiExpression) val callElements = if (expressionElement != null) { buildExpressionCall(methodCall, dependencies.dataOutput) } else { buildCall(methodCall, dependencies.flowOutput, dependencies.dataOutput, dependencies.exposedLocalVariables) } val styleManager = CodeStyleManager.getInstance(dependencies.project) return callElements.map(styleManager::reformat) } }
apache-2.0
acb31caa66474057cf367a338be55d88
48.912409
160
0.754424
4.79453
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/gui/GuiInitializer.kt
1
4505
package com.cout970.modeler.gui import com.cout970.glutilities.structure.Timer import com.cout970.modeler.controller.Dispatcher import com.cout970.modeler.controller.binders.ButtonBinder import com.cout970.modeler.controller.binders.KeyboardBinder import com.cout970.modeler.core.log.Level import com.cout970.modeler.core.log.log import com.cout970.modeler.core.project.IProgramState import com.cout970.modeler.core.project.IProjectPropertiesHolder import com.cout970.modeler.core.resource.ResourceLoader import com.cout970.modeler.gui.canvas.CanvasContainer import com.cout970.modeler.gui.canvas.CanvasManager import com.cout970.modeler.gui.canvas.GridLines import com.cout970.modeler.gui.canvas.cursor.CursorManager import com.cout970.modeler.gui.event.NotificationHandler import com.cout970.modeler.gui.leguicomp.Panel import com.cout970.modeler.gui.leguicomp.StringInput import com.cout970.modeler.gui.views.EditorView import com.cout970.modeler.input.event.EventController import com.cout970.modeler.input.window.WindowHandler import com.cout970.modeler.render.tool.Animator import com.cout970.modeler.util.PropertyManager import com.cout970.reactive.core.ReconciliationManager import org.liquidengine.legui.component.TextInput /** * Created by cout970 on 2017/04/08. */ class GuiInitializer( val eventController: EventController, val windowHandler: WindowHandler, val resourceLoader: ResourceLoader, val timer: Timer, val programState: IProgramState, val propertyHolder: IProjectPropertiesHolder ) { fun init(): Gui { log(Level.FINE) { "[GuiInitializer] Initializing GUI" } log(Level.FINE) { "[GuiInitializer] Creating gui resources" } val guiResources = GuiResources() log(Level.FINE) { "[GuiInitializer] Creating Editor Panel" } val editorPanel = EditorView() log(Level.FINE) { "[GuiInitializer] Creating Root Frame" } val root = Root(editorPanel) log(Level.FINE) { "[GuiInitializer] Creating CanvasContainer" } val canvasContainer = CanvasContainer(Panel()) log(Level.FINE) { "[GuiInitializer] Creating CanvasManager" } val canvasManager = CanvasManager() log(Level.FINE) { "[GuiInitializer] Creating CursorManager" } val cursorManager = CursorManager() log(Level.FINE) { "[GuiInitializer] Creating Listeners" } val listeners = Listeners() log(Level.FINE) { "[GuiInitializer] Creating GuiState" } val guiState = GuiState(programState) log(Level.FINE) { "[GuiInitializer] Creating Dispatcher" } val dispatcher = Dispatcher() log(Level.FINE) { "[GuiInitializer] Creating ButtonBinder" } val buttonBinder = ButtonBinder(dispatcher) log(Level.FINE) { "[GuiInitializer] Creating KeyboardBinder" } val keyboardBinder = KeyboardBinder(dispatcher) log(Level.FINE) { "[GuiInitializer] Creating NotificationHandler" } val notificationHandler = NotificationHandler() log(Level.FINE) { "[GuiInitializer] Creating GridLines" } val gridLines = GridLines() log(Level.FINE) { "[GuiInitializer] Creating Animator" } val animator = Animator() log(Level.FINE) { "[GuiInitializer] Creating initial canvas" } canvasContainer.newCanvas() log(Level.FINE) { "[GuiInitializer] GUI Initialization done" } ReconciliationManager.registerMergeStrategy(TextInput::class.java, TextInputMergeStrategy) ReconciliationManager.registerMergeStrategy(StringInput::class.java, TextInputMergeStrategy) PropertyManager.setupProperties(listeners) return Gui( root = root, canvasContainer = canvasContainer, listeners = listeners, windowHandler = windowHandler, timer = timer, input = eventController, editorView = editorPanel, resources = guiResources, state = guiState, dispatcher = dispatcher, buttonBinder = buttonBinder, keyboardBinder = keyboardBinder, canvasManager = canvasManager, programState = programState, cursorManager = cursorManager, propertyHolder = propertyHolder, notificationHandler = notificationHandler, gridLines = gridLines, animator = animator ) } }
gpl-3.0
9498d9104b7739c23c1f7261c532bfa2
44.06
100
0.694784
4.573604
false
false
false
false
npryce/robots
common/src/test/kotlin/robots/ui/GameStateTest.kt
1
2603
package robots.ui import robots.Action import robots.Seq import robots.UndoRedoStack import robots.canRedo import robots.canUndo import robots.nop import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue open class GameStateTest { @Test fun starts_in_edit_mode_with_empty_program_and_no_edit_history() { val game = initialGameState() assertEquals(expected = nop, actual = game.source.current) assertTrue(!game.source.canUndo()) assertTrue(!game.source.canRedo()) } private val a = Action("a") private val b = Action("b") @Test fun when_starts_running_trace_has_source_as_next_graph_to_reduce() { val editing = Editing(UndoRedoStack(Seq(a, b))) val running = editing.startRunning() assertEquals(editing.source, running.source) assertEquals(running.source.current, running.trace.current.next) } @Test fun when_starts_running_cannot_undo_or_redo_step() { val editing = Editing(UndoRedoStack(Seq(a, b))) val running = editing.startRunning() assertFalse(running.canRedoStep()) assertFalse(running.canUndoStep()) } @Test fun can_step_to_end_of_program() { val running = Editing(UndoRedoStack(Seq(a, b))).startRunning() assertFalse(running.hasFinished(), "start") assertFalse(running.step().hasFinished(), "one step") assertTrue(running.step().step().hasFinished(), "two steps") } @Test fun can_undo_execution_steps() { val running = Editing(UndoRedoStack(Seq(a, b))).startRunning() assertEquals(actual = running.step().undoStep().trace.current, expected = running.trace.current) assertEquals(actual = running.step().step().undoStep().trace.current, expected = running.step().trace.current) assertEquals(actual = running.step().step().undoStep().undoStep().trace.current, expected = running.trace.current) } @Test fun can_undo_and_redo_execution_steps() { val running = Editing(UndoRedoStack(Seq(a, b))).startRunning() assertEquals( actual = running.step().undoStep().redoStep(), expected = running.step()) assertEquals( actual = running.step().step().undoStep().redoStep(), expected = running.step().step()) assertEquals( actual = running.step().step().undoStep().undoStep().redoStep().redoStep(), expected = running.step().step()) } }
gpl-3.0
55250c8d51f61c67d37ccbe5e5bd0d72
33.25
122
0.639647
4.138315
false
true
false
false
SimpleMobileTools/Simple-Music-Player
app/src/main/kotlin/com/simplemobiletools/musicplayer/helpers/Config.kt
1
5996
package com.simplemobiletools.musicplayer.helpers import android.content.Context import com.simplemobiletools.commons.helpers.BaseConfig import com.simplemobiletools.commons.helpers.SORT_FOLDER_PREFIX import java.util.* class Config(context: Context) : BaseConfig(context) { companion object { fun newInstance(context: Context) = Config(context) } var isShuffleEnabled: Boolean get() = prefs.getBoolean(SHUFFLE, true) set(shuffle) = prefs.edit().putBoolean(SHUFFLE, shuffle).apply() var playbackSetting: PlaybackSetting get() = PlaybackSetting.values()[prefs.getInt(PLAYBACK_SETTING, PlaybackSetting.REPEAT_OFF.ordinal)] set(playbackSetting) = prefs.edit().putInt(PLAYBACK_SETTING, playbackSetting.ordinal).apply() var autoplay: Boolean get() = prefs.getBoolean(AUTOPLAY, true) set(autoplay) = prefs.edit().putBoolean(AUTOPLAY, autoplay).apply() var showFilename: Int get() = prefs.getInt(SHOW_FILENAME, SHOW_FILENAME_IF_UNAVAILABLE) set(showFilename) = prefs.edit().putInt(SHOW_FILENAME, showFilename).apply() var swapPrevNext: Boolean get() = prefs.getBoolean(SWAP_PREV_NEXT, false) set(swapPrevNext) = prefs.edit().putBoolean(SWAP_PREV_NEXT, swapPrevNext).apply() var lastSleepTimerSeconds: Int get() = prefs.getInt(LAST_SLEEP_TIMER_SECONDS, 30 * 60) set(lastSleepTimerSeconds) = prefs.edit().putInt(LAST_SLEEP_TIMER_SECONDS, lastSleepTimerSeconds).apply() var sleepInTS: Long get() = prefs.getLong(SLEEP_IN_TS, 0) set(sleepInTS) = prefs.edit().putLong(SLEEP_IN_TS, sleepInTS).apply() var playlistSorting: Int get() = prefs.getInt(PLAYLIST_SORTING, PLAYER_SORT_BY_TITLE) set(playlistSorting) = prefs.edit().putInt(PLAYLIST_SORTING, playlistSorting).apply() var playlistTracksSorting: Int get() = prefs.getInt(PLAYLIST_TRACKS_SORTING, PLAYER_SORT_BY_TITLE) set(playlistTracksSorting) = prefs.edit().putInt(PLAYLIST_TRACKS_SORTING, playlistTracksSorting).apply() fun saveCustomPlaylistSorting(playlistId: Int, value: Int) { prefs.edit().putInt(SORT_PLAYLIST_PREFIX + playlistId, value).apply() } fun getCustomPlaylistSorting(playlistId: Int) = prefs.getInt(SORT_PLAYLIST_PREFIX + playlistId, sorting) fun removeCustomPlaylistSorting(playlistId: Int) { prefs.edit().remove(SORT_PLAYLIST_PREFIX + playlistId).apply() } fun hasCustomPlaylistSorting(playlistId: Int) = prefs.contains(SORT_PLAYLIST_PREFIX + playlistId) fun getProperPlaylistSorting(playlistId: Int) = if (hasCustomPlaylistSorting(playlistId)) { getCustomPlaylistSorting(playlistId) } else { playlistTracksSorting } fun getProperFolderSorting(path: String) = if (hasCustomSorting(path)) { getFolderSorting(path) } else { playlistTracksSorting } var folderSorting: Int get() = prefs.getInt(FOLDER_SORTING, PLAYER_SORT_BY_TITLE) set(folderSorting) = prefs.edit().putInt(FOLDER_SORTING, folderSorting).apply() var artistSorting: Int get() = prefs.getInt(ARTIST_SORTING, PLAYER_SORT_BY_TITLE) set(artistSorting) = prefs.edit().putInt(ARTIST_SORTING, artistSorting).apply() var albumSorting: Int get() = prefs.getInt(ALBUM_SORTING, PLAYER_SORT_BY_TITLE) set(albumSorting) = prefs.edit().putInt(ALBUM_SORTING, albumSorting).apply() var trackSorting: Int get() = prefs.getInt(TRACK_SORTING, PLAYER_SORT_BY_TITLE) set(trackSorting) = prefs.edit().putInt(TRACK_SORTING, trackSorting).apply() var equalizerPreset: Int get() = prefs.getInt(EQUALIZER_PRESET, 0) set(equalizerPreset) = prefs.edit().putInt(EQUALIZER_PRESET, equalizerPreset).apply() var equalizerBands: String get() = prefs.getString(EQUALIZER_BANDS, "")!! set(equalizerBands) = prefs.edit().putString(EQUALIZER_BANDS, equalizerBands).apply() var playbackSpeed: Float get() = prefs.getFloat(PLAYBACK_SPEED, 1f) set(playbackSpeed) = prefs.edit().putFloat(PLAYBACK_SPEED, playbackSpeed).apply() var playbackSpeedProgress: Int get() = prefs.getInt(PLAYBACK_SPEED_PROGRESS, -1) set(playbackSpeedProgress) = prefs.edit().putInt(PLAYBACK_SPEED_PROGRESS, playbackSpeedProgress).apply() var wereTrackFoldersAdded: Boolean get() = prefs.getBoolean(WERE_TRACK_FOLDERS_ADDED, false) set(wereTrackFoldersAdded) = prefs.edit().putBoolean(WERE_TRACK_FOLDERS_ADDED, wereTrackFoldersAdded).apply() var wasAllTracksPlaylistCreated: Boolean get() = prefs.getBoolean(WAS_ALL_TRACKS_PLAYLIST_CREATED, false) set(wasAllTracksPlaylistCreated) = prefs.edit().putBoolean(WAS_ALL_TRACKS_PLAYLIST_CREATED, wasAllTracksPlaylistCreated).apply() var showTabs: Int get() = prefs.getInt(SHOW_TABS, allTabsMask) set(showTabs) = prefs.edit().putInt(SHOW_TABS, showTabs).apply() var lastExportPath: String get() = prefs.getString(LAST_EXPORT_PATH, "")!! set(lastExportPath) = prefs.edit().putString(LAST_EXPORT_PATH, lastExportPath).apply() var excludedFolders: MutableSet<String> get() = prefs.getStringSet(EXCLUDED_FOLDERS, HashSet())!! set(excludedFolders) = prefs.edit().remove(EXCLUDED_FOLDERS).putStringSet(EXCLUDED_FOLDERS, excludedFolders).apply() fun addExcludedFolder(path: String) { addExcludedFolders(HashSet(Arrays.asList(path))) } fun addExcludedFolders(paths: Set<String>) { val currExcludedFolders = HashSet(excludedFolders) currExcludedFolders.addAll(paths.map { it.removeSuffix("/") }) excludedFolders = currExcludedFolders.filter { it.isNotEmpty() }.toHashSet() } fun removeExcludedFolder(path: String) { val currExcludedFolders = HashSet(excludedFolders) currExcludedFolders.remove(path) excludedFolders = currExcludedFolders } }
gpl-3.0
2429a245561380185451a0c079a5073c
41.828571
136
0.702302
4.087253
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/multiModuleLineMarker/fromExpectedSealedClass/common/common.kt
1
536
expect sealed class <!LINE_MARKER("descr='Is subclassed by Sealed1 [common] Sealed1 in Sealed [jvm] Sealed2 [common] Sealed2 in Sealed [jvm] Click or press ... to navigate'"), LINE_MARKER("descr='Has actuals in JVM'")!>Sealed<!> { object <!LINE_MARKER("descr='Has actuals in JVM'")!>Sealed1<!> : Sealed class <!LINE_MARKER("descr='Has actuals in JVM'")!>Sealed2<!> : Sealed { val <!LINE_MARKER("descr='Has actuals in JVM'")!>x<!>: Int fun <!LINE_MARKER("descr='Has actuals in JVM'")!>foo<!>(): String } }
apache-2.0
7819c89f824c7eb4addf86cb205d552e
58.555556
231
0.63806
3.912409
false
false
false
false
siosio/intellij-community
plugins/git-features-trainer/src/git4idea/ift/lesson/GitProjectHistoryLesson.kt
1
6483
// 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 git4idea.ift.lesson import com.intellij.diff.tools.util.SimpleDiffPanel import com.intellij.ide.dnd.aware.DnDAwareTree import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.vcs.changes.VcsEditorTabFilesManager import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.SearchTextField import com.intellij.util.ui.UIUtil import com.intellij.util.ui.tree.TreeUtil import com.intellij.vcs.log.VcsLogBundle import com.intellij.vcs.log.impl.VcsProjectLog import com.intellij.vcs.log.ui.filter.BranchFilterPopupComponent import com.intellij.vcs.log.ui.filter.UserFilterPopupComponent import com.intellij.vcs.log.ui.frame.MainFrame import com.intellij.vcs.log.ui.frame.VcsLogCommitDetailsListPanel import com.intellij.vcs.log.ui.table.GraphTableModel import com.intellij.vcs.log.ui.table.VcsLogGraphTable import git4idea.ift.GitLessonsBundle import git4idea.ift.GitLessonsUtil.checkoutBranch import git4idea.ift.GitLessonsUtil.highlightLatestCommitsFromBranch import git4idea.ift.GitLessonsUtil.highlightSubsequentCommitsInGitLog import git4idea.ift.GitLessonsUtil.resetGitLogWindow import git4idea.ift.GitLessonsUtil.showWarningIfGitWindowClosed import training.dsl.* import training.ui.LearningUiHighlightingManager import java.awt.Rectangle class GitProjectHistoryLesson : GitLesson("Git.ProjectHistory", GitLessonsBundle.message("git.project.history.lesson.name")) { override val existedFile = "git/sphinx_cat.yml" private val branchName = "feature" private val textToFind = "sphinx" override val testScriptProperties = TaskTestContext.TestScriptProperties(skipTesting = true) override val lessonContent: LessonContext.() -> Unit = { checkoutBranch("feature") task("ActivateVersionControlToolWindow") { text(GitLessonsBundle.message("git.project.history.open.git.window", action(it))) stateCheck { val toolWindowManager = ToolWindowManager.getInstance(project) toolWindowManager.getToolWindow(ToolWindowId.VCS)?.isVisible == true } } resetGitLogWindow() task { highlightLatestCommitsFromBranch(branchName) } task { text(GitLessonsBundle.message("git.project.history.commits.tree.explanation")) proceedLink() } task { // todo: return highlighting of full tree node when IFT-234 will be resolved triggerByPartOfComponent(highlightBorder = false) l@{ tree: DnDAwareTree -> val path = TreeUtil.treePathTraverser(tree).find { it.getPathComponent(it.pathCount - 1).toString() == "HEAD_NODE" } ?: return@l null val rect = tree.getPathBounds(path) ?: return@l null Rectangle(rect.x, rect.y, rect.width, 0) } } task { text(GitLessonsBundle.message("git.project.history.apply.branch.filter")) text(GitLessonsBundle.message("git.project.history.click.head.tooltip"), LearningBalloonConfig(Balloon.Position.above, 250)) triggerByUiComponentAndHighlight(false, false) { ui: BranchFilterPopupComponent -> ui.currentText?.contains("HEAD") == true } showWarningIfGitWindowClosed() } task { triggerByUiComponentAndHighlight { _: UserFilterPopupComponent -> true } } val meFilterText = VcsLogBundle.message("vcs.log.user.filter.me") task { text(GitLessonsBundle.message("git.project.history.apply.user.filter")) text(GitLessonsBundle.message("git.project.history.click.filter.tooltip"), LearningBalloonConfig(Balloon.Position.above, 0)) triggerByListItemAndHighlight { item -> item.toString().contains(meFilterText) } showWarningIfGitWindowClosed() } task { text(GitLessonsBundle.message("git.project.history.select.me", strong(meFilterText))) triggerByUiComponentAndHighlight(false, false) { ui: UserFilterPopupComponent -> ui.currentText?.contains(meFilterText) == true } restoreByUi(delayMillis = defaultRestoreDelay) } task { text(GitLessonsBundle.message("git.project.history.apply.message.filter", code(textToFind), LessonUtil.rawEnter())) triggerByUiComponentAndHighlight { ui: SearchTextField -> (UIUtil.getParentOfType(MainFrame::class.java, ui) != null).also { if (it) IdeFocusManager.getInstance(project).requestFocus(ui, true) } } triggerByUiComponentAndHighlight(false, false) l@{ ui: VcsLogGraphTable -> val model = ui.model as? GraphTableModel ?: return@l false model.rowCount > 0 && model.getCommitMetadata(0).fullMessage.contains(textToFind) } showWarningIfGitWindowClosed() } task { text(GitLessonsBundle.message("git.project.history.select.commit")) highlightSubsequentCommitsInGitLog(0) triggerByUiComponentAndHighlight(false, false) { ui: VcsLogGraphTable -> ui.selectedRow == 0 } restoreState { val vcsLogUi = VcsProjectLog.getInstance(project).mainLogUi ?: return@restoreState false vcsLogUi.filterUi.textFilterComponent.text == "" } showWarningIfGitWindowClosed() } // todo Find out why it's hard to collapse highlighted commit details task { text(GitLessonsBundle.message("git.project.history.commit.details.explanation")) proceedLink() triggerByUiComponentAndHighlight(highlightInside = false, usePulsation = true) { _: VcsLogCommitDetailsListPanel -> true } } task { before { LearningUiHighlightingManager.clearHighlights() } text(GitLessonsBundle.message("git.project.history.click.changed.file")) triggerByFoundPathAndHighlight(highlightInside = true) { _, path -> path.getPathComponent(path.pathCount - 1).toString().contains(".yml") } triggerByUiComponentAndHighlight(false, false) { _: SimpleDiffPanel -> true } showWarningIfGitWindowClosed() } if (VcsEditorTabFilesManager.getInstance().shouldOpenInNewWindow) { task("EditorEscape") { text(GitLessonsBundle.message("git.project.history.close.diff", action(it))) stateCheck { previous.ui?.isShowing != true } } } text(GitLessonsBundle.message("git.project.history.invitation.to.commit.lesson")) } }
apache-2.0
037564533f7196ed89cddb53f9da38e5
39.779874
140
0.732223
4.647312
false
false
false
false
siosio/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/ScriptTemplatesProvider.kt
1
1843
// 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("PackageDirectoryMismatch") package org.jetbrains.kotlin.script import com.intellij.openapi.extensions.ExtensionPointName import java.io.File import kotlin.script.experimental.dependencies.DependenciesResolver @Deprecated("Use ScriptDefinitionContributor EP and loadDefinitionsFromTemplates top level function") interface ScriptTemplatesProvider { // for resolving ambiguities val id: String @Deprecated("Parameter isn't used for resolving priorities anymore. " + "com.intellij.openapi.extensions.LoadingOrder constants can be used to order providers when registered from Intellij plugin.", ReplaceWith("0")) val version: Int get() = 0 val isValid: Boolean val templateClassNames: Iterable<String> val resolver: DependenciesResolver? get() = null val filePattern: String? get() = null val templateClasspath: List<File> // TODO: need to provide a way to specify this in compiler/repl .. etc /* * Allows to specify additional jars needed for DependenciesResolver (and not script template). * Script template dependencies naturally become (part of) dependencies of the script which is not always desired for resolver dependencies. * i.e. gradle resolver may depend on some jars that 'built.gradle.kts' files should not depend on. */ val additionalResolverClasspath: List<File> get() = emptyList() val environment: Map<String, Any?>? companion object { val EP_NAME: ExtensionPointName<ScriptTemplatesProvider> = ExtensionPointName.create<ScriptTemplatesProvider>("org.jetbrains.kotlin.scriptTemplatesProvider") } }
apache-2.0
5c7a2e730b2863bf32f169bb871c7d59
38.212766
158
0.737927
4.981081
false
false
false
false
vaibhavpandeyvpz/rootbox
src/main/kotlin/com/vaibhavpandey/rootbox/ShellReader.kt
1
787
package com.vaibhavpandey.rootbox import java.io.BufferedReader import java.io.IOException import java.io.InputStream import java.io.InputStreamReader internal class ShellReader constructor(val stream: InputStream, name: String) : Thread(name) { var contents: MutableList<String> = ArrayList() override fun run() { var reader: BufferedReader? = null try { reader = BufferedReader(InputStreamReader(stream)) var line: String? while (true) { line = reader.readLine() if (null == line) break contents.add(line) } } catch (e: IOException) { e.printStackTrace() } finally { reader?.close() } } }
mit
0a815a3eeee429e9f3d3e96f1d2e7256
26.137931
94
0.573062
4.656805
false
false
false
false
SimpleMobileTools/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/helpers/FadePageTransformer.kt
2
490
package com.simplemobiletools.gallery.pro.helpers import android.view.View import androidx.viewpager.widget.ViewPager class FadePageTransformer : ViewPager.PageTransformer { override fun transformPage(view: View, position: Float) { view.translationX = view.width * -position view.alpha = if (position <= -1f || position >= 1f) { 0f } else if (position == 0f) { 1f } else { 1f - Math.abs(position) } } }
gpl-3.0
d72e75d8f9d09546479ba7367597304e
26.222222
61
0.614286
4.083333
false
false
false
false
StratusHunter/JustEat-Test-Kotlin
app/src/main/kotlin/com/bulbstudios/justeat/services/JustEatRetrofit.kt
1
1612
package com.bulbstudios.justeat.services import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory /** * Created by Terence Baker on 12/05/2016. */ class JustEatRetrofit { companion object { val JSON_RESTAURANTS = "Restaurants" private val JUST_EAT_URL = "https://public.je-apis.com" private val AUTH_CODE = "VGVjaFRlc3RBUEk6dXNlcjI=" private val httpClient = { var client = OkHttpClient.Builder() client.addInterceptor { chain -> val request = chain.request().newBuilder() .addHeader("Accept-Tenant", "uk") .addHeader("Accept-Language", "en-GB") .addHeader("Accept-Charset", "utf-8") .addHeader("Authorization", "Basic $AUTH_CODE") .addHeader("User-Agent", "Android") .addHeader("Host", "public.je-apis.com") .build() chain.proceed(request) } client.build() }() private val retrofit = { Retrofit.Builder() .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(JUST_EAT_URL) .client(httpClient) .build() }() val resturantService = retrofit.create(JustEatService::class.java) } }
mit
eb3471ef7fc0543ab53ecfc2c73a650d
29.433962
77
0.550248
4.826347
false
false
false
false
dpisarenko/econsim-tr01
src/main/java/cc/altruix/econsimtr01/ch03/AgriculturalSimulationAccountant.kt
1
3359
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 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. * * econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01.ch03 import cc.altruix.econsimtr01.AbstractAccountant2 import cc.altruix.econsimtr01.DefaultAgent import cc.altruix.econsimtr01.IAgent import cc.altruix.econsimtr01.ch0202.SimResRow import cc.altruix.econsimtr01.evenHourAndMinute import org.joda.time.DateTime /** * Created by pisarenko on 17.05.2016. */ open class AgriculturalSimulationAccountant( resultsStorage: MutableMap<DateTime, SimResRow<AgriculturalSimulationRowField>>, scenarioName: String) : AbstractAccountant2<AgriculturalSimulationRowField>(resultsStorage, scenarioName) { override fun timeToMeasure(time: DateTime): Boolean = time.evenHourAndMinute(0, 0) override fun saveRowData(agents: List<IAgent>, target: MutableMap<AgriculturalSimulationRowField, Double>) { target.put(AgriculturalSimulationRowField.SEEDS_IN_SHACK, calculateSeedsInShack(agents)) target.put(AgriculturalSimulationRowField.FIELD_AREA_WITH_SEEDS, calculateFieldAreaWithSeeds(agents)) target.put(AgriculturalSimulationRowField.EMPTY_FIELD_AREA, calculateEmptyFieldArea(agents)) target.put(AgriculturalSimulationRowField.FIELD_AREA_WITH_CROP, calculateFieldAreaWithCrop(agents)) } open internal fun calculateFieldAreaWithCrop(agents: List<IAgent>): Double = (agents.find { it.id() == Field.ID } as DefaultAgent). amount( AgriculturalSimParametersProvider.RESOURCE_AREA_WITH_CROP.id ) open internal fun calculateEmptyFieldArea(agents: List<IAgent>): Double = (agents.find { it.id() == Field.ID } as DefaultAgent). amount( AgriculturalSimParametersProvider.RESOURCE_EMPTY_AREA.id ) open internal fun calculateFieldAreaWithSeeds(agents: List<IAgent>): Double = (agents.find { it.id() == Field.ID } as DefaultAgent). amount( AgriculturalSimParametersProvider. RESOURCE_AREA_WITH_SEEDS.id ) open internal fun calculateSeedsInShack(agents: List<IAgent>): Double = (agents.find { it.id() == Shack.ID } as DefaultAgent). amount(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id) }
gpl-3.0
84f5395f8edff70049a6ed0af1d7f1d7
38.05814
80
0.682346
4.652355
false
false
false
false
jwren/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/NamedArgumentCompletion.kt
1
9697
// 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.completion import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.ArgumentPositionData import org.jetbrains.kotlin.idea.core.ExpectedInfo import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.CallType import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull object NamedArgumentCompletion { fun isOnlyNamedArgumentExpected(nameExpression: KtSimpleNameExpression, resolutionFacade: ResolutionFacade): Boolean { val thisArgument = nameExpression.parent as? KtValueArgument ?: return false if (thisArgument.isNamed()) return false val resolvedCall = thisArgument.getStrictParentOfType<KtCallElement>()?.resolveToCall(resolutionFacade) ?: return false return !thisArgument.canBeUsedWithoutNameInCall(resolvedCall) } fun complete(collector: LookupElementsCollector, expectedInfos: Collection<ExpectedInfo>, callType: CallType<*>) { if (callType != CallType.DEFAULT) return val nameToParameterType = HashMap<Name, MutableSet<KotlinType>>() for (expectedInfo in expectedInfos) { val argumentData = expectedInfo.additionalData as? ArgumentPositionData.Positional ?: continue for (parameter in argumentData.namedArgumentCandidates) { nameToParameterType.getOrPut(parameter.name) { HashSet() }.add(parameter.type) } } for ((name, types) in nameToParameterType) { val typeText = types.singleOrNull()?.let { BasicLookupElementFactory.SHORT_NAMES_RENDERER.renderType(it) } ?: "..." val nameString = name.asString() val lookupElement = LookupElementBuilder.create("$nameString =") .withPresentableText("$nameString =") .withTailText(" $typeText") .withIcon(KotlinIcons.PARAMETER) .withInsertHandler(NamedArgumentInsertHandler(name)) lookupElement.putUserData(SmartCompletionInBasicWeigher.NAMED_ARGUMENT_KEY, Unit) collector.addElement(lookupElement) } } private class NamedArgumentInsertHandler(private val parameterName: Name) : InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, item: LookupElement) { val editor = context.editor val (textAfterCompletionArea, doNeedTrailingSpace) = context.file.findElementAt(context.tailOffset).let { psi -> psi?.siblings()?.firstOrNull { it !is PsiWhiteSpace }?.text to (psi !is PsiWhiteSpace) } var text: String var caretOffset: Int if (textAfterCompletionArea == "=") { // User tries to manually rename existing named argument. We shouldn't add trailing `=` in such case text = parameterName.render() caretOffset = text.length } else { // For complicated cases let's try to normalize the document firstly in order to avoid parsing errors due to incomplete code editor.document.replaceString(context.startOffset, context.tailOffset, "") PsiDocumentManager.getInstance(context.project).commitDocument(editor.document) val nextArgument = context.file.findElementAt(context.startOffset)?.siblings() ?.firstOrNull { it !is PsiWhiteSpace }?.parentsWithSelf?.takeWhile { it !is KtValueArgumentList } ?.firstIsInstanceOrNull<KtValueArgument>() if (nextArgument?.isNamed() == true) { if (doNeedTrailingSpace) { text = "${parameterName.render()} = , " caretOffset = text.length - 2 } else { text = "${parameterName.render()} = ," caretOffset = text.length - 1 } } else { text = "${parameterName.render()} = " caretOffset = text.length } } if (context.file.findElementAt(context.startOffset - 1)?.let { it !is PsiWhiteSpace && it.text != "(" } == true) { text = " $text" caretOffset++ } editor.document.replaceString(context.startOffset, context.tailOffset, text) editor.caretModel.moveToOffset(context.startOffset + caretOffset) } } } /** * Checks whether argument in the [resolvedCall] can be used without its name (as positional argument). */ fun KtValueArgument.canBeUsedWithoutNameInCall(resolvedCall: ResolvedCall<out CallableDescriptor>): Boolean { if (resolvedCall.resultingDescriptor.valueParameters.isEmpty()) return true val argumentsThatCanBeUsedWithoutName = collectAllArgumentsThatCanBeUsedWithoutName(resolvedCall).map { it.argument } if (argumentsThatCanBeUsedWithoutName.isEmpty() || argumentsThatCanBeUsedWithoutName.none { it == this }) return false val argumentsBeforeThis = argumentsThatCanBeUsedWithoutName.takeWhile { it != this } return if (languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition)) { argumentsBeforeThis.none { it.isNamed() && !it.placedOnItsOwnPositionInCall(resolvedCall) } } else { argumentsBeforeThis.none { it.isNamed() } } } data class ArgumentThatCanBeUsedWithoutName( val argument: KtValueArgument, /** * When we didn't manage to map an argument to the appropriate parameter then the parameter is `null`. It's useful for cases when we * want to analyze possibility for the argument to be used without name even when appropriate parameter doesn't yet exist * (it may start existing when user will create the parameter from usage with "Add parameter to function" refactoring) */ val parameter: ValueParameterDescriptor? ) fun collectAllArgumentsThatCanBeUsedWithoutName( resolvedCall: ResolvedCall<out CallableDescriptor>, ): List<ArgumentThatCanBeUsedWithoutName> { val arguments = resolvedCall.call.valueArguments.filterIsInstance<KtValueArgument>() val argumentAndParameters = arguments.map { argument -> val parameter = resolvedCall.getParameterForArgument(argument) argument to parameter }.sortedBy { (_, parameter) -> parameter?.index ?: Int.MAX_VALUE } val firstVarargArgumentIndex = argumentAndParameters.indexOfFirst { (_, parameter) -> parameter?.isVararg ?: false } val lastVarargArgumentIndex = argumentAndParameters.indexOfLast { (_, parameter) -> parameter?.isVararg ?: false } return argumentAndParameters .asSequence() .mapIndexed { argumentIndex, (argument, parameter) -> val parameterIndex = parameter?.index ?: argumentIndex val isAfterVararg = lastVarargArgumentIndex != -1 && argumentIndex > lastVarargArgumentIndex val isVarargArg = argumentIndex in firstVarargArgumentIndex..lastVarargArgumentIndex if (!isVarargArg && argumentIndex != parameterIndex || isAfterVararg || isVarargArg && argumentAndParameters.drop(lastVarargArgumentIndex + 1).any { (argument, _) -> !argument.isNamed() } ) { null } else { ArgumentThatCanBeUsedWithoutName(argument, parameter) } } .takeWhile { it != null } // When any argument can't be used without a name then all subsequent arguments must have a name too! .map { it ?: error("It cannot be null because of the previous takeWhile in the chain") } .toList() } /** * Checks whether argument in the [resolvedCall] is on the same position as it listed in the callable definition. * * It is always true for the positional arguments, but may be untrue for the named arguments. * * ``` * fun foo(a: Int, b: Int, c: Int, d: Int) {} * * foo( * 10, // true * b = 10, // true, possible since Kotlin 1.4 with `MixedNamedArgumentsInTheirOwnPosition` feature * d = 30, // false, 3 vs 4 * c = 40 // false, 4 vs 3 * ) * ``` */ fun ValueArgument.placedOnItsOwnPositionInCall(resolvedCall: ResolvedCall<out CallableDescriptor>): Boolean { return resolvedCall.getParameterForArgument(this)?.index == resolvedCall.call.valueArguments.indexOf(this) }
apache-2.0
5c4f675650bfc1934b85b4f246b698e9
49.769634
158
0.69671
5.325096
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/JavaToKotlinPushDownDelegate.kt
4
5496
// 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.pushDown import com.intellij.psi.* import com.intellij.refactoring.memberPushDown.JavaPushDownDelegate import com.intellij.refactoring.memberPushDown.NewSubClassData import com.intellij.refactoring.memberPushDown.PushDownData import com.intellij.refactoring.util.RefactoringUtil import com.intellij.refactoring.util.classMembers.MemberInfo import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMemberDescriptor import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject import org.jetbrains.kotlin.idea.j2k.j2k import org.jetbrains.kotlin.idea.j2k.j2kText import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass import org.jetbrains.kotlin.idea.refactoring.pullUp.addMemberToTarget import org.jetbrains.kotlin.idea.util.getTypeSubstitution import org.jetbrains.kotlin.idea.util.orEmpty import org.jetbrains.kotlin.idea.util.toSubstitutor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtPsiFactory class JavaToKotlinPushDownDelegate : JavaPushDownDelegate() { override fun checkTargetClassConflicts( targetClass: PsiElement?, pushDownData: PushDownData<MemberInfo, PsiMember>, conflicts: MultiMap<PsiElement, String>, subClassData: NewSubClassData? ) { super.checkTargetClassConflicts(targetClass, pushDownData, conflicts, subClassData) val ktClass = targetClass?.unwrapped as? KtClassOrObject ?: return val targetClassDescriptor = ktClass.unsafeResolveToDescriptor() as ClassDescriptor for (memberInfo in pushDownData.membersToMove) { val member = memberInfo.member ?: continue checkExternalUsages(conflicts, member, targetClassDescriptor, ktClass.getResolutionFacade()) } } override fun pushDownToClass(targetClass: PsiElement, pushDownData: PushDownData<MemberInfo, PsiMember>) { val superClass = pushDownData.sourceClass as? PsiClass ?: return val subClass = targetClass.unwrapped as? KtClassOrObject ?: return val resolutionFacade = subClass.getResolutionFacade() val superClassDescriptor = superClass.getJavaClassDescriptor(resolutionFacade) ?: return val subClassDescriptor = subClass.unsafeResolveToDescriptor() as ClassDescriptor val substitutor = getTypeSubstitution(superClassDescriptor.defaultType, subClassDescriptor.defaultType)?.toSubstitutor().orEmpty() val psiFactory = KtPsiFactory(subClass) var hasAbstractMembers = false members@ for (memberInfo in pushDownData.membersToMove) { val member = memberInfo.member val memberDescriptor = member.getJavaMemberDescriptor(resolutionFacade) ?: continue when (member) { is PsiMethod, is PsiField -> { val ktMember = member.j2k() as? KtCallableDeclaration ?: continue@members ktMember.removeModifier(KtTokens.DEFAULT_VISIBILITY_KEYWORD) val isStatic = member.hasModifierProperty(PsiModifier.STATIC) val targetMemberClass = if (isStatic && subClass is KtClass) subClass.getOrCreateCompanionObject() else subClass val targetMemberClassDescriptor = resolutionFacade.resolveToDescriptor(targetMemberClass) as ClassDescriptor if (member.hasModifierProperty(PsiModifier.ABSTRACT)) { hasAbstractMembers = true } moveCallableMemberToClass( ktMember, memberDescriptor as CallableMemberDescriptor, targetMemberClass, targetMemberClassDescriptor, substitutor, memberInfo.isToAbstract ).apply { if (subClass.isInterfaceClass()) { removeModifier(KtTokens.ABSTRACT_KEYWORD) } } } is PsiClass -> { if (memberInfo.overrides != null) { val typeText = RefactoringUtil.findReferenceToClass(superClass.implementsList, member)?.j2kText() ?: continue@members subClass.addSuperTypeListEntry(psiFactory.createSuperTypeEntry(typeText)) } else { val ktClass = member.j2k() as? KtClassOrObject ?: continue@members addMemberToTarget(ktClass, subClass) } } } } if (hasAbstractMembers && !subClass.isInterfaceClass()) { subClass.addModifier(KtTokens.ABSTRACT_KEYWORD) } } }
apache-2.0
f4ae30c0d4d39419fd9845240e270afd
52.359223
158
0.694505
5.545913
false
false
false
false
jwren/intellij-community
java/idea-ui/src/com/intellij/ide/starters/local/generator/AssetsProcessor.kt
1
3745
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.starters.local.generator import com.intellij.ide.starters.local.* import com.intellij.ide.starters.local.GeneratorContext import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.annotations.ApiStatus import java.io.IOException @ApiStatus.Experimental class AssetsProcessor { private val LOG = logger<AssetsProcessor>() internal fun generateSources(context: GeneratorContext, templateProperties: Map<String, Any>) { val outputDir = VfsUtil.createDirectoryIfMissing(context.outputDirectory.fileSystem, context.outputDirectory.path) ?: throw IllegalStateException("Unable to create directory ${context.outputDirectory.path}") generateSources(outputDir, context.assets, templateProperties + ("context" to context)) } fun generateSources( outputDirectory: String, assets: List<GeneratorAsset>, templateProperties: Map<String, Any> ): List<VirtualFile> { val outputDir = VfsUtil.createDirectoryIfMissing(LocalFileSystem.getInstance(), outputDirectory) ?: throw IllegalStateException("Unable to create directory ${outputDirectory}") return generateSources(outputDir, assets, templateProperties) } private fun generateSources( outputDirectory: VirtualFile, assets: List<GeneratorAsset>, templateProperties: Map<String, Any> ): List<VirtualFile> { return assets.map { asset -> when (asset) { is GeneratorTemplateFile -> generateSources(outputDirectory, asset, templateProperties) is GeneratorResourceFile -> generateSources(outputDirectory, asset) is GeneratorEmptyDirectory -> generateSources(outputDirectory, asset) } } } private fun createFile(outputDirectory: VirtualFile, relativePath: String): VirtualFile { val subPath = if (relativePath.contains("/")) "/" + relativePath.substringBeforeLast("/") else "" val fileDirectory = if (subPath.isEmpty()) { outputDirectory } else { VfsUtil.createDirectoryIfMissing(outputDirectory, subPath) ?: throw IllegalStateException("Unable to create directory ${subPath} in ${outputDirectory.path}") } val fileName = relativePath.substringAfterLast("/") LOG.info("Creating file $fileName in ${fileDirectory.path}") return fileDirectory.findOrCreateChildData(this, fileName) } private fun generateSources(outputDirectory: VirtualFile, asset: GeneratorTemplateFile, templateProps: Map<String, Any>): VirtualFile { val sourceCode = try { asset.template.getText(templateProps) } catch (e: Exception) { throw TemplateProcessingException(e) } val file = createFile(outputDirectory, asset.targetFileName) VfsUtil.saveText(file, sourceCode) return file } private fun generateSources(outputDirectory: VirtualFile, asset: GeneratorResourceFile): VirtualFile { val file = createFile(outputDirectory, asset.targetFileName) asset.resource.openStream().use { file.setBinaryContent(it.readBytes()) } return file } private fun generateSources(outputDirectory: VirtualFile, asset: GeneratorEmptyDirectory): VirtualFile { LOG.info("Creating empty directory ${asset.targetFileName} in ${outputDirectory.path}") return VfsUtil.createDirectoryIfMissing(outputDirectory, asset.targetFileName) } private class TemplateProcessingException(t: Throwable) : IOException("Unable to process template", t) }
apache-2.0
09c2c8def9edf49c2c04594c636867ca
38.851064
158
0.747397
5.020107
false
false
false
false
blazsolar/gradle-play-publisher
src/main/java/solar/blaz/gradle/play/tasks/ListingTask.kt
1
1563
package solar.blaz.gradle.play.tasks import com.google.api.services.androidpublisher.model.Apk import org.gradle.api.logging.Logging import javax.inject.Inject open class ListingTask @Inject constructor(applicationId: String, artifactName: String) : PlayEditTask(applicationId, artifactName) { var listings: Map<String, String>? = null override fun perform() { // TODO get apk // uploadListings() } private fun uploadListings(apk: Apk) { // if (listings == null || listings.size() == 0) { // LOG.info("Not APK listings available") // return // } // // listings.each { String country, String listing -> // // // Update recent changes field in apk listing. // final ApkListing newApkListing = new ApkListing(); // newApkListing.setRecentChanges(listing); // // AndroidPublisher.Edits.Apklistings.Update updateRecentChangesRequest = edits // .apklistings() // .update(packageName, editId, apk.getVersionCode(), country, newApkListing) // updateRecentChangesRequest.execute(); // LOG.info("Recent changes for %s updated.", country); // // } // // LOG.info("Recent changes has been updated."); } companion object { private val LOG = Logging.getLogger(UploadApkTask::class.java) } }
mit
fcafde13fb514d25cdd8b21d039e3162
36.214286
133
0.559181
4.765244
false
false
false
false
smmribeiro/intellij-community
python/ide/impl/src/com/jetbrains/python/newProject/welcome/PyWelcomeSettings.kt
12
1294
// 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.jetbrains.python.newProject.welcome import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.xmlb.XmlSerializerUtil @State(name = "PyWelcomeSettings", storages = [Storage("pyWelcome.xml")], reportStatistic = true) class PyWelcomeSettings : PersistentStateComponent<PyWelcomeSettings.State> { companion object { @JvmStatic val instance: PyWelcomeSettings get() = ApplicationManager.getApplication().getService(PyWelcomeSettings::class.java) } private val state: State = State() var createWelcomeScriptForEmptyProject: Boolean get() = state.CREATE_WELCOME_SCRIPT_FOR_EMPTY_PROJECT set(value) { state.CREATE_WELCOME_SCRIPT_FOR_EMPTY_PROJECT = value } override fun getState(): State = state override fun loadState(state: State) { XmlSerializerUtil.copyBean(state, this.state) } @Suppress("PropertyName") class State { @JvmField var CREATE_WELCOME_SCRIPT_FOR_EMPTY_PROJECT: Boolean = true } }
apache-2.0
161e6fccffc7171be2ca5ca816078cb2
34
140
0.767388
4.371622
false
false
false
false
smmribeiro/intellij-community
plugins/settings-repository/src/autoSync.kt
4
5151
// 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.settingsRepository import com.intellij.configurationStore.ComponentStoreImpl import com.intellij.notification.Notification import com.intellij.notification.Notifications import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.impl.coroutineDispatchingContext import com.intellij.openapi.components.stateStore import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.ShutDownTracker import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier import kotlinx.coroutines.* internal class AutoSyncManager(private val icsManager: IcsManager) { @Volatile private var autoSyncFuture: Job? = null @Volatile var enabled = true fun waitAutoSync(indicator: ProgressIndicator) { val autoFuture = autoSyncFuture if (autoFuture != null) { if (autoFuture.isCompleted) { autoSyncFuture = null } else if (autoSyncFuture != null) { LOG.info("Wait for auto sync future") indicator.text = IcsBundle.message("autosync.progress.text") while (!autoFuture.isCompleted) { if (indicator.isCanceled) { return } Thread.sleep(5) } } } } fun autoSync(onAppExit: Boolean = false, force: Boolean = false) { if (!enabled || !icsManager.isActive || (!force && !icsManager.settings.autoSync)) { return } autoSyncFuture?.let { if (!it.isCompleted) { return } } if (onAppExit) { // called on final confirmed exit - no need to restore enabled state enabled = false catchAndLog { runBlocking { icsManager.runInAutoCommitDisabledMode { val repositoryManager = icsManager.repositoryManager val hasUpstream = repositoryManager.hasUpstream() if (hasUpstream && !repositoryManager.canCommit()) { LOG.warn("Auto sync skipped: repository is not committable") return@runInAutoCommitDisabledMode } // on app exit fetch and push only if there are commits to push // if no upstream - just update cloud schemes if (hasUpstream && !repositoryManager.commit() && repositoryManager.getAheadCommitsCount() == 0 && icsManager.readOnlySourcesManager.repositories.isEmpty()) { return@runInAutoCommitDisabledMode } // use explicit progress task to sync on app exit to make it clear why app is not exited immediately icsManager.syncManager.sync(SyncType.MERGE, onAppExit = true) } } } return } else if (ApplicationManager.getApplication().isDisposed) { // will be handled by applicationExiting listener return } // to ensure that repository will not be in uncompleted state and changes will be pushed ShutDownTracker.getInstance().executeWithStopperThread(Thread.currentThread()) { autoSyncFuture = GlobalScope.launch { catchAndLog { icsManager.runInAutoCommitDisabledMode { doSync() } } } } } private suspend fun doSync() { val app = ApplicationManager.getApplication() val repositoryManager = icsManager.repositoryManager val hasUpstream = repositoryManager.hasUpstream() if (hasUpstream && !repositoryManager.canCommit()) { LOG.warn("Auto sync skipped: repository is not committable") return } // update read-only sources at first (because contain scheme - to ensure that some scheme will exist when it will be set as current by some setting) updateCloudSchemes(icsManager) if (!hasUpstream) { return } val updater = repositoryManager.fetch() // we merge in EDT non-modal to ensure that new settings will be properly applied withContext(AppUIExecutor.onUiThread(ModalityState.NON_MODAL).coroutineDispatchingContext()) { catchAndLog { val updateResult = updater.merge() if (!app.isDisposed && updateResult != null && updateStoragesFromStreamProvider(icsManager, app.stateStore as ComponentStoreImpl, updateResult)) { // force to avoid saveAll & confirmation app.exit(true, true, true) } } } if (!updater.definitelySkipPush) { repositoryManager.push() } } } internal inline fun catchAndLog(asWarning: Boolean = false, runnable: () -> Unit) { try { runnable() } catch (e: ProcessCanceledException) { } catch (e: Throwable) { if (asWarning || e is AuthenticationException || e is NoRemoteRepositoryException) { LOG.warn(e) } else { LOG.error(e) } } }
apache-2.0
5bad7aa07efe2a816cfb8044d6728fbe
33.810811
170
0.686469
4.957652
false
false
false
false
WillowChat/Kale
src/test/kotlin/chat/willow/kale/irc/message/extension/chghost/ChgHostMessageTests.kt
2
1998
package chat.willow.kale.irc.message.extension.chghost import chat.willow.kale.core.message.IrcMessage import chat.willow.kale.irc.prefix.Prefix import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test class ChgHostMessageTests { private lateinit var messageParser: ChgHostMessage.Message.Parser private lateinit var messageSerialiser: ChgHostMessage.Message.Serialiser @Before fun setUp() { messageParser = ChgHostMessage.Message.Parser messageSerialiser = ChgHostMessage.Message.Serialiser } @Test fun test_parse_SanityCheck() { val message = messageParser.parse(IrcMessage(command = "CHGHOST", prefix = "testnick!testuser@testhost", parameters = listOf("newuser", "newhost"))) assertEquals(ChgHostMessage.Message(source = Prefix(nick = "testnick", user = "testuser", host = "testhost"), newUser = "newuser", newHost = "newhost"), message) } @Test fun test_parse_TooFewParameters_ReturnsNull() { val messageOne = messageParser.parse(IrcMessage(command = "CHGHOST", prefix = "testnick!testuser@testhost", parameters = listOf("newuser"))) val messageTwo = messageParser.parse(IrcMessage(command = "CHGHOST", prefix = "testnick!testuser@testhost", parameters = listOf())) assertNull(messageOne) assertNull(messageTwo) } @Test fun test_parse_MissingPrefix_ReturnsNull() { val message = messageParser.parse(IrcMessage(command = "CHGHOST", prefix = null, parameters = listOf("newuser", "newhost"))) assertNull(message) } @Test fun test_serialise_SanityCheck() { val message = messageSerialiser.serialise(ChgHostMessage.Message(source = Prefix(nick = "testnick", user = "testuser", host = "testhost"), newUser = "newuser", newHost = "newhost")) assertEquals(IrcMessage(command = "CHGHOST", prefix = "testnick!testuser@testhost", parameters = listOf("newuser", "newhost")), message) } }
isc
9d8a167428ebe8b2251212223e6748f9
42.456522
189
0.718719
4.036364
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinPropertyCallUsage.kt
3
2614
// 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.changeSignature.usages import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtQualifiedExpression import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver class KotlinPropertyCallUsage(element: KtSimpleNameExpression) : KotlinUsageInfo<KtSimpleNameExpression>(element) { private val resolvedCall = element.resolveToCall(BodyResolveMode.FULL) override fun processUsage(changeInfo: KotlinChangeInfo, element: KtSimpleNameExpression, allUsages: Array<out UsageInfo>): Boolean { updateName(changeInfo, element) updateReceiver(changeInfo, element) return true } private fun updateName(changeInfo: KotlinChangeInfo, element: KtSimpleNameExpression) { if (changeInfo.isNameChanged) { element.mainReference.handleElementRename(changeInfo.newName) } } private fun updateReceiver(changeInfo: KotlinChangeInfo, element: KtSimpleNameExpression) { val newReceiver = changeInfo.receiverParameterInfo val oldReceiver = changeInfo.methodDescriptor.receiver if (newReceiver == oldReceiver) return val elementToReplace = element.getQualifiedExpressionForSelectorOrThis() // Do not add extension receiver to calls with explicit dispatch receiver if (newReceiver != null && elementToReplace is KtQualifiedExpression && resolvedCall?.dispatchReceiver is ExpressionReceiver ) return val replacingElement = newReceiver?.let { val psiFactory = KtPsiFactory(project) val receiver = it.defaultValueForCall?.asMarkedForShortening() ?: psiFactory.createExpression("_") psiFactory.createExpressionByPattern("$0.$1", receiver, element) } ?: element elementToReplace.replaced(replacingElement).flushElementsForShorteningToWaitList() } }
apache-2.0
c84fa15331569fb46ac46797d1c029c6
47.425926
158
0.773527
5.561702
false
false
false
false
dreampany/framework
frame/src/main/kotlin/com/dreampany/framework/app/BaseApp.kt
1
11072
package com.dreampany.framework.app import android.annotation.SuppressLint import android.app.Activity import android.app.Application import android.content.Context import android.os.Bundle import android.os.StrictMode import com.dreampany.framework.BuildConfig import com.dreampany.framework.R import com.dreampany.framework.api.service.JobManager import com.dreampany.framework.api.worker.WorkerManager import com.dreampany.framework.data.model.Color import com.dreampany.framework.misc.AppExecutors import com.dreampany.framework.misc.Constants import com.dreampany.framework.misc.SmartAd import com.dreampany.framework.util.AndroidUtil import com.dreampany.framework.util.ColorUtil import com.dreampany.framework.util.TextUtil import com.facebook.cache.disk.DiskCacheConfig import com.facebook.common.internal.Supplier import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.imagepipeline.core.ImagePipelineConfig import com.google.android.gms.ads.MobileAds import com.google.firebase.FirebaseApp import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.appindexing.Action import com.google.firebase.appindexing.FirebaseAppIndex import com.google.firebase.appindexing.FirebaseUserActions import com.google.firebase.appindexing.Indexable import com.google.firebase.appindexing.builders.Indexables import dagger.android.support.DaggerApplication import io.reactivex.plugins.RxJavaPlugins import org.apache.commons.lang3.exception.ExceptionUtils import timber.log.Timber import java.io.File import java.lang.ref.WeakReference import javax.inject.Inject /** * Created by Hawladar Roman on 5/22/2018. * BJIT Group * [email protected] */ abstract class BaseApp : DaggerApplication(), Application.ActivityLifecycleCallbacks { //protected var context: CondomContext? = null @Inject protected lateinit var ex: AppExecutors protected var refs: WeakReference<Activity>? = null protected var action: Action? = null protected var indexable: Indexable? = null @Inject protected lateinit var ad: SmartAd /* @Inject protected lateinit var service: ServiceManager*/ @Inject protected lateinit var job: JobManager @Inject protected lateinit var worker: WorkerManager @Volatile protected var visible: Boolean = false private lateinit var color: Color open fun isDebug(): Boolean { return BuildConfig.DEBUG } open fun hasStrict(): Boolean { return false } open fun hasLeakCanary(): Boolean { return false } open fun hasSoLoader():Boolean { return false } open fun hasStetho(): Boolean { return false } open fun hasCrashlytics(): Boolean { return false } open fun hasAppIndex(): Boolean { return false } open fun hasUpdate(): Boolean { return false; } open fun hasRate(): Boolean { return false; } open fun hasAd(): Boolean { return false; } open fun hasColor(): Boolean { return false } open fun applyColor(): Boolean { return false } open fun hasTheme(): Boolean { return false } open fun hasRemoteUi(): Boolean { return false } open fun getRemoteUi(): Class<*>? { return null } open fun getAdmobAppId(): Int { return 0 } open fun getScreen(): String { return javaClass.simpleName } open fun onOpen() {} open fun onClose() {} open fun onActivityOpen(activity: Activity) {} open fun onActivityClose(activity: Activity) {} open fun getName(): String? { return null } open fun getDescription(): String? { return null } open fun getUrl(): String? { return null } @SuppressLint("MissingPermission") fun getAnalytics(): FirebaseAnalytics { return FirebaseAnalytics.getInstance(this) } /* abstract fun getPrimaryColor(): Colorful.ThemeColor abstract fun getAccentColor(): Colorful.ThemeColor abstract fun isTranslucent(): Boolean abstract fun isDark(): Boolean*/ override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) //MultiDex.install(this) } @SuppressLint("MissingPermission") override fun onCreate() { if (isDebug() && hasStrict()) { //setStrictMode() } super.onCreate() // CondomProcess.installInCurrentProcess(this) //context = CondomContext.wrap(this, packageName) if (isDebug() && hasLeakCanary()) { if (!initLeakCanary()) { return } } if (hasSoLoader()) { initSoLoader() } if (isDebug() && hasStetho()) { //Stetho.initializeWithDefaults(this); } if (isDebug()) { Timber.plant(Timber.DebugTree()) } if (hasCrashlytics()) { /* val fabric = Fabric.Builder(this) .kits(Crashlytics()) .debuggable(true) .build() Fabric.with(fabric)*/ } configRx() configFresco() configWorker() FirebaseApp.initializeApp(this) if (hasAd() && getAdmobAppId() != 0) { MobileAds.initialize(this, TextUtil.getString(this, getAdmobAppId())) } if (hasAppIndex()) { val name = getName() val description = getDescription() val url = getUrl() if (name != null && description != null && url != null) { action = getAction(description, url); indexable = Indexables.newSimple(name, url); startAppIndex(); } } if (hasColor()) { color = ColorUtil.createColor(R.color.colorPrimary, R.color.colorPrimaryDark, R.color.colorAccent) } registerActivityLifecycleCallbacks(this) //TypefaceProvider.registerDefaultIconSets() onOpen() throwAnalytics(Constants.Event.APPLICATION, getScreen()) } override fun onLowMemory() { super.onLowMemory() } override fun onTerminate() { stopAppIndex() onClose() super.onTerminate() } override fun onActivityPaused(activity: Activity) { visible = false } override fun onActivityResumed(activity: Activity) { visible = true } override fun onActivityStarted(activity: Activity) { } override fun onActivityDestroyed(activity: Activity) { onActivityClose(activity) refs?.clear() if (hasUpdate()) { stopUpdate() } } override fun onActivitySaveInstanceState(activity: Activity?, bundle: Bundle?) { } override fun onActivityStopped(activity: Activity) { } override fun onActivityCreated(activity: Activity, bundle: Bundle?) { onActivityClose(activity) refs = WeakReference(activity) goToRemoteUi() if (hasUpdate()) { startUpdate() } } fun isVisible(): Boolean { return visible } fun getCurrentUi(): Activity? { if (refs != null) { return refs?.get() } else { return null } } open fun getColor(): Color { return color; } open fun throwAnalytics(event: String, screen: String) { throwAnalytics(event, screen, null) } open fun throwAnalytics(event: String, screen: String, error: Throwable?) { if (AndroidUtil.isDebug(applicationContext)) { return } ex.postToNetwork(Runnable{ val packageName = AndroidUtil.getPackageName(applicationContext) val versionCode = AndroidUtil.getVersionCode(applicationContext) val versionName = AndroidUtil.getVersionName(applicationContext) val bundle = Bundle() bundle.putString(Constants.Param.PACKAGE_NAME, packageName) bundle.putInt(Constants.Param.VERSION_CODE, versionCode) bundle.putString(Constants.Param.VERSION_NAME, versionName) bundle.putString(Constants.Param.SCREEN, screen) error?.let { bundle.putString(Constants.Param.ERROR_MESSAGE, ExceptionUtils.getMessage(it)) bundle.putString(Constants.Param.ERROR_DETAILS, ExceptionUtils.getStackTrace(it)) } getAnalytics().logEvent(event, bundle) }) } private fun goToRemoteUi() { val target = getRemoteUi(); val current = getCurrentUi(); if (hasRemoteUi() && target != null && current != null) { AndroidUtil.openActivity(getCurrentUi(), target, true) } } private fun setStrictMode() { StrictMode.setThreadPolicy( StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // or .detectAll() for all detectable problems .penaltyLog().build() ) StrictMode.setVmPolicy( StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().detectActivityLeaks().build() ) } private fun initLeakCanary(): Boolean { //if (LeakCanary.isInAnalyzerProcess(this)) { // This process is dedicated to LeakCanary for heap analysis. // You should not init your app in this process. //return false //} //LeakCanary.install(this) return true } private fun initSoLoader() { // SoLoader.init(this, false) } private fun configRx() { RxJavaPlugins.setErrorHandler { Timber.e(it, "Rx Global Error Handler.") throwAnalytics(Constants.Event.ERROR, getScreen(), it) } } private fun configFresco() { val diskSupplier = Supplier<File> { applicationContext.cacheDir } val diskCacheConfig = DiskCacheConfig.newBuilder(applicationContext).setBaseDirectoryName("image.cache") .setBaseDirectoryPathSupplier(diskSupplier).build() val frescoConfig = ImagePipelineConfig.newBuilder(this).setMainDiskCacheConfig(diskCacheConfig).build() Fresco.initialize(this, frescoConfig) } private fun configWorker() { worker.init() } private fun startAppIndex() { if (isDebug()) { return } FirebaseAppIndex.getInstance().update(indexable) FirebaseUserActions.getInstance().start(action) } private fun stopAppIndex() { if (isDebug()) { return } FirebaseUserActions.getInstance().end(action) } private fun getAction(description: String, uri: String): Action { return Action.Builder(Action.Builder.VIEW_ACTION).setObject(description, uri).build() } private fun startUpdate() { } private fun stopUpdate() { } }
apache-2.0
ba9cae88a67a51fdcc5cf3f5e9676bd9
26.340741
147
0.633851
4.85614
false
false
false
false
sksamuel/ktest
kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/specs/isolation/leaf/FunSpecInstancePerLeafTest.kt
1
680
package com.sksamuel.kotest.specs.isolation.leaf import io.kotest.core.spec.IsolationMode import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe import java.util.concurrent.atomic.AtomicInteger private var buffer = "" class FunSpecInstancePerLeafTest : FunSpec({ afterProject { buffer.shouldBe("abc") } isolationMode = IsolationMode.InstancePerLeaf val counter = AtomicInteger(0) test("a") { buffer += "a" counter.incrementAndGet() shouldBe 1 } test("b") { buffer += "b" counter.incrementAndGet() shouldBe 1 } test("c") { buffer += "c" counter.incrementAndGet() shouldBe 1 } })
mit
26d582aa5e180945ecc6d53f6dfc608c
19
48
0.677941
4.121212
false
true
false
false
mikepenz/MaterialDrawer
materialdrawer/src/main/java/com/mikepenz/materialdrawer/model/utils/DrawerItemExtensions.kt
1
666
package com.mikepenz.materialdrawer.model.utils import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem /** Define tags associated to specific tag items */ private val drawerItemTags = mutableMapOf<Any, Any>() /** Define if this IDrawerItem should / can be shown inside the MiniDrawer */ var <T : IDrawerItem<*>> T.hiddenInMiniDrawer: Boolean get() = drawerItemTags[this] as? Boolean == true set(value) { drawerItemTags[this] = value } @Deprecated("Please consider to replace with the actual property setter") fun <T : IDrawerItem<*>> T.withIsHiddenInMiniDrawer(hidden: Boolean): T { hiddenInMiniDrawer = hidden return this }
apache-2.0
ded3925d88e55d31449ec3da3abfad71
34.052632
77
0.737237
4.21519
false
false
false
false
batagliao/onebible.android
app/src/main/java/com/claraboia/bibleandroid/fragments/CloudTranslationsFragment.kt
1
7321
package com.claraboia.bibleandroid.fragments import android.app.Activity import android.app.DownloadManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.content.LocalBroadcastManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.claraboia.bibleandroid.R import com.claraboia.bibleandroid.adapters.TranslationCloudRecyclerAdapter import com.claraboia.bibleandroid.bibleApplication import com.claraboia.bibleandroid.helpers.getBibleDir import com.claraboia.bibleandroid.models.BibleTranslation import com.claraboia.bibleandroid.services.* import com.claraboia.bibleandroid.views.decorators.GridSpacingItemDecoration import com.google.firebase.database.* import kotlinx.android.synthetic.main.fragment_cloud_translations.* import kotlinx.android.synthetic.main.fragment_cloud_translations.view.* import kotlinx.android.synthetic.main.layout_translation_cloud_item.* import kotlinx.android.synthetic.main.layout_translation_cloud_item.view.* import java.util.* /** * Created by lucasbatagliao on 26/10/16. */ class CloudTranslationsFragment : Fragment() { private val database by lazy { FirebaseDatabase.getInstance().reference } var localTranslationFragment: LocalTranslationsFragment? = null private val translations: MutableList<BibleTranslation> = ArrayList() private val adapter = TranslationCloudRecyclerAdapter(translations, click = { t -> downloadTranslationClick(t) }) private val downloadIntentReceiver = intentReceiver() override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater?.inflate(R.layout.fragment_cloud_translations, container, false) return view } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) translationCloudList.visibility = View.GONE translationCloudList.layoutManager = LinearLayoutManager(activity) translationCloudList.adapter = adapter translationCloudList.setHasFixedSize(true) val metrics = this.resources.displayMetrics val space = (metrics.density * 12).toInt() translationCloudList.addItemDecoration(GridSpacingItemDecoration(1, space, true, 0)) val query = database.child("translations").orderByChild("abbreviation") query.addListenerForSingleValueEvent(listenerForDatabase()) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) } override fun onResume() { super.onResume() registerReceiver() } override fun onPause() { super.onPause() LocalBroadcastManager.getInstance(activity).unregisterReceiver(downloadIntentReceiver) } private fun downloadTranslationClick(translation: BibleTranslation) { if (activity.bibleApplication.localBibles.size == 0) { activity.bibleApplication.preferences.selectedTranslation = translation } val position = adapter.getTranslationPosition(translation.abbreviation) val viewholder = translationCloudList.findViewHolderForAdapterPosition(position) updateItem(viewholder as TranslationCloudRecyclerAdapter.TranslationViewHolder, 0) val svcintent = Intent(activity, DownloadTranslationService::class.java) svcintent.putExtra(EXTRA_TRANSLATION, translation) activity.startService(svcintent) } private fun registerReceiver() { val filter = IntentFilter(DOWNLOAD_TRANSLATION_PROGRESS_ACTION) LocalBroadcastManager.getInstance(activity) .registerReceiver(downloadIntentReceiver, filter) } inner class intentReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { //TODO: update adapter to mark the translation as downloading - show progress bar val translation = intent?.getStringExtra(DOWNLOAD_TRANSLATION_NAME_VALUE) val progress = intent?.getIntExtra(DOWNLOAD_TRANSLATION_PROGRESS_VALUE, 0) if (progress != null && progress > 99) { adapter.removeTranslation(translation) } if (progress != null) { val position = adapter.getTranslationPosition(translation) val viewholder = translationCloudList.findViewHolderForAdapterPosition(position) if(viewholder != null) { updateItem(viewholder as TranslationCloudRecyclerAdapter.TranslationViewHolder, progress) } } Log.d("CLOUDTRANSLATION", "$translation >> $progress") //if there is only one translation > restart the app (first translation downloaded) // if(activity.bibleApplication.localBibles.size == 1){ // activity.bibleApplication.doRestart() // } } } fun updateItem(vh: TranslationCloudRecyclerAdapter.TranslationViewHolder, progress: Int){ //block download buytton if not //show progress bar if not //update progress bar value val view = vh.itemView if(view.item_translationDownload.visibility != View.INVISIBLE){ view.item_translationDownload.visibility = View.INVISIBLE } if(view.item_translationDownloadProgressBar.visibility != View.VISIBLE){ view.item_translationDownloadProgressBar.visibility = View.VISIBLE } if(view.item_translationDownloadProgressText.visibility != View.VISIBLE){ view.item_translationDownloadProgressText.visibility = View.VISIBLE } view.item_translationDownloadProgressBar.progress = progress view.item_translationDownloadProgressText.text = progress.toString() + " %" } inner class listenerForDatabase : ValueEventListener { override fun onCancelled(error: DatabaseError?) { Log.e("CloudTranslationsFragme", error.toString()) } override fun onDataChange(snapshot: DataSnapshot?) { translations.clear() for (translationsnapshot in snapshot!!.children) { val translation = translationsnapshot.getValue(BibleTranslation::class.java) if (!activity.bibleApplication.localBibles.any { b -> b.abbreviation == translation.abbreviation }) { //include only not downloaded translations translations.add(translation) } } adapter.updateData(translations) translationCloudList.visibility = View.VISIBLE progress_bar.visibility = View.GONE } } //this method is here to LocalTranslationFragment be able to add removed translations back to this list fun addTranslation(translation: BibleTranslation) { adapter.addTranslation(translation) } }
apache-2.0
d24a856d8f4bd1de445272da58b5e83a
40.134831
117
0.716432
5.192199
false
false
false
false
samthor/intellij-community
platform/vcs-log/graph/test/com/intellij/vcs/log/graph/impl/print/PrintElementGeneratorTest.kt
25
3345
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.vcs.log.graph.impl.print import com.intellij.util.NotNullFunction import com.intellij.vcs.log.graph.* import com.intellij.vcs.log.graph.api.elements.GraphEdge import com.intellij.vcs.log.graph.api.elements.GraphElement import com.intellij.vcs.log.graph.api.elements.GraphNode import com.intellij.vcs.log.graph.api.printer.PrintElementManager import com.intellij.vcs.log.graph.impl.permanent.GraphLayoutBuilder import com.intellij.vcs.log.graph.impl.print.elements.PrintElementWithGraphElement import com.intellij.vcs.log.graph.parser.LinearGraphParser import com.intellij.vcs.log.graph.utils.LinearGraphUtils import org.junit.Test import java.io.IOException import java.util.Comparator import org.junit.Assert.assertEquals public class PrintElementGeneratorTest : AbstractTestWithTwoTextFile("elementGenerator") { class TestPrintElementManager(private val myGraphElementComparator: Comparator<GraphElement>) : PrintElementManager { override fun isSelected(printElement: PrintElementWithGraphElement): Boolean { return false } override fun getColorId(element: GraphElement): Int { if (element is GraphNode) { return (element as GraphNode).getNodeIndex() } if (element is GraphEdge) { val edge = element as GraphEdge val normalEdge = LinearGraphUtils.asNormalEdge(edge) if (normalEdge != null) return normalEdge!!.first + normalEdge!!.second return LinearGraphUtils.getNotNullNodeIndex(edge) } throw IllegalStateException("Incorrect graph element type: " + element) } override fun getGraphElementComparator(): Comparator<GraphElement> { return myGraphElementComparator } } override fun runTest(`in`: String, out: String) { val graph = LinearGraphParser.parse(`in`) val graphLayout = GraphLayoutBuilder.build(graph, object : Comparator<Int> { override fun compare(o1: Int, o2: Int): Int { return o1.compareTo(o2) } }) val graphElementComparator = GraphElementComparatorByLayoutIndex(object : NotNullFunction<Int, Int> { override fun `fun`(nodeIndex: Int?): Int { return graphLayout.getLayoutIndex(nodeIndex!!) } }) val elementManager = TestPrintElementManager(graphElementComparator) val printElementGenerator = PrintElementGeneratorImpl(graph, elementManager, 7, 2, 10) val actual = printElementGenerator.asString(graph.nodesCount()) assertEquals(out, actual) } Test public fun oneNode() { doTest("oneNode") } Test public fun manyNodes() { doTest("manyNodes") } Test public fun longEdges() { doTest("longEdges") } Test public fun specialElements() { doTest("specialElements") } }
apache-2.0
7615584fff10d5acdf8aab52f2888cd4
32.45
119
0.739013
4.119458
false
true
false
false
seventhroot/elysium
bukkit/rpk-auctions-bukkit/src/main/kotlin/com/rpkit/auctions/bukkit/listener/SignChangeListener.kt
1
2928
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.auctions.bukkit.listener import com.rpkit.auctions.bukkit.RPKAuctionsBukkit import com.rpkit.auctions.bukkit.auction.RPKAuctionProvider import com.rpkit.auctions.bukkit.bid.RPKBid import org.bukkit.ChatColor.GREEN import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.block.SignChangeEvent /** * Sign change listener for auction signs. */ class SignChangeListener(private val plugin: RPKAuctionsBukkit): Listener { @EventHandler fun onSignChange(event: SignChangeEvent) { if (event.getLine(0).equals("[auction]", ignoreCase = true)) { event.setLine(0, "$GREEN[auction]") if (!event.player.hasPermission("rpkit.auctions.sign.auction")) { event.block.breakNaturally() event.player.sendMessage(plugin.messages["no-permission-auction-sign-create"]) return } try { val auctionProvider = plugin.core.serviceManager.getServiceProvider(RPKAuctionProvider::class) val auctionId = event.getLine(1)?.toInt() if (auctionId == null) { event.block.breakNaturally() event.player.sendMessage(plugin.messages["auction-sign-invalid-id-not-a-number"]) return } val auction = auctionProvider.getAuction(auctionId) if (auction == null) { event.block.breakNaturally() event.player.sendMessage(plugin.messages["auction-sign-invalid-auction-does-not-exist"]) return } else { event.setLine(2, auction.item.amount.toString() + " x " + auction.item.type.toString().toLowerCase().replace('_', ' ')) event.setLine(3, ((auction.bids .sortedByDescending(RPKBid::amount) .firstOrNull() ?.amount?:auction.startPrice) + auction.minimumBidIncrement).toString()) } } catch (exception: NumberFormatException) { event.block.breakNaturally() event.player.sendMessage(plugin.messages["auction-sign-invalid-id-not-a-number"]) return } } } }
apache-2.0
ee68a57c78eefdde1706ff64b8f9d995
41.434783
139
0.621585
4.714976
false
false
false
false
Ufkoku/AndroidMVPHelper
mvp/src/main/kotlin/com/ufkoku/mvp/delegate/observable/BaseLifecycleObservable.kt
1
4808
/* * Copyright 2017 Ufkoku (https://github.com/Ufkoku/AndroidMVPHelper) * * 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.ufkoku.mvp.delegate.observable import android.util.Log import com.ufkoku.mvp_base.view.lifecycle.ILifecycleObservable import java.lang.reflect.Method import java.lang.reflect.Modifier import java.util.* abstract class BaseLifecycleObservable : ILifecycleObservable { protected companion object { val TAG = "ActivityObservable" protected val cache: WeakHashMap<Class<out Annotation>, WeakHashMap<Any, Collection<Method>>> = WeakHashMap() } protected val registeredSet: MutableSet<Any?> = Collections.newSetFromMap(WeakHashMap()) //-----------------------------------------------------------------------------------------// protected fun getAcceptableMethods(clazz: Class<*>, annotation: Class<out Annotation>): Collection<Method> { val methods: Collection<Method> val cacheForAnnotation: WeakHashMap<Any, Collection<Method>> if (cache.containsKey(annotation)) { cacheForAnnotation = cache[annotation]!! } else { cacheForAnnotation = WeakHashMap() cache[annotation] = cacheForAnnotation } if (cacheForAnnotation.contains(clazz)) { methods = cacheForAnnotation[clazz]!! } else { methods = clazz.getAllDeclaredAcceptableMethods(annotation).filterUnique() methods.forEach { it.isAccessible = true } cacheForAnnotation[clazz] = methods } Log.d(TAG, "Obtained ${methods.size} methods from $clazz") return methods } protected fun Class<*>.getAllDeclaredAcceptableMethods(annotation: Class<out Annotation>): Collection<Method> { var methods = this.declaredMethods .filter { !Modifier.isStatic(it.modifiers) && it.isAnnotationPresent(annotation) } if (methods !is MutableList) { methods = methods.toMutableList() } if (this.superclass != null) { methods.addAll(this.superclass.getAllDeclaredAcceptableMethods(annotation)) } return methods } protected fun Iterable<Method>.filterUnique(): Collection<Method> { val uniqueMethods = ArrayList<Method>() for (method in this) { if (uniqueMethods.none { areEqualMethods(method, it) }) { uniqueMethods.add(method) } } return uniqueMethods } protected open fun areEqualMethods(method1: Method, method2: Method): Boolean { if (method1.name != (method2.name)) { return false } if (method1.returnType != method2.returnType) { return false } val params1 = method1.parameterTypes val params2 = method2.parameterTypes if (params1.size == params2.size) { return params1.indices.none { params1[it] != params2[it] } } return false } protected open fun printErrorMessage(method: Method, ex: Exception?) { if (ex == null) { Log.e(TAG, "Incorrect contract of method $method") } else { Log.e(TAG, "Incorrect contract of method $method", ex) } } //-----------------------------------------------------------------------------------------// protected open fun invokeMethodsFromMap(subscribers: Map<Any, Collection<Method>>, vararg args: Any?) { for ((key, value) in subscribers) { for (method in value) { invokeMethod(key, method, *args) } } } protected open fun invokeMethod(subscriber: Any, method: Method, vararg args: Any?) { val params = method.parameterTypes val paramsCount = params.size if (args.size < paramsCount) { printErrorMessage(method, null) return } try { if (paramsCount == 0) { method.invoke(subscriber) } else { val requestedArgs: Array<*> = Arrays.copyOf(args, paramsCount) method.invoke(subscriber, *requestedArgs) } } catch (ex: IllegalArgumentException) { printErrorMessage(method, ex) } } }
apache-2.0
cc2eaa15c6aadeff97c620529abf2956
32.165517
117
0.604617
4.750988
false
false
false
false
EndlessCodeGroup/BukkitGradle
src/main/kotlin/server/task/DownloadPaperclip.kt
1
2072
package ru.endlesscode.bukkitgradle.server.task import de.undercouch.gradle.tasks.download.Download import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import org.gradle.api.provider.Property import org.gradle.api.provider.Provider import org.gradle.api.provider.ProviderFactory import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.StopExecutionException import ru.endlesscode.bukkitgradle.TASKS_GROUP_BUKKIT import java.io.File import javax.inject.Inject @Suppress("LeakingThis") public abstract class DownloadPaperclip @Inject constructor(providers: ProviderFactory) : Download() { @get:InputFile public abstract val paperVersionsFile: Property<File> @get:Input public abstract val version: Property<String> @get:OutputFile public val paperclipFile: Provider<File> = providers.provider { outputFiles.single() } init { group = TASKS_GROUP_BUKKIT description = "Download paperclip" src(paperVersionsFile.zip(version, ::extractPaperUrl)) onlyIfModified(true) } private fun extractPaperUrl(versionsFile: File, version: String): String { if (!versionsFile.isFile) { logger.warn("Paper versions file not downloaded, make sure that Gradle isn\'t running in offline mode.") throw StopExecutionException() } val versionsUrls = Json.decodeFromString<PaperVersions>(versionsFile.readText()).versions val paperUrl = versionsUrls[version] if (paperUrl == null) { logger.warn( """ Paper v$version not found. Supported paper versions: ${versionsUrls.keys}. """.trimIndent() ) throw StopExecutionException() } return paperUrl } @Serializable private data class PaperVersions( val latest: String, val versions: Map<String, String> ) }
mit
e29ef11838b51a571721f943cfb567ad
31.375
116
0.699807
4.533917
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/history/StreamFragment.kt
1
5776
package com.battlelancer.seriesguide.history import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.view.MenuProvider import androidx.core.view.isGone import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.battlelancer.seriesguide.R import com.battlelancer.seriesguide.databinding.FragmentStreamBinding import com.battlelancer.seriesguide.history.TraktEpisodeHistoryLoader.HistoryItem import com.battlelancer.seriesguide.traktapi.TraktCredentials import com.battlelancer.seriesguide.ui.AutoGridLayoutManager import com.battlelancer.seriesguide.ui.widgets.SgFastScroller import com.battlelancer.seriesguide.util.Utils import com.battlelancer.seriesguide.util.ViewTools import com.uwetrottmann.androidutils.AndroidUtils /** * Displays a stream of activities that can be refreshed by the user via a swipe gesture (or an * action item). */ abstract class StreamFragment : Fragment() { private var _binding: FragmentStreamBinding? = null private val binding get() = _binding!! /** * Implementers should create their history adapter here. */ protected abstract val listAdapter: BaseHistoryAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentStreamBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding.floatingActionButtonStream.setOnClickListener { Utils.launchWebsite(context, TRAKT_HISTORY_URL) } binding.swipeRefreshLayoutStream.apply { setSwipeableChildren(R.id.scrollViewStream, R.id.recyclerViewStream) setOnRefreshListener { refreshStreamWithNetworkCheck() } setProgressViewOffset( false, resources.getDimensionPixelSize( R.dimen.swipe_refresh_progress_bar_start_margin ), resources.getDimensionPixelSize( R.dimen.swipe_refresh_progress_bar_end_margin ) ) } ViewTools.setSwipeRefreshLayoutColors( requireActivity().theme, binding.swipeRefreshLayoutStream ) val layoutManager = AutoGridLayoutManager( context, R.dimen.showgrid_columnWidth, 1, 1, listAdapter ) binding.recyclerViewStream.also { it.setHasFixedSize(true) it.layoutManager = layoutManager it.adapter = listAdapter } SgFastScroller(requireContext(), binding.recyclerViewStream) // set initial view states showProgressBar(true) initializeStream() requireActivity().addMenuProvider( optionsMenuProvider, viewLifecycleOwner, Lifecycle.State.RESUMED ) } private val optionsMenuProvider = object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.stream_menu, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { return when (menuItem.itemId) { R.id.menu_action_stream_refresh -> { refreshStreamWithNetworkCheck() true } else -> false } } } private fun refreshStreamWithNetworkCheck() { // launch trakt connect flow if disconnected TraktCredentials.ensureCredentials(requireContext()) // intercept loader call if offline to avoid replacing data with error message // once trakt data has proper cache headers this might become irrelevant if (!AndroidUtils.isNetworkConnected(requireContext())) { showProgressBar(false) setEmptyMessage(getString(R.string.offline)) Toast.makeText(requireContext(), R.string.offline, Toast.LENGTH_SHORT).show() return } refreshStream() } override fun onDestroyView() { super.onDestroyView() _binding = null } /** * Submits data and an sets empty message to be shown if the data list is empty. */ fun setListData(data: List<HistoryItem>, emptyMessage: String) { listAdapter.submitList(data) setEmptyMessage(emptyMessage) showProgressBar(false) binding.recyclerViewStream.isGone = data.isEmpty() binding.emptyViewStream.isGone = data.isNotEmpty() } private fun setEmptyMessage(emptyMessage: String) { binding.emptyViewStream.text = emptyMessage } /** * Implementers should initialize the activity stream and supply the results to the grid * adapter. */ protected abstract fun initializeStream() /** * Implementers should refresh the activity stream and replace the data of the grid adapter. * Once finished you should hide the progress bar with [.showProgressBar]. */ protected abstract fun refreshStream() /** * Show or hide the progress bar of the [SwipeRefreshLayout] * wrapping the stream view. */ protected fun showProgressBar(isShowing: Boolean) { binding.swipeRefreshLayoutStream.isRefreshing = isShowing } companion object { private const val TRAKT_HISTORY_URL = "https://trakt.tv/users/me/history/" } }
apache-2.0
78059630f0dca190e85fa54f6a2fe351
32.777778
96
0.673303
5.289377
false
false
false
false
alexmonthy/lttng-scope
lttng-scope/src/main/kotlin/org/lttng/scope/views/events/EventTableControl.kt
2
7558
/* * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.lttng.scope.views.events import com.efficios.jabberwocky.context.ViewGroupContext import com.efficios.jabberwocky.project.TraceProject import com.efficios.jabberwocky.project.TraceProjectIterator import com.efficios.jabberwocky.task.JabberwockyTask import com.efficios.jabberwocky.trace.event.TraceEvent import javafx.beans.InvalidationListener import org.lttng.scope.application.ScopeOptions import org.lttng.scope.common.LatestTaskExecutor import java.util.* import java.util.logging.Logger class EventTableControl(internal val viewContext: ViewGroupContext) { companion object { private val LOGGER = Logger.getLogger(EventTableControl::class.java.name) /** How many events to fetch *in each direction*, limited by the start/end of the project. */ private const val FETCH_SIZE = 25_000 } private val projectChangeListener = object : ViewGroupContext.ProjectChangeListener(this) { override fun flush() { /* Stop the redraw task and wait for it to finish */ val bubble = JabberwockyTask<Unit>(null) {} taskExecutor.schedule(bubble) bubble.get() /* Wait for it be scheduled and to finish its execution. */ } override fun newProjectCb(newProject: TraceProject<*, *>?) { if (newProject == null) { clearView() } else { initializeForProject(newProject) } } } private val timestampFormatChangeListener = InvalidationListener { table.refresh() } val table = EventTable(this) private val taskExecutor = LatestTaskExecutor() private var currentBackwardsEvents: List<TraceEvent>? = null private var currentForwardsEvents: List<TraceEvent>? = null init { viewContext.registerProjectChangeListener(projectChangeListener) viewContext.selectionTimeRangeProperty().addListener { _, _, newRange -> if (viewContext.listenerFreeze) return@addListener viewContext.traceProject?.let { recenterOn(it, newRange.startTime) } } ScopeOptions.timestampFormatProperty().addListener(timestampFormatChangeListener) ScopeOptions.timestampTimeZoneProperty().addListener(timestampFormatChangeListener) } @Suppress("ProtectedInFinal", "Unused") protected fun finalize() { viewContext.deregisterProjectChangeListener(projectChangeListener) ScopeOptions.timestampFormatProperty().removeListener(timestampFormatChangeListener) ScopeOptions.timestampTimeZoneProperty().removeListener(timestampFormatChangeListener) } @Synchronized fun scrollToBeginning() { val project = viewContext.traceProject ?: return initializeForProject(project) } @Synchronized fun pageUp() { val project = viewContext.traceProject ?: return /* * The "currentBackwardsEvents" will become the new "forwardsEvents", * and we will fetch the previous "page" as the new backwardsEvents. */ val currentEvents = currentBackwardsEvents ?: return if (currentEvents.isEmpty()) return val ts = currentEvents.first().timestamp val previousEvents = project.iterator().use { it.seek(ts) fetchPreviousEvents(it, FETCH_SIZE) } val fullEventList = listOf(previousEvents + currentEvents).flatten() currentBackwardsEvents = previousEvents currentForwardsEvents = currentEvents table.displayEvents(fullEventList) table.selectIndex(previousEvents.size) } @Synchronized fun pageDown() { val project = viewContext.traceProject ?: return /* * The "currentForwardsEvents" will become the new "backwardsEvents", * and we will fetch the next "page" as the new forwardsEvents. */ val currentEvents = currentForwardsEvents ?: return if (currentEvents.isEmpty()) return val ts = currentEvents.last().timestamp val nextEvents = project.iterator().use { it.seek(ts) /* Consume the last of "currentEvents", we already have it. */ it.next() /* then read the next page */ it.asSequence().take(FETCH_SIZE).toList() } val fullEventList = listOf(currentEvents + nextEvents).flatten() currentBackwardsEvents = currentEvents currentForwardsEvents = nextEvents table.displayEvents(fullEventList) table.selectIndex(currentEvents.size) } @Synchronized fun scrollToEnd() { val project = viewContext.traceProject ?: return val events = project.iterator().use { it.seek(Long.MAX_VALUE) fetchPreviousEvents(it, FETCH_SIZE) } currentBackwardsEvents = events currentForwardsEvents = null table.displayEvents(events) table.scrollToBottom() } private fun clearView() { table.clearTable() } private fun initializeForProject(project: TraceProject<*, *>) { val firstEvents = project.iterator().use { it.asSequence().take(FETCH_SIZE).toList() } currentBackwardsEvents = null currentForwardsEvents = firstEvents table.displayEvents(firstEvents) table.scrollToTop() } @Synchronized private fun recenterOn(project: TraceProject<*, *>, timestamp: Long) { val task = JabberwockyTask<Unit>("Fetching Event Table Contents") { // TODO Implement TraceProjectIterator.copy(), use it here instead of seeking twice val forwardsEvents = project.iterator().use { it.seek(timestamp) it.asSequence().take(FETCH_SIZE).toList() } val backwardsEvents = project.iterator().use { it.seek(timestamp) fetchPreviousEvents(it, FETCH_SIZE) } val eventIndex = backwardsEvents.size val eventsList = listOf(backwardsEvents + forwardsEvents).flatten() LOGGER.finer { "Backwards events: ${logEventsToString(backwardsEvents)}" } LOGGER.finer { "Forwards events: ${logEventsToString(forwardsEvents)}" } if (it.isCancelled) return@JabberwockyTask currentBackwardsEvents = backwardsEvents currentForwardsEvents = forwardsEvents table.displayEvents(eventsList) table.selectIndex(eventIndex) } taskExecutor.schedule(task) } private fun <E : TraceEvent> fetchPreviousEvents(iterator: TraceProjectIterator<E>, limit: Int): List<E> { if (limit < 0) throw IllegalArgumentException() var left = limit val events: MutableList<E> = LinkedList() while (iterator.hasPrevious() && left > 0) { events.add(iterator.previous()) left-- } return events.asReversed() } private fun logEventsToString(events: List<TraceEvent>): String { return if (events.isEmpty()) { "none" } else { "${events.first().timestamp} to ${events.last().timestamp}, ${events.size} total" } } }
epl-1.0
c6406caac7a350749692ef7d2c40519f
34.824645
110
0.657449
4.851091
false
false
false
false
FWDekker/intellij-randomness
src/main/kotlin/com/fwdekker/randomness/integer/IntegerScheme.kt
1
6233
package com.fwdekker.randomness.integer import com.fwdekker.randomness.Bundle import com.fwdekker.randomness.CapitalizationMode import com.fwdekker.randomness.RandomnessIcons import com.fwdekker.randomness.Scheme import com.fwdekker.randomness.SchemeDecorator import com.fwdekker.randomness.TypeIcon import com.fwdekker.randomness.array.ArrayDecorator import com.fwdekker.randomness.fixedlength.FixedLengthDecorator import com.intellij.util.xmlb.annotations.Transient import java.awt.Color import java.text.DecimalFormat /** * Contains settings for generating random integers. * * @property minValue The minimum value to be generated, inclusive. * @property maxValue The maximum value to be generated, inclusive. * @property base The base the generated value should be displayed in. * @property groupingSeparator The character that should separate groups. * @property customGroupingSeparator The grouping separator defined in the custom option. * @property capitalization The capitalization mode of the generated integer, applicable for bases higher than 10. * @property prefix The string to prepend to the generated value. * @property suffix The string to append to the generated value. * @property fixedLengthDecorator Settings that determine whether the output should be fixed to a specific length. * @property arrayDecorator Settings that determine whether the output should be an array of values. */ data class IntegerScheme( var minValue: Long = DEFAULT_MIN_VALUE, var maxValue: Long = DEFAULT_MAX_VALUE, var base: Int = DEFAULT_BASE, var groupingSeparator: String = DEFAULT_GROUPING_SEPARATOR, var customGroupingSeparator: String = DEFAULT_CUSTOM_GROUPING_SEPARATOR, var capitalization: CapitalizationMode = DEFAULT_CAPITALIZATION, var prefix: String = DEFAULT_PREFIX, var suffix: String = DEFAULT_SUFFIX, var fixedLengthDecorator: FixedLengthDecorator = FixedLengthDecorator(), var arrayDecorator: ArrayDecorator = ArrayDecorator() ) : Scheme() { @get:Transient override val name = Bundle("integer.title") override val typeIcon = BASE_ICON override val decorators: List<SchemeDecorator> get() = listOf(fixedLengthDecorator, arrayDecorator) /** * Returns random formatted integers from [minValue] until [maxValue], inclusive. * * @param count the number of integers to generate * @return random formatted integers from [minValue] until [maxValue], inclusive */ override fun generateUndecoratedStrings(count: Int) = List(count) { prefix + longToString(randomLong(minValue, maxValue)) + suffix } /** * Returns a random long in the range from [from] until [until], inclusive, without causing overflow. * * @param from inclusive lower bound * @param until inclusive upper bound * @return a random long in the range from [from] until [until], inclusive, without causing overflow */ private fun randomLong(from: Long, until: Long) = if (from == Long.MIN_VALUE && until == Long.MAX_VALUE) random.nextLong() else if (until == Long.MAX_VALUE) random.nextLong(from - 1, until) + 1 else random.nextLong(from, until + 1) /** * Returns a nicely formatted representation of [value]. * * @param value the value to format * @return a nicely formatted representation of [value] */ private fun longToString(value: Long): String { if (base != DECIMAL_BASE) return capitalization.transform(value.toString(base), random) val format = DecimalFormat() format.isGroupingUsed = groupingSeparator.isNotEmpty() format.minimumFractionDigits = 0 format.maximumFractionDigits = 0 format.decimalFormatSymbols = format.decimalFormatSymbols .also { it.groupingSeparator = groupingSeparator.getOrElse(0) { Char.MIN_VALUE } } return format.format(value) } override fun doValidate() = when { minValue > maxValue -> Bundle("integer.error.min_value_above_max") base !in MIN_BASE..MAX_BASE -> Bundle("integer.error.base_range", "$MIN_BASE..$MAX_BASE") groupingSeparator.length > 1 -> Bundle("integer.error.grouping_separator_length") else -> fixedLengthDecorator.doValidate() ?: arrayDecorator.doValidate() } override fun deepCopy(retainUuid: Boolean) = copy( fixedLengthDecorator = fixedLengthDecorator.deepCopy(retainUuid), arrayDecorator = arrayDecorator.deepCopy(retainUuid) ).also { if (retainUuid) it.uuid = this.uuid } /** * Holds constants. */ companion object { /** * The base icon for integers. */ val BASE_ICON = TypeIcon(RandomnessIcons.SCHEME, "123", listOf(Color(64, 182, 224, 154))) /** * The minimum value of the [base] field. */ const val MIN_BASE = Character.MIN_RADIX /** * The maximum value of the [base] field. */ const val MAX_BASE = Character.MAX_RADIX /** * The definition of decimal base. */ const val DECIMAL_BASE = 10 /** * The default value of the [minValue] field. */ const val DEFAULT_MIN_VALUE = 0L /** * The default value of the [maxValue] field. */ const val DEFAULT_MAX_VALUE = 1000L /** * The default value of the [base] field. */ const val DEFAULT_BASE = DECIMAL_BASE /** * The default value of the [groupingSeparator] field. */ const val DEFAULT_GROUPING_SEPARATOR = "" /** * The default value of the [customGroupingSeparator] field. */ const val DEFAULT_CUSTOM_GROUPING_SEPARATOR = "/" /** * The default value of the [capitalization] field. */ val DEFAULT_CAPITALIZATION = CapitalizationMode.LOWER /** * The default value of the [prefix] field. */ const val DEFAULT_PREFIX = "" /** * The default value of the [suffix] field. */ const val DEFAULT_SUFFIX = "" } }
mit
c3ef61d240df57aca5a1a296cae0b8f9
35.450292
114
0.663565
4.623887
false
false
false
false
FWDekker/intellij-randomness
src/main/kotlin/com/fwdekker/randomness/ui/PreviewPanel.kt
1
3768
package com.fwdekker.randomness.ui import com.fwdekker.randomness.Bundle import com.fwdekker.randomness.DataGenerationException import com.fwdekker.randomness.Scheme import com.fwdekker.randomness.Timely.generateTimely import com.intellij.icons.AllIcons import com.intellij.openapi.Disposable import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.undo.UndoUtil import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.ui.InplaceButton import com.intellij.ui.SeparatorFactory import com.intellij.ui.TitledSeparator import javax.swing.JComponent import javax.swing.JPanel import kotlin.random.Random /** * A panel that shows a preview of the values generated by a scheme. * * Generates a random value that the scheme from [getScheme] could generate as a preview to the user. By reusing the * same seed, the generated value remains (approximately) the same and the user can easily see the effect of their * changes. After registering some components with this panel, the preview will be updated whenever those components are * updated. * * Note that [dispose] should be invoked when this panel is no longer used. * * @property getScheme Returns a scheme that generates previews. Its random source will be changed. */ @Suppress("LateinitUsage") // Initialized by scene builder class PreviewPanel(private val getScheme: () -> Scheme) : Disposable { /** * The root panel containing the preview elements. */ lateinit var rootComponent: JPanel private set private lateinit var separator: TitledSeparator private lateinit var refreshButton: JComponent private lateinit var previewDocument: Document private lateinit var previewEditor: Editor private lateinit var previewComponent: JComponent /** * The current seed to generate data with. */ private var seed = Random.nextInt() /** * The text currently displayed as the preview. */ var previewText: String get() = previewDocument.text set(value) = runWriteAction { previewDocument.setText(value) } /** * Initializes custom UI components. * * This method is called by the scene builder at the start of the constructor. */ @Suppress("UnusedPrivateMember") // Used by scene builder private fun createUIComponents() { separator = SeparatorFactory.createSeparator(Bundle("preview.title"), null) refreshButton = InplaceButton(Bundle("shared.action.refresh"), AllIcons.Actions.Refresh) { seed = Random.nextInt() updatePreview() } val factory = EditorFactory.getInstance() previewDocument = factory.createDocument(Bundle("preview.placeholder")) UndoUtil.disableUndoFor(previewDocument) previewEditor = factory.createViewer(previewDocument) previewComponent = previewEditor.component } /** * Disposes of this panel's resources, to be used when this panel is no longer used. */ override fun dispose() { EditorFactory.getInstance().releaseEditor(previewEditor) } /** * Updates the preview with the current settings. */ @Suppress("SwallowedException") // Alternative is to add coupling to SettingsComponent fun updatePreview() { try { previewText = generateTimely { getScheme().also { it.random = Random(seed) }.generateStrings() }.first() } catch (e: DataGenerationException) { previewText = Bundle("preview.invalid", e.message) } catch (e: IllegalArgumentException) { // Ignore exception; invalid settings are handled by form validation } } }
mit
99cf6ed6032dad03f9e039e39a08b947
36.68
120
0.721868
4.849421
false
false
false
false
FWDekker/intellij-randomness
src/test/kotlin/com/fwdekker/randomness/template/TemplateJTreeModelTest.kt
1
37530
package com.fwdekker.randomness.template import com.fwdekker.randomness.DummyScheme import com.fwdekker.randomness.Scheme import com.fwdekker.randomness.ui.SimpleTreeModelListener import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import javax.swing.event.TreeModelEvent import javax.swing.event.TreeModelListener /** * Unit tests for [TemplateJTreeModel]. */ object TemplateJTreeModelTest : Spek({ lateinit var model: TemplateJTreeModel beforeEachTest { model = TemplateJTreeModel( TemplateList( listOf( Template("Strong", listOf(DummyScheme.from("bell"), DummyScheme.from("people"))), Template("Roll", listOf(DummyScheme.from("hot"))), Template("Steady", emptyList()) ) ) ) } describe("rowToNode (default implementation)") { it("returns null for a negative index") { assertThat(model.rowToNode(-2)).isNull() } it("returns null at a too-high index") { assertThat(model.rowToNode(241)).isNull() } it("returns the first template given index 0") { assertThat(model.rowToNode(0)).isEqualTo(model.root.children[0]) } it("returns the first leaf given index 1") { assertThat(model.rowToNode(1)).isEqualTo(model.root.children[0].children[0]) } it("returns the second template given an index considering the number of previous templates") { assertThat(model.rowToNode(5)).isEqualTo(model.root.children[2]) } it("returns a scheme of the second template given an index considering the number of previous schemes") { assertThat(model.rowToNode(4)).isEqualTo(model.root.children[1].children[0]) } } describe("nodeToRow (default implementation)") { it("returns -1 for null") { assertThat(model.nodeToRow(null)).isEqualTo(-1) } it("returns -1 for an unknown node") { assertThat(model.nodeToRow(StateNode(DummyScheme()))).isEqualTo(-1) } it("returns 0 for the first template") { assertThat(model.nodeToRow(model.root.children[0])).isEqualTo(0) } it("returns 1 for the first scheme") { assertThat(model.nodeToRow(model.root.children[0].children[0])).isEqualTo(1) } it("returns the index considering the number of previous templates given the second template") { assertThat(model.nodeToRow(model.root.children[2])).isEqualTo(5) } it("returns an index considering the number of previous schemes given a scheme of the second template") { assertThat(model.nodeToRow(model.root.children[1].children[0])).isEqualTo(4) } } describe("reload") { it("informs listeners that the root has been reloaded") { var lastEvent: TreeModelEvent? = null model.addTreeModelListener(SimpleTreeModelListener { lastEvent = it }) val oldList = model.list model.reload() assertThat(model.list).isEqualTo(oldList) assertThat(lastEvent!!.treePath.lastPathComponent).isEqualTo(model.root) assertThat(lastEvent!!.childIndices).isEmpty() assertThat(lastEvent!!.children).isNull() } it("informs listeners that a new root has been loaded") { var lastEvent: TreeModelEvent? = null model.addTreeModelListener(SimpleTreeModelListener { lastEvent = it }) val newList = TemplateList(emptyList()) model.reload(newList) assertThat(model.list).isEqualTo(newList) assertThat(lastEvent!!.treePath.lastPathComponent).isEqualTo(StateNode(newList)) assertThat(lastEvent!!.childIndices).isEmpty() assertThat(lastEvent!!.children).isNull() } } describe("addRow") { it("throws an error") { assertThatThrownBy { model.addRow() } .isInstanceOf(IllegalStateException::class.java) .hasMessage("Cannot add empty row.") } } describe("removeRow") { it("throws an error") { assertThatThrownBy { model.removeRow(641) } .isInstanceOf(IllegalStateException::class.java) .hasMessage("Cannot remove row by index.") } } describe("exchangeRows") { describe("templates") { it("moves a template to the previous template") { model.exchangeRows(5, 3) assertThat(model.list.templates.map { it.name }).containsExactly("Strong", "Steady", "Roll") } it("moves a template to the next template") { model.exchangeRows(0, 3) assertThat(model.list.templates.map { it.name }).containsExactly("Roll", "Strong", "Steady") } it("moves a template to the next-template-but-one") { model.exchangeRows(0, 5) assertThat(model.list.templates.map { it.name }).containsExactly("Roll", "Steady", "Strong") } } describe("schemes") { it("moves a scheme to the previous scheme under the same parent") { model.exchangeRows(1, 2) assertThat(model.list.templates[0].schemes.map { it.name }).containsExactly("people", "bell") } it("moves a scheme to the next scheme under the same parent") { model.exchangeRows(2, 1) assertThat(model.list.templates[0].schemes.map { it.name }).containsExactly("people", "bell") } it("moves a scheme to its parent, making it the last child of the parent's previous sibling") { model.exchangeRows(4, 3) assertThat(model.list.templates[0].schemes.map { it.name }) .containsExactly("bell", "people", "hot") assertThat(model.list.templates[1].schemes).isEmpty() } it("moves a scheme to its parent's next sibling, making it that sibling's first child") { model.exchangeRows(4, 5) assertThat(model.list.templates[1].schemes).isEmpty() assertThat(model.list.templates[2].schemes.map { it.name }).containsExactly("hot") } it("moves a scheme to a scheme in another template") { model.exchangeRows(1, 4) assertThat(model.list.templates[0].schemes.map { it.name }).containsExactly("people") assertThat(model.list.templates[1].schemes.map { it.name }).containsExactly("bell", "hot") } } } describe("canExchangeRows") { it("returns false if the old node could not be found") { assertThat(model.canExchangeRows(-2, 2)).isFalse() } it("returns false if the new node could not be found") { assertThat(model.canExchangeRows(1, -4)).isFalse() } it("returns false if the old node is a template but the new node is a non-template scheme") { assertThat(model.canExchangeRows(0, 2)).isFalse() } it("returns false if the old node is a non-template scheme and the new node is the first template") { assertThat(model.canExchangeRows(1, 0)).isFalse() } it("returns true if the nodes at both indices are templates") { assertThat(model.canExchangeRows(0, 5)).isTrue() } it("returns true if the nodes at both indices are schemes") { assertThat(model.canExchangeRows(1, 4)).isTrue() } it("returns true if the old node is a scheme and the new node is a non-first template") { assertThat(model.canExchangeRows(4, 3)).isTrue() } } describe("isLeaf") { it("throws an error if the given node is not a StateNode") { assertThatThrownBy { model.isLeaf("enter") } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("'node' must be a StateNode, but was a 'java.lang.String'.") } it("returns true if the node cannot have children") { assertThat(model.isLeaf(StateNode(DummyScheme()))).isTrue() } it("returns true if the node can have children but has no children") { assertThat(model.isLeaf(StateNode(Template()))).isTrue() } it("returns false if the node can have children and has children") { assertThat(model.isLeaf(StateNode(Template(schemes = listOf(DummyScheme()))))).isFalse() } } describe("getChild") { it("throws an error if the given node is not a StateNode") { assertThatThrownBy { model.getChild("over", 0) } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("'parent' must be a StateNode, but was a 'java.lang.String'.") } it("throws an error if the given node cannot have children") { assertThatThrownBy { model.getChild(StateNode(DummyScheme()), 0) } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("Cannot get child of parent that cannot have children.") } it("throws an error if there is no child at the given index") { val template = Template(schemes = listOf(DummyScheme())) assertThatThrownBy { model.getChild(StateNode(template), 2) } .isInstanceOf(IndexOutOfBoundsException::class.java) } it("returns the child at the given index") { val template = Template(schemes = listOf(DummyScheme.from("appear"), DummyScheme.from("tribe"))) assertThat(model.getChild(StateNode(template), 1).state).isEqualTo(template.schemes[1]) } } describe("getChildCount") { it("throws an error if the given node is not a StateNode") { assertThatThrownBy { model.getChildCount("eager") } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("'parent' must be a StateNode, but was a 'java.lang.String'.") } it("returns 0 if the node cannot have children") { assertThat(model.getChildCount(StateNode(DummyScheme()))).isZero() } it("returns 0 if the node has no children") { assertThat(model.getChildCount(StateNode(Template()))).isZero() } it("returns the number of children of the node") { val template = Template(schemes = listOf(DummyScheme(), DummyScheme())) assertThat(model.getChildCount(StateNode(template))).isEqualTo(2) } } describe("getIndexOfChild") { it("returns -1 if the parent is null") { assertThat(model.getIndexOfChild(null, StateNode(DummyScheme()))).isEqualTo(-1) } it("returns -1 if the child is null") { assertThat(model.getIndexOfChild(StateNode(DummyScheme()), null)).isEqualTo(-1) } it("throws an error if the parent is not a StateNode") { assertThatThrownBy { model.getIndexOfChild("mild", StateNode(DummyScheme())) } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("'parent' must be a StateNode, but was a 'java.lang.String'.") } it("throws an error if the child is not a StateNode") { assertThatThrownBy { model.getIndexOfChild(StateNode(DummyScheme()), "soldier") } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("'child' must be a StateNode, but was a 'java.lang.String'.") } it("returns -1 if the child is not contained in the parent") { val child = DummyScheme() val parent = Template(schemes = emptyList()) assertThat(model.getIndexOfChild(StateNode(parent), StateNode(child))).isEqualTo(-1) } it("returns the index of the child in the parent") { val child = DummyScheme() val parent = Template(schemes = listOf(DummyScheme.from("advance"), child, DummyScheme.from("then"))) assertThat(model.getIndexOfChild(StateNode(parent), StateNode(child))).isEqualTo(1) } it("returns the index of the child in the parent considering only the child's UUID") { val child = DummyScheme() val parent = Template(schemes = listOf(DummyScheme.from("blood"), child, DummyScheme.from("private"))) val childCopy = DummyScheme().also { it.uuid = child.uuid } assertThat(model.getIndexOfChild(StateNode(parent), StateNode(childCopy))).isEqualTo(1) } } describe("getParentOf") { it("returns an error if the node is not contained in this model") { assertThatThrownBy { model.getParentOf(StateNode(DummyScheme())) } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("Cannot get parent of node not in this model.") } it("returns null as the parent of the root") { assertThat(model.getParentOf(model.root)).isNull() } it("returns the root as the parent of any template") { val template = Template(name = "Talk") model.reload(TemplateList(listOf(template))) assertThat(model.getParentOf(StateNode(template))).isEqualTo(model.root) } it("returns the appropriate template as the parent of a given scheme") { val scheme = DummyScheme.from("everyone") val template = Template("Snake", listOf(scheme)) model.reload(TemplateList(listOf(Template("Firm", listOf(DummyScheme.from("set"))), template))) assertThat(model.getParentOf(StateNode(scheme))).isEqualTo(StateNode(template)) } } describe("getPathToRoot") { it("returns an error if the node is not contained in this model") { assertThatThrownBy { model.getPathToRoot(StateNode(DummyScheme())) } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("Cannot get path of node not in this model.") } it("returns a path `root` if a path from the root is requested") { assertThat(model.getPathToRoot(model.root).path).containsExactly(model.root) } it("returns a path `root -> template` if a path from a template is requested") { val template = Template(name = "Package") model.reload(TemplateList(listOf(template))) assertThat(model.getPathToRoot(StateNode(template)).path).containsExactly(model.root, StateNode(template)) } it("returns a path `root -> template -> scheme` if a path from a scheme is requested") { val scheme = DummyScheme.from("review") val template = Template("Reserve", listOf(scheme)) model.reload(TemplateList(listOf(template))) assertThat(model.getPathToRoot(StateNode(scheme)).path) .containsExactly(model.root, StateNode(template), StateNode(scheme)) } } describe("insertNode") { it("throws an error when a node is inserted at a negative index") { assertThatThrownBy { model.insertNode(model.root, StateNode(Template()), -2) } .isInstanceOf(IndexOutOfBoundsException::class.java) } it("throws an error if a node is inserted at a too-high index") { assertThatThrownBy { model.insertNode(model.root, StateNode(Template()), 14) } .isInstanceOf(IndexOutOfBoundsException::class.java) } it("inserts a node into the model and the underlying list") { model.reload(TemplateList(listOf(Template(name = "Current"), Template(name = "Here")))) val template = Template("Royal", listOf(DummyScheme.from("aim"))) model.insertNode(model.root, StateNode(template), 1) assertThat(model.root.children).hasSize(3) assertThat(model.root.children[1]).isEqualTo(StateNode(template)) assertThat(model.list.templates).hasSize(3) assertThat(model.list.templates[1]).isEqualTo(template) } it("inserts a node as the last child of a parent") { model.reload(TemplateList(listOf(Template(name = "Loud"), Template(name = "Various")))) val template = Template(name = "Sister") model.insertNode(model.root, StateNode(template)) assertThat(model.root.children[2]).isEqualTo(StateNode(template)) assertThat(model.list.templates[2]).isEqualTo(template) } it("informs listeners of the insertion") { model.reload(TemplateList(listOf(Template(name = "Rather")))) var lastEvent: TreeModelEvent? = null model.addTreeModelListener(SimpleTreeModelListener { lastEvent = it }) val scheme = DummyScheme.from("fortune") model.insertNode(model.root.children[0], StateNode(scheme)) assertThat(lastEvent!!.treePath.lastPathComponent).isEqualTo(model.root.children[0]) assertThat(lastEvent!!.childIndices).containsExactly(0) assertThat(lastEvent!!.children).containsExactly(StateNode(scheme)) } it("informs listeners of a node insertion if the root's not-only child was inserted") { model.reload(TemplateList(listOf(Template(name = "Every")))) var lastEvent: TreeModelEvent? = null model.addTreeModelListener(SimpleTreeModelListener { lastEvent = it }) val template = Template(name = "Deed") model.insertNode(model.root, StateNode(template)) assertThat(lastEvent!!.treePath.lastPathComponent).isEqualTo(model.root) assertThat(lastEvent!!.childIndices).containsExactly(1) assertThat(lastEvent!!.children).containsExactly(StateNode(template)) } it("informs listeners of a structure change if the root's now-only child was inserted") { model.reload(TemplateList(emptyList())) var lastEvent: TreeModelEvent? = null model.addTreeModelListener(SimpleTreeModelListener { lastEvent = it }) val template = Template(name = "Dot") model.insertNode(model.root, StateNode(template)) assertThat(lastEvent!!.treePath.lastPathComponent).isEqualTo(model.root) assertThat(lastEvent!!.childIndices).isEmpty() assertThat(lastEvent!!.children).isNull() } } describe("insertNodeAfter") { it("throws an error if the node to insert after is not in the parent") { assertThatThrownBy { model.insertNodeAfter( model.root, StateNode(Template()), StateNode(DummyScheme()) ) } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("Cannot find node to insert after in parent.") } it("inserts the node after the given node") { model.reload(TemplateList(listOf(Template(name = "Aloud"), Template(name = "Homemade")))) val template = Template(name = "Family") model.insertNodeAfter(model.root, StateNode(template), model.root.children[1]) assertThat(model.list.templates[2]).isEqualTo(template) } } describe("removeNode") { it("throws an error if the given node is not contained in the model") { assertThatThrownBy { model.removeNode(StateNode(DummyScheme.from("best"))) } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("Cannot remove node not contained in this model.") } it("throws an error if the given node is the root of the model") { assertThatThrownBy { model.removeNode(model.root) } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("Cannot remove root from model.") } it("removes a node from the model and the underlying list") { val template = Template(name = "Ride") model.reload(TemplateList(listOf(Template(name = "Animal"), template, Template(name = "Tend")))) model.removeNode(StateNode(template)) assertThat(model.root.children) .hasSize(2) .doesNotContain(StateNode(template)) assertThat(model.list.templates) .hasSize(2) .doesNotContain(template) } it("informs listeners of the removal") { val template = Template(name = "Fortune") model.reload(TemplateList(listOf(Template(name = "Rather"), template))) var lastEvent: TreeModelEvent? = null model.addTreeModelListener(SimpleTreeModelListener { lastEvent = it }) model.removeNode(StateNode(template)) assertThat(lastEvent!!.treePath.lastPathComponent).isEqualTo(model.root) assertThat(lastEvent!!.childIndices).containsExactly(1) assertThat(lastEvent!!.children).containsExactly(StateNode(template)) } } describe("fire methods") { var nodesChangedInvoked = 0 var nodesInsertedInvoked = 0 var nodesRemovedInvoked = 0 var structureChangedInvoked = 0 var totalInvoked = 0 var lastEvent: TreeModelEvent? = null beforeEachTest { nodesChangedInvoked = 0 nodesInsertedInvoked = 0 nodesRemovedInvoked = 0 structureChangedInvoked = 0 totalInvoked = 0 lastEvent = null model.addTreeModelListener(object : TreeModelListener { override fun treeNodesChanged(event: TreeModelEvent) { nodesChangedInvoked++ totalInvoked++ lastEvent = event } override fun treeNodesInserted(event: TreeModelEvent) { nodesInsertedInvoked++ totalInvoked++ lastEvent = event } override fun treeNodesRemoved(event: TreeModelEvent) { nodesRemovedInvoked++ totalInvoked++ lastEvent = event } override fun treeStructureChanged(event: TreeModelEvent) { structureChangedInvoked++ totalInvoked++ lastEvent = event } }) } describe("fireNodeChanged") { it("does nothing if the given node is null") { model.fireNodeChanged(null) assertThat(nodesChangedInvoked).isZero() assertThat(totalInvoked - nodesChangedInvoked).isZero() } it("invokes the listener with an event without children if the current root is provided") { model.fireNodeChanged(model.root) assertThat(nodesChangedInvoked).isOne() assertThat(totalInvoked - nodesChangedInvoked).isZero() assertThat(lastEvent!!.treePath.lastPathComponent).isEqualTo(model.root) } it("indicates the parent and child index when a non-root node is changed") { val template = model.list.templates[0] model.fireNodeChanged(StateNode(template)) assertThat(nodesChangedInvoked).isOne() assertThat(totalInvoked - nodesChangedInvoked).isZero() assertThat(lastEvent!!.treePath.lastPathComponent).isEqualTo(model.root) assertThat(lastEvent!!.childIndices).containsExactly(0) assertThat(lastEvent!!.children).containsExactly(StateNode(template)) } } describe("fireNodeInserted") { it("does nothing if the given node is null") { model.fireNodeInserted(null, StateNode(DummyScheme()), 227) assertThat(totalInvoked).isZero() } it("throws an error if a template list is given") { assertThatThrownBy { model.fireNodeInserted(model.root, StateNode(DummyScheme()), 688) } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("Template list cannot have parent so cannot be inserted.") } it("fires an event with the given parent, node, and index") { val template = model.list.templates[0] val newScheme = DummyScheme.from("show") model.fireNodeInserted(StateNode(newScheme), StateNode(template), 1) assertThat(nodesInsertedInvoked).isOne() assertThat(totalInvoked - nodesInsertedInvoked).isZero() assertThat(lastEvent!!.treePath.lastPathComponent).isEqualTo(StateNode(template)) assertThat(lastEvent!!.childIndices).containsExactly(1) assertThat(lastEvent!!.children).containsExactly(StateNode(newScheme)) } } describe("fireNodeRemoved") { it("does nothing if the given node is null") { model.fireNodeRemoved(null, StateNode(DummyScheme()), 247) assertThat(totalInvoked).isZero() } it("throws an error if a template list is given") { assertThatThrownBy { model.fireNodeRemoved(model.root, StateNode(DummyScheme()), 888) } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("Template list cannot have parent so cannot be removed.") } it("fires an event with the given parent, node, and index") { val template = model.list.templates[0] val oldScheme = template.schemes[0] model.fireNodeRemoved(StateNode(oldScheme), StateNode(template), 0) assertThat(nodesRemovedInvoked).isOne() assertThat(totalInvoked - nodesRemovedInvoked).isZero() assertThat(lastEvent!!.treePath.lastPathComponent).isEqualTo(StateNode(template)) assertThat(lastEvent!!.childIndices).containsExactly(0) assertThat(lastEvent!!.children).containsExactly(StateNode(oldScheme)) } } describe("fireNodeStructureChanged") { it("does nothing if the given node is null") { model.fireNodeStructureChanged(null) assertThat(totalInvoked).isZero() } it("fires an event with the given node") { val template = model.list.templates[0] model.fireNodeStructureChanged(StateNode(template)) assertThat(structureChangedInvoked).isOne() assertThat(totalInvoked - structureChangedInvoked).isZero() assertThat(lastEvent!!.treePath.lastPathComponent).isEqualTo(StateNode(template)) assertThat(lastEvent!!.childIndices).isEmpty() assertThat(lastEvent!!.children).isNull() } } } describe("valueForPathChanged") { it("throws an error") { assertThatThrownBy { model.valueForPathChanged(model.getPathToRoot(model.root), "dirt") } .isInstanceOf(IllegalStateException::class.java) .hasMessage("Cannot change value by path.") } } describe("addTreeModelListener") { it("invokes the added listener when an event occurs") { var invoked = 0 val listener = SimpleTreeModelListener { invoked++ } model.addTreeModelListener(listener) model.reload() assertThat(invoked).isEqualTo(1) } } describe("removeTreeModelListener") { it("no longer invokes the removed listener when an event occurs") { var invoked = 0 val listener = SimpleTreeModelListener { invoked++ } model.addTreeModelListener(listener) model.reload() model.removeTreeModelListener(listener) model.reload() assertThat(invoked).isEqualTo(1) } } }) /** * Unit tests for [StateNode]. */ object StateNodeTest : Spek({ describe("canHaveChildren") { it("returns true if the state is a template list") { assertThat(StateNode(TemplateList(emptyList())).canHaveChildren).isTrue() } it("returns true if the state is a template") { assertThat(StateNode(Template()).canHaveChildren).isTrue() } it("returns false if the state is a non-template scheme") { assertThat(StateNode(DummyScheme()).canHaveChildren).isFalse() } } describe("children") { describe("get") { it("returns the templates of a template list") { val templates = listOf(Template(name = "Hammer"), Template(name = "Shadow")) assertThat(StateNode(TemplateList(templates)).children.map { it.state }) .containsExactlyElementsOf(templates) } it("returns the schemes of a template") { val schemes = listOf(DummyScheme.from("virtue"), DummyScheme.from("shock")) assertThat(StateNode(Template(schemes = schemes)).children.map { it.state }) .containsExactlyElementsOf(schemes) } it("throws an error for a non-template scheme") { assertThatThrownBy { StateNode(DummyScheme()).children } .isInstanceOf(IllegalStateException::class.java) .hasMessage("Unknown parent type 'com.fwdekker.randomness.DummyScheme'.") } } describe("set") { it("modifies the templates of a template list") { val list = TemplateList(listOf(Template(name = "Wave"), Template(name = "Limit"))) StateNode(list).children = listOf(StateNode(Template(name = "Meantime"))) assertThat(list.templates.map { it.name }).containsExactly("Meantime") } it("modifies the schemes of a template") { val template = Template(schemes = listOf(DummyScheme.from("mean"), DummyScheme.from("further"))) StateNode(template).children = listOf(StateNode(DummyScheme.from("scenery"))) assertThat(template.schemes.map { it.name }).containsExactly("scenery") } it("throws an error for a non-template scheme") { assertThatThrownBy { StateNode(DummyScheme()).children = emptyList() } .isInstanceOf(IllegalStateException::class.java) .hasMessage("Unknown parent type 'com.fwdekker.randomness.DummyScheme'.") } } } describe("recursiveChildren") { it("returns the templates and schemes of a template list in depth-first order") { val templates = listOf( Template("Hammer", listOf(DummyScheme.from("absence"), DummyScheme.from("like"))), Template("Shadow", listOf(DummyScheme.from("village"))) ) assertThat(StateNode(TemplateList(templates)).recursiveChildren.map { (it.state as Scheme).name }) .containsExactly("Hammer", "absence", "like", "Shadow", "village") } it("returns the schemes of a template") { val schemes = listOf(DummyScheme.from("ache"), DummyScheme.from("future")) assertThat(StateNode(Template(schemes = schemes)).recursiveChildren.map { it.state }) .containsExactlyElementsOf(schemes) } it("returns an empty list if the node cannot have children") { assertThat(StateNode(DummyScheme()).recursiveChildren).isEmpty() } } describe("contains") { describe("template list") { it("returns true if the given template list is itself") { val node = StateNode(TemplateList(emptyList())) assertThat(node.contains(node)).isTrue() } it("returns false if the given template list is not itself") { val nodeA = StateNode(TemplateList(emptyList())) val nodeB = StateNode(TemplateList(emptyList())) assertThat(nodeA.contains(nodeB)).isFalse() } it("returns true if the given template is contained in the template list") { val template = Template(name = "Gain") val node = StateNode(TemplateList(listOf(template))) assertThat(node.contains(StateNode(template))).isTrue() } it("returns false if the given template is not contained in the template list") { val node = StateNode(TemplateList(listOf(Template(name = "Governor")))) assertThat(node.contains(StateNode(Template(name = "Resist")))).isFalse() } it("returns true if the given scheme is contained in the template list") { val scheme = DummyScheme.from("company") val node = StateNode(TemplateList(listOf(Template(schemes = listOf(scheme))))) assertThat(node.contains(StateNode(scheme))).isTrue() } it("returns false if the given scheme is not contained in the template list") { val node = StateNode(TemplateList(listOf(Template(schemes = listOf(DummyScheme.from("northern")))))) assertThat(node.contains(StateNode(DummyScheme.from("curve")))).isFalse() } } describe("template") { it("returns false for a template list") { val node = StateNode(Template()) assertThat(node.contains(StateNode(TemplateList(emptyList())))).isFalse() } it("returns true if the given template is itself") { val node = StateNode(Template()) assertThat(node.contains(node)).isTrue() } it("returns false if the given template is not itself") { val nodeA = StateNode(Template(name = "Imagine")) val nodeB = StateNode(Template(name = "Ideal")) assertThat(nodeA.contains(nodeB)).isFalse() } it("returns true if the given scheme is contained in the template") { val scheme = DummyScheme.from("borrow") val node = StateNode(Template(schemes = listOf(scheme))) assertThat(node.contains(StateNode(scheme))).isTrue() } it("returns false if the given scheme is not contained in the template") { val node = StateNode(Template(schemes = listOf(DummyScheme.from("also")))) assertThat(node.contains(StateNode(DummyScheme.from("enter")))).isFalse() } } describe("scheme") { it("returns false for a template list") { val node = StateNode(Template()) assertThat(node.contains(StateNode(TemplateList(emptyList())))).isFalse() } it("returns false for a template") { val node = StateNode(Template()) assertThat(node.contains(StateNode(Template()))).isFalse() } it("returns true if the given scheme is itself") { val node = StateNode(DummyScheme.from("empire")) assertThat(node.contains(node)).isTrue() } it("returns false if the given scheme is not itself") { val nodeA = StateNode(DummyScheme.from("soft")) val nodeB = StateNode(DummyScheme.from("penny")) assertThat(nodeA.contains(nodeB)).isFalse() } } } describe("equals") { it("does not equal an object of another class") { assertThat(StateNode(DummyScheme())).isNotEqualTo(299) } it("equals itself") { val node = StateNode(DummyScheme()) assertThat(node).isEqualTo(node) } it("equals an identical object") { val scheme = DummyScheme() assertThat(StateNode(scheme)).isEqualTo(StateNode(scheme)) } it("does not equal a different object") { assertThat(StateNode(DummyScheme())).isNotEqualTo(StateNode(DummyScheme())) } } describe("hashCode") { it("equals the hashcode of itself") { val node = StateNode(DummyScheme()) assertThat(node.hashCode()).isEqualTo(node.hashCode()) } it("equals the hashcode of an identical object") { val scheme = DummyScheme() assertThat(StateNode(scheme).hashCode()).isEqualTo(StateNode(scheme).hashCode()) } it("does not equal the hashcode of a different object") { assertThat(StateNode(DummyScheme()).hashCode()).isNotEqualTo(StateNode(DummyScheme()).hashCode()) } } })
mit
c13c408c4a1cf6d402f3e02f5c6f5626
38.505263
118
0.597229
5.029483
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RustDropRefInspection.kt
1
1723
package org.rust.ide.inspections import com.intellij.codeInspection.ProblemsHolder import org.rust.ide.inspections.fixes.RemoveRefFix import org.rust.lang.core.psi.RustCallExprElement import org.rust.lang.core.psi.RustElementVisitor import org.rust.lang.core.psi.RustFnItemElement import org.rust.lang.core.psi.RustPathExprElement import org.rust.lang.core.types.RustReferenceType import org.rust.lang.core.types.util.resolvedType /** * Checks for calls to std::mem::drop with a reference instead of an owned value. Analogue of Clippy's drop_ref. * Quick fix: Use the owned value as the argument. */ class RustDropRefInspection : RustLocalInspectionTool() { override fun getDisplayName(): String = "Drop reference" override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RustElementVisitor() { override fun visitCallExpr(expr: RustCallExprElement) = inspectExpr(expr, holder) } fun inspectExpr(expr: RustCallExprElement, holder: ProblemsHolder) { val pathExpr = expr.expr as? RustPathExprElement ?: return val resEl = pathExpr.path.reference.resolve() if (resEl !is RustFnItemElement || resEl.crateRelativePath.toString() != "::mem::drop") return val args = expr.argList.exprList if (args.size != 1) return val arg = args[0] if (arg.resolvedType is RustReferenceType) { val fixes = if (arg.text[0] == '&') arrayOf(RemoveRefFix(arg, "Call with owned value")) else emptyArray() holder.registerProblem( expr, "Call to std::mem::drop with a reference argument. Dropping a reference does nothing", *fixes) } } }
mit
d487bdf50b51260b0b639df9ddf2ae7f
40.02381
117
0.699362
4.141827
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/Constants.kt
1
9492
package net.perfectdreams.loritta.morenitta.utils import com.fasterxml.jackson.databind.BeanDescription import com.fasterxml.jackson.databind.DeserializationConfig import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.MapperFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.PropertyNamingStrategy import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier import com.fasterxml.jackson.databind.module.SimpleModule import com.fasterxml.jackson.databind.type.MapType import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator import com.fasterxml.jackson.module.paramnames.ParameterNamesModule import com.jasonclawson.jackson.dataformat.hocon.HoconFactory import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.commands.CommandContext import kotlinx.serialization.hocon.Hocon import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.common.utils.jackson.FixedMapDeserializer import net.perfectdreams.loritta.common.utils.Emotes import org.yaml.snakeyaml.Yaml import java.awt.Color import java.awt.Font import java.io.File import java.io.FileInputStream import java.text.SimpleDateFormat import java.time.ZoneId import java.util.regex.Pattern import javax.imageio.ImageIO /** * Constantes */ object Constants { const val ERROR = "<:error:412585701054611458>" const val USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0" const val ONE_MINUTE_IN_MILLISECONDS = 60_000L const val ONE_HOUR_IN_MILLISECONDS = 3_600_000L const val ONE_DAY_IN_MILLISECONDS = 86_400_000L const val SEVEN_DAYS_IN_MILLISECONDS = ONE_DAY_IN_MILLISECONDS * 7 const val ONE_WEEK_IN_MILLISECONDS = 604_800_000L const val ONE_MONTH_IN_MILLISECONDS = 2_592_000_000L const val TWO_MONTHS_IN_MILLISECONDS = ONE_MONTH_IN_MILLISECONDS * 2 const val SIX_MONTHS_IN_MILLISECONDS = ONE_MONTH_IN_MILLISECONDS * 8 const val DELAY_CUT_OFF = SIX_MONTHS_IN_MILLISECONDS // six months const val CLUSTER_USER_AGENT = "Loritta Cluster %s (%s)" const val CANARY_CLUSTER_USER_AGENT = "Canary Cluster %s (%s)" val DEFAULT_DISCORD_BLUE_AVATAR by lazy { ImageIO.read(LorittaBot::class.java.getResourceAsStream("/avatars/0.png")) } /** * Discord's URL Crawler User Agent */ const val DISCORD_CRAWLER_USER_AGENT = "Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)" const val LEFT_PADDING = "\uD83D\uDD39" val INDEXES = listOf("1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6⃣", "7⃣", "8⃣", "9⃣") // Folder names used for the action commands const val ACTION_BOTH = "both" const val ACTION_FEMALE_AND_FEMALE = "female_x_female" const val ACTION_FEMALE_AND_MALE = "female_x_male" const val ACTION_GENERIC = "generic" const val ACTION_MALE_AND_FEMALE = "male_x_female" const val ACTION_MALE_AND_MALE = "male_x_male" val JSON_MAPPER = ObjectMapper() val MAPPER = ObjectMapper(YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)) val YAML = Yaml() val HOCON = Hocon { useArrayPolymorphism = true } val HOCON_MAPPER = ObjectMapper(HoconFactory()).apply { this.enable(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING) this.registerModule(ParameterNamesModule()) val module = SimpleModule() // Workaround for https://github.com/jclawson/jackson-dataformat-hocon/issues/15 module.setDeserializerModifier(object: BeanDeserializerModifier() { override fun modifyMapDeserializer(config: DeserializationConfig, type: MapType, beanDesc: BeanDescription, deserializer: JsonDeserializer<*>): JsonDeserializer<*> { return FixedMapDeserializer(type) } }) this.registerModule(module) this.propertyNamingStrategy = object: PropertyNamingStrategy.PropertyNamingStrategyBase() { override fun translate(p0: String): String { val newField = StringBuilder() for (ch in p0) { if (ch.isUpperCase()) { newField.append('-') } newField.append(ch.toLowerCase()) } return newField.toString() } } } const val PORTUGUESE_SUPPORT_GUILD_ID = "297732013006389252" const val ENGLISH_SUPPORT_GUILD_ID = "420626099257475072" const val SPARKLYPOWER_GUILD_ID = "320248230917046282" const val LORI_STICKERS_ROLE_ID = "510788363264196638" const val THANK_YOU_DONATORS_CHANNEL_ID = "536171041546960916" const val DEFAULT_LOCALE_ID = "default" const val DONATION_ACTIVE_MILLIS = 2_764_800_000 // 32 dias // ===[ COLORS ]=== val DISCORD_BLURPLE = Color(114, 137, 218) val LORITTA_AQUA = Color(26, 160, 254) val ROBLOX_RED = Color(226, 35, 26) val IMAGE_FALLBACK by lazy { ImageIO.read(File(LorittaBot.ASSETS, "avatar0.png")) } val URL_PATTERN = Pattern.compile("[-a-zA-Z0-9@:%._+~#=]{2,256}\\.[A-z]{2,7}\\b([-a-zA-Z0-9@:%_+.~#?&/=]*)") val HTTP_URL_PATTERN = Pattern.compile("https?:\\/\\/[-a-zA-Z0-9@:%._+~#=]{2,256}\\.[A-z]{2,7}\\b([-a-zA-Z0-9@:%_+.~#?&/=]*)") val EMOJI_PATTERN = Pattern.compile("(?:[\uD83C\uDF00-\uD83D\uDDFF]|[\uD83E\uDD00-\uD83E\uDDFF]|" + "[\uD83D\uDE00-\uD83D\uDE4F]|[\uD83D\uDE80-\uD83D\uDEFF]|" + "[\u2600-\u26FF]\uFE0F?|[\u2700-\u27BF]\uFE0F?|\u24C2\uFE0F?|" + "[\uD83C\uDDE6-\uD83C\uDDFF]{1,2}|" + "[\uD83C\uDD70\uD83C\uDD71\uD83C\uDD7E\uD83C\uDD7F\uD83C\uDD8E\uD83C\uDD91-\uD83C\uDD9A]\uFE0F?|" + "[\u0023\u002A\u0030-\u0039]\uFE0F?\u20E3|[\u2194-\u2199\u21A9-\u21AA]\uFE0F?|[\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55]\uFE0F?|" + "[\u2934\u2935]\uFE0F?|[\u3030\u303D]\uFE0F?|[\u3297\u3299]\uFE0F?|" + "[\uD83C\uDE01\uD83C\uDE02\uD83C\uDE1A\uD83C\uDE2F\uD83C\uDE32-\uD83C\uDE3A\uD83C\uDE50\uD83C\uDE51]\uFE0F?|" + "[\u203C\u2049]\uFE0F?|[\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE]\uFE0F?|" + "[\u00A9\u00AE]\uFE0F?|[\u2122\u2139]\uFE0F?|\uD83C\uDC04\uFE0F?|\uD83C\uDCCF\uFE0F?|" + "[\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA]\uFE0F?)+") val REPEATING_CHARACTERS_REGEX = Regex("(.)\\1+") val WHITE_SPACE_MULTIPLE_REGEX = Regex(" +") val TWITCH_USERNAME_PATTERN = Pattern.compile("^[a-zA-Z0-9][\\w]{3,24}\$") val DISCORD_EMOTE_PATTERN = Pattern.compile("<a?:([A-z0-9_]+):([0-9]+)>") val DISCORD_INVITE_PATTERN = Pattern.compile(".*(discord\\.gg|(?:discordapp.com|discord.com)(?:/invite))/([A-z0-9]+).*", Pattern.CASE_INSENSITIVE) val YOUTUBE_DATE_FORMAT = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss") val ASSETS_FOLDER by lazy { File(LorittaBot.ASSETS) } // TODO: Don't hardcode this val INVALID_IMAGE_URL = "https://loritta.website/assets/img/oopsie_woopsie_invalid_image.png" // Palavras inapropariadas val BAD_NICKNAME_WORDS = listOf( "puta", "vagabunda", "lixo", "desgraça", "burra", "piranha", "protistuta", "bicha", "bixa", "arromabada", "cachorra", "ruim", "boquete", "boqueteira", "putona", "viada", "vadia", "putiane", "fdp", "xereca", "pepeca", "pepeka", "ppk", "escrava sexual", "xota", "xoxota", "xoxotinha" ) // Canais de textos utilizados na Loritta const val RELAY_YOUTUBE_VIDEOS_CHANNEL = "509043859792068609" const val RELAY_TWITCH_STREAMS_CHANNEL = "520354012021784586" /** * Timezone used by Loritta, Brazil's timezone * * In the future this should be configurable by the server admin or by the user */ val LORITTA_TIMEZONE = ZoneId.of("America/Sao_Paulo") /** * Used in conjuction with the elvis operation ("?:") plus a "return;" when the image is null, this allows the user to receive feedback if the image * is valid or, if he doesn't provide any arguments to the command, explain how the command works. * * ``` * context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; } * ``` */ val INVALID_IMAGE_REPLY: suspend ((CommandContext) -> Unit) = { context -> if (context.rawArgs.isEmpty()) { context.explain() } else { context.reply( LorittaReply( message = context.locale["commands.noValidImageFound", Emotes.LORI_CRYING.toString()], prefix = ERROR ) ) } } // ===[ FONTS ]=== val OSWALD_REGULAR: Font by lazy { FileInputStream(File(LorittaBot.ASSETS + "oswald_regular.ttf")).use { Font.createFont(java.awt.Font.TRUETYPE_FONT, it) } } val MINECRAFTIA: Font by lazy { FileInputStream(File(LorittaBot.ASSETS + "minecraftia.ttf")).use { Font.createFont(Font.TRUETYPE_FONT, it) } } val DOTUMCHE: Font by lazy { FileInputStream(File(LorittaBot.ASSETS + "dotumche.ttf")).use { Font.createFont(Font.TRUETYPE_FONT, it) } } val DETERMINATION_MONO: Font by lazy { FileInputStream(File(LorittaBot.ASSETS + "DTM-Mono.otf")).use { Font.createFont(Font.TRUETYPE_FONT, it) } } val VOLTER: Font by lazy { FileInputStream(File(LorittaBot.ASSETS + "Volter__28Goldfish_29.ttf")).use { Font.createFont(Font.TRUETYPE_FONT, it) } } val JACKEY: Font by lazy { FileInputStream(File(LorittaBot.ASSETS + "jackeyfont.ttf")).use { Font.createFont(Font.TRUETYPE_FONT, it) } } val BURBANK_BIG_CONDENSED_BLACK: Font by lazy { FileInputStream(File(LorittaBot.ASSETS + "burbank-big-condensed-black.otf")).use { Font.createFont(Font.TRUETYPE_FONT, it) } } val BURBANK_BIG_CONDENSED_BOLD: Font by lazy { FileInputStream(File(LorittaBot.ASSETS + "burbank-big-condensed-bold.otf")).use { Font.createFont(Font.TRUETYPE_FONT, it) } } }
agpl-3.0
bc547413192b474ffc97f129520cfe3f
35.295019
168
0.706112
2.836228
false
false
false
false
DVT/showcase-android
app/src/main/kotlin/za/co/dvt/android/showcase/ui/about/AboutViewModel.kt
1
1531
package za.co.dvt.android.showcase.ui.about import android.arch.lifecycle.ViewModel import io.reactivex.Observable import za.co.dvt.android.showcase.injection.ShowcaseComponent import za.co.dvt.android.showcase.repository.RemoteConfigurationRepository import za.co.dvt.android.showcase.repository.TrackingRepository import za.co.dvt.android.showcase.utils.SingleLiveEvent import javax.inject.Inject /** * @author rebeccafranks * @since 2017/06/07. */ class AboutViewModel : ViewModel(), ShowcaseComponent.Injectable { @Inject lateinit var trackingRepository: TrackingRepository @Inject lateinit var remoteConfigRepository: RemoteConfigurationRepository val openWebsite: SingleLiveEvent<String> = SingleLiveEvent() val openFacebook: SingleLiveEvent<String> = SingleLiveEvent() val openTwitter: SingleLiveEvent<String> = SingleLiveEvent() lateinit var aboutCompany: Observable<String> override fun inject(component: ShowcaseComponent) { component.inject(this) aboutCompany = remoteConfigRepository.getAboutCompany() } fun openWebsite() { trackingRepository.trackOpenWebsite() openWebsite.value = remoteConfigRepository.getWebsiteUrl() } fun openTwitter() { trackingRepository.trackOpenTwitter() openTwitter.value = remoteConfigRepository.getTwitterUsername() } fun openFacebook() { trackingRepository.trackOpenFacebook() openFacebook.value = remoteConfigRepository.getFacebookPageName() } }
apache-2.0
a1609a29d3ec58a57e27dd6d40f7d1ca
29.64
74
0.761594
4.696319
false
true
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/DateItem.kt
2
1452
package eu.kanade.tachiyomi.ui.recent_updates import android.text.format.DateUtils import android.view.View import android.widget.TextView import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractHeaderItem import eu.davidea.viewholders.FlexibleViewHolder import eu.kanade.tachiyomi.R import java.util.* class DateItem(val date: Date) : AbstractHeaderItem<DateItem.Holder>() { override fun getLayoutRes(): Int { return R.layout.recent_chapters_section_item } override fun createViewHolder(view: View, adapter: FlexibleAdapter<*>): Holder { return Holder(view, adapter) } override fun bindViewHolder(adapter: FlexibleAdapter<*>, holder: Holder, position: Int, payloads: List<Any?>?) { holder.bind(this) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other is DateItem) { return date == other.date } return false } override fun hashCode(): Int { return date.hashCode() } class Holder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter, true) { private val now = Date().time val section_text: TextView = view.findViewById(R.id.section_text) fun bind(item: DateItem) { section_text.text = DateUtils.getRelativeTimeSpanString(item.date.time, now, DateUtils.DAY_IN_MILLIS) } } }
apache-2.0
6cbb36e02d1392ccede3961d5c09bfc9
29.270833
116
0.684573
4.334328
false
false
false
false
christophpickl/kpotpourri
http4k/src/main/kotlin/com/github/christophpickl/kpotpourri/http4k/internal/ResponseCaster.kt
1
3306
package com.github.christophpickl.kpotpourri.http4k.internal import com.fasterxml.jackson.core.type.TypeReference import com.github.christophpickl.kpotpourri.common.string.toBooleanLenient2 import com.github.christophpickl.kpotpourri.http4k.Http4kException import com.github.christophpickl.kpotpourri.http4k.Response4k import kotlin.reflect.KClass @Suppress("UNCHECKED_CAST") internal object ResponseCaster { fun <R : Any> cast(response4k: Response4k, returnOption: ReturnOption<R>): R = when (returnOption) { is ReturnOption.ReturnClass<*> -> response4k.castTo(returnOption.klass) as R is ReturnOption.ReturnType<*> -> if (returnOption.isSimpleType() || response4k.bodyAsString.isEmpty()) { response4k.castTo((returnOption.typeRef.type as Class<R>).kotlin) } else { mapper.readValue<R>(response4k.bodyAsString, returnOption.typeRef) } } private fun <R> ReturnOption.ReturnType<R>.isSimpleType() = when (typeRef.type as? Class<R>) { Any::class.java, Response4k::class.java, String::class.java, java.lang.String::class.java, Float::class.java, java.lang.Float::class.java, Double::class.java, java.lang.Double::class.java, Byte::class.java, java.lang.Byte::class.java, Short::class.java, java.lang.Short::class.java, Int::class.java, java.lang.Integer::class.java, Long::class.java, java.lang.Long::class.java, Boolean::class.java, java.lang.Boolean::class.java -> true else -> false } private fun <R : Any> Response4k.castTo(returnType: KClass<R>): R = when (returnType) { Response4k::class -> this as R String::class -> this.bodyAsString as R Any::class -> this as R Unit::class -> Unit as R // could catch parsing exceptions here ;) Float::class -> this.bodyAsString.toFloat() as R Double::class -> this.bodyAsString.toDouble() as R Byte::class -> this.bodyAsString.toByte() as R // ByteArray::class -> ??? as R Short::class -> this.bodyAsString.toShort() as R Int::class -> this.bodyAsString.toInt() as R Long::class -> this.bodyAsString.toLong() as R Boolean::class -> this.bodyAsString.toBooleanLenient2() as R else -> mapper.readValue(this.bodyAsString, returnType.java).apply { if (this is ArrayList<*> && this.isNotEmpty() && this[0] is LinkedHashMap<*, *>) { throw Http4kException("Seems as you ran into Java's type erasure problem! Use Jackson's TypeReference instead.") } } } } internal sealed class ReturnOption<R> { class ReturnClass<R : Any>(val klass: KClass<R>) : ReturnOption<R>() class ReturnType<R>(val typeRef: TypeReference<R>) : ReturnOption<R>() } internal fun <R : Any> KClass<R>.toOption() = ReturnOption.ReturnClass<R>(this) internal fun <R> TypeReference<R>.toOption() = ReturnOption.ReturnType<R>(this)
apache-2.0
2b989e67dbea5222f16312bada7c36bc
43.08
136
0.601331
4.249357
false
false
false
false