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
androidx/androidx
benchmark/benchmark-darwin-gradle-plugin/src/main/kotlin/androidx/benchmark/darwin/gradle/DarwinBenchmarkPlugin.kt
3
7327
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.benchmark.darwin.gradle import java.io.File import java.util.concurrent.atomic.AtomicBoolean import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.file.Directory import org.gradle.api.provider.Provider import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension import org.jetbrains.kotlin.gradle.plugin.KotlinMultiplatformPluginWrapper import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget /** * The Darwin benchmark plugin that helps run KMP benchmarks on iOS devices, and extracts benchmark * results in `json`. */ class DarwinBenchmarkPlugin : Plugin<Project> { override fun apply(project: Project) { val extension = project.extensions.create("darwinBenchmark", DarwinBenchmarkPluginExtension::class.java) val appliedDarwinPlugin = AtomicBoolean() project.plugins.withType(KotlinMultiplatformPluginWrapper::class.java) { val multiplatformExtension: KotlinMultiplatformExtension = project.extensions.getByType(it.projectExtensionClass.java) multiplatformExtension.targets.all { kotlinTarget -> if (kotlinTarget is KotlinNativeTarget) { if (kotlinTarget.konanTarget.family.isAppleFamily) { // We want to apply the plugin only once. if (appliedDarwinPlugin.compareAndSet(false, true)) { applyDarwinPlugin(extension, project) } } } } } } private fun applyDarwinPlugin( extension: DarwinBenchmarkPluginExtension, project: Project ) { // You can override the xcodeGenDownloadUri by specifying something like: // androidx.benchmark.darwin.xcodeGenDownloadUri=https://github.com/yonaskolb/XcodeGen/releases/download/2.32.0/xcodegen.zip val xcodeGenUri = when (val uri = project.findProperty(XCODEGEN_DOWNLOAD_URI)) { null -> File( project.rootProject.projectDir, // frameworks/support "../../prebuilts/androidx/external/xcodegen" ).absoluteFile.toURI().toString() else -> uri.toString() } val xcodeProjectPath = extension.xcodeProjectName.flatMap { name -> project.layout.buildDirectory.dir("$name.xcodeproj") } val xcResultPath = extension.xcodeProjectName.flatMap { name -> project.layout.buildDirectory.dir("$name.xcresult") } // Configure the XCode Build Service so we don't run too many benchmarks at the same time. project.configureXCodeBuildService() val fetchXCodeGenTask = project.tasks.register( FETCH_XCODEGEN_TASK, FetchXCodeGenTask::class.java ) { it.xcodeGenUri.set(xcodeGenUri) it.downloadPath.set(project.layout.buildDirectory.dir("xcodegen")) } val generateXCodeProjectTask = project.tasks.register( GENERATE_XCODE_PROJECT_TASK, GenerateXCodeProjectTask::class.java ) { it.xcodeGenPath.set(fetchXCodeGenTask.map { task -> task.xcodeGenBinary() }) it.yamlFile.set(extension.xcodeGenConfigFile) it.projectName.set(extension.xcodeProjectName) it.xcProjectPath.set(xcodeProjectPath) } val runDarwinBenchmarks = project.tasks.register( RUN_DARWIN_BENCHMARKS_TASK, RunDarwinBenchmarksTask::class.java ) { val sharedService = project .gradle .sharedServices .registrations.getByName(XCodeBuildService.XCODE_BUILD_SERVICE_NAME) .service it.usesService(sharedService) it.xcodeProjectPath.set(generateXCodeProjectTask.flatMap { task -> task.xcProjectPath }) it.destination.set(extension.destination) it.scheme.set(extension.scheme) it.xcResultPath.set(xcResultPath) it.dependsOn(XCFRAMEWORK_TASK_NAME) } project.tasks.register( DARWIN_BENCHMARK_RESULTS_TASK, DarwinBenchmarkResultsTask::class.java ) { it.xcResultPath.set(runDarwinBenchmarks.flatMap { task -> task.xcResultPath }) val resultFileName = "${extension.xcodeProjectName.get()}-benchmark-result.json" it.outputFile.set( project.layout.buildDirectory.file( resultFileName ) ) val provider = project.benchmarksDistributionDirectory(extension) val resultFile = provider.map { directory -> directory.file(resultFileName) } it.distFile.set(resultFile) } } private fun Project.benchmarksDistributionDirectory( extension: DarwinBenchmarkPluginExtension ): Provider<Directory> { val distProvider = project.distributionDirectory() val benchmarksDirProvider = distProvider.flatMap { distDir -> extension.xcodeProjectName.map { projectName -> val projectPath = project.path.replace(":", "/") val benchmarksDirectory = File(distDir, DARWIN_BENCHMARKS_DIR) File(benchmarksDirectory, "$projectPath/$projectName") } } return project.layout.dir(benchmarksDirProvider) } private fun Project.distributionDirectory(): Provider<File> { // We want to write metrics to library metrics specific location // Context: b/257326666 return providers.environmentVariable(DIST_DIR).map { value -> File(value, LIBRARY_METRICS) } } private companion object { // Environment variables const val DIST_DIR = "DIST_DIR" const val LIBRARY_METRICS = "librarymetrics" const val DARWIN_BENCHMARKS_DIR = "darwinBenchmarks" // Gradle Properties const val XCODEGEN_DOWNLOAD_URI = "androidx.benchmark.darwin.xcodeGenDownloadUri" // Tasks const val FETCH_XCODEGEN_TASK = "fetchXCodeGen" const val GENERATE_XCODE_PROJECT_TASK = "generateXCodeProject" const val RUN_DARWIN_BENCHMARKS_TASK = "runDarwinBenchmarks" const val DARWIN_BENCHMARK_RESULTS_TASK = "darwinBenchmarkResults" // There is always a XCFrameworkConfig with the name `AndroidXDarwinBenchmarks` // The corresponding task name is `assemble{name}ReleaseXCFramework` const val XCFRAMEWORK_TASK_NAME = "assembleAndroidXDarwinBenchmarksReleaseXCFramework" } }
apache-2.0
e5ad08846842687673ae2157825a0362
40.162921
132
0.650744
4.779517
false
false
false
false
pthomain/SharedPreferenceStore
lib/src/main/java/uk/co/glass_software/android/shared_preferences/persistence/preferences/StoreUtils.kt
1
1937
/* * Copyright (C) 2017 Glass Software Ltd * * 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 uk.co.glass_software.android.shared_preferences.persistence.preferences import android.content.Context import uk.co.glass_software.android.boilerplate.core.utils.delegates.Prefs import uk.co.glass_software.android.boilerplate.core.utils.delegates.Prefs.Companion.prefs object StoreUtils { fun openSharedPreferences(context: Context, name: String) = getSharedPreferenceFactory(context)(name) private fun getSharedPreferenceFactory(context: Context): (String) -> Prefs = { context.prefs(getStoreName(context, it)) } private fun getStoreName(context: Context, name: String): String { val availableLength = StoreModule.MAX_FILE_NAME_LENGTH - name.length var packageName = context.packageName if (packageName.length > availableLength) { packageName = packageName.substring( packageName.length - availableLength - 1, packageName.length ) } return "$packageName$$name" } }
apache-2.0
865cc978b999f24dfd484b26f2191bec
35.566038
90
0.695405
4.579196
false
false
false
false
codehz/container
app/src/main/java/one/codehz/container/widget/OptimizingDialog.kt
1
1345
package one.codehz.container.widget import android.app.Dialog import android.content.Context import android.graphics.drawable.Drawable import android.widget.ImageView import android.widget.TextView import one.codehz.container.R import one.codehz.container.ext.get import one.codehz.container.ext.virtualCore import one.codehz.container.models.AppModel class OptimizingDialog(context: Context) : Dialog(context) { init { setContentView(R.layout.opt_dialog) } val iconView by lazy<ImageView> { this[R.id.icon] } val titleView by lazy<TextView> { this[R.id.title] } var name: CharSequence get() = titleView.text set(value) { titleView.text = value } var icon: Drawable get() = iconView.drawable set(value) { iconView.setImageDrawable(value) } class OptimizeHelper(val appModel: AppModel, val ui: (() -> Unit) -> Unit) { val dialog by lazy { OptimizingDialog(appModel.context) } fun optimize() { ui { dialog.apply { name = appModel.name icon = appModel.icon show() } } virtualCore.preOpt(appModel.packageName) ui { dialog.dismiss() } } } }
gpl-3.0
fec73849df27cf40c08e7a53a198057a
26.469388
80
0.594796
4.33871
false
false
false
false
solkin/drawa-android
app/src/main/java/com/tomclaw/drawa/play/PlayView.kt
1
2146
package com.tomclaw.drawa.play import android.graphics.drawable.Animatable import android.graphics.drawable.Drawable import android.view.View import android.widget.ImageView import androidx.appcompat.widget.Toolbar import com.jakewharton.rxrelay2.PublishRelay import com.tomclaw.drawa.R import com.tomclaw.drawa.util.show import com.tomclaw.drawa.util.toggle import io.reactivex.Observable interface PlayView { fun navigationClicks(): Observable<Unit> fun shareClicks(): Observable<Unit> fun replayClicks(): Observable<Unit> fun showDrawable(drawable: Drawable) fun showReplayButton() fun hideReplayButton() } class PlayViewImpl(view: View) : PlayView { private val toolbar: Toolbar = view.findViewById(R.id.toolbar) private val imageView: ImageView = view.findViewById(R.id.image_view) private val navigationRelay = PublishRelay.create<Unit>() private val shareRelay = PublishRelay.create<Unit>() private val replayRelay = PublishRelay.create<Unit>() init { toolbar.setTitle(R.string.play) toolbar.setNavigationOnClickListener { navigationRelay.accept(Unit) } toolbar.inflateMenu(R.menu.play) toolbar.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.menu_share -> shareRelay.accept(Unit) R.id.menu_replay -> replayRelay.accept(Unit) } true } imageView.scaleType = ImageView.ScaleType.FIT_CENTER imageView.setOnClickListener { toolbar.toggle() } } override fun navigationClicks(): Observable<Unit> = navigationRelay override fun shareClicks(): Observable<Unit> = shareRelay override fun replayClicks(): Observable<Unit> = replayRelay override fun showDrawable(drawable: Drawable) { imageView.setImageDrawable(drawable) (drawable as? Animatable)?.start() } override fun showReplayButton() { toolbar.menu.findItem(R.id.menu_replay).isVisible = true toolbar.show() } override fun hideReplayButton() { toolbar.menu.findItem(R.id.menu_replay).isVisible = false } }
apache-2.0
32d7479df44a1f359f0714ef9638c801
28
77
0.703169
4.388548
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/CommunityParentViewHolder.kt
2
1557
package ru.fantlab.android.ui.adapter.viewholder import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.community_parent_row_item.view.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.Community import ru.fantlab.android.data.dao.model.CommunityTreeParent import ru.fantlab.android.ui.widgets.treeview.TreeNode import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter import ru.fantlab.android.ui.widgets.treeview.TreeViewBinder class CommunityParentViewHolder : TreeViewBinder<CommunityParentViewHolder.ViewHolder>() { override val layoutId: Int = R.layout.community_parent_row_item override fun provideViewHolder(itemView: View): ViewHolder = ViewHolder(itemView) override fun bindView( holder: RecyclerView.ViewHolder, position: Int, node: TreeNode<*>, onTreeNodeListener: TreeViewAdapter.OnTreeNodeListener? ) { (holder as ViewHolder).expandButton.rotation = 0f holder.expandButton.setImageResource(R.drawable.ic_arrow_right) val rotateDegree = if (node.isExpand) 90f else 0f holder.expandButton.rotation = rotateDegree val parentNode = node.content as CommunityTreeParent holder.title.text = parentNode.title holder.expandButton.isVisible = !node.isLeaf } class ViewHolder(rootView: View) : TreeViewBinder.ViewHolder(rootView) { val expandButton: ImageView = rootView.expandButton var title: TextView = rootView.communityGroupTitle } }
gpl-3.0
e89f6748e469bed80a021c5da0ca770c
39.973684
125
0.817598
3.91206
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/download/DownloadController.kt
1
3090
package de.westnordost.streetcomplete.data.download import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.IBinder import de.westnordost.osmapi.map.data.BoundingBox import de.westnordost.streetcomplete.ApplicationConstants import de.westnordost.streetcomplete.util.enclosingTilesRect import javax.inject.Inject import javax.inject.Singleton /** Controls downloading */ @Singleton class DownloadController @Inject constructor( private val context: Context ): DownloadProgressSource { private var downloadServiceIsBound: Boolean = false private var downloadService: DownloadService.Interface? = null private val downloadServiceConnection = object : ServiceConnection { override fun onServiceConnected(className: ComponentName, service: IBinder) { downloadService = service as DownloadService.Interface downloadService?.setProgressListener(downloadProgressRelay) } override fun onServiceDisconnected(className: ComponentName) { downloadService = null } } private val downloadProgressRelay = DownloadProgressRelay() /** @return true if a download triggered by the user is running */ override val isPriorityDownloadInProgress: Boolean get() = downloadService?.isPriorityDownloadInProgress == true /** @return true if a download is running */ override val isDownloadInProgress: Boolean get() = downloadService?.isDownloadInProgress == true var showNotification: Boolean get() = downloadService?.showDownloadNotification == true set(value) { downloadService?.showDownloadNotification = value } init { bindServices() } /** Download in at least the given bounding box asynchronously. The next-bigger rectangle * in a (z16) tiles grid that encloses the given bounding box will be downloaded. * * @param bbox the minimum area to download * @param isPriority whether this shall be a priority download (cancels previous downloads and * puts itself in the front) */ fun download(bbox: BoundingBox, isPriority: Boolean = false) { val tilesRect = bbox.enclosingTilesRect(ApplicationConstants.QUEST_TILE_ZOOM) context.startService(DownloadService.createIntent(context, tilesRect, isPriority)) } private fun bindServices() { downloadServiceIsBound = context.bindService( Intent(context, DownloadService::class.java), downloadServiceConnection, Context.BIND_AUTO_CREATE ) } private fun unbindServices() { if (downloadServiceIsBound) context.unbindService(downloadServiceConnection) downloadServiceIsBound = false } override fun addDownloadProgressListener(listener: DownloadProgressListener) { downloadProgressRelay.addListener(listener) } override fun removeDownloadProgressListener(listener: DownloadProgressListener) { downloadProgressRelay.removeListener(listener) } }
gpl-3.0
2746972736f85dbdd9a1bf26e20519a2
38.113924
98
0.740777
5.498221
false
false
false
false
HabitRPG/habitica-android
shared/src/commonMain/kotlin/com/habitrpg/shared/habitica/models/responses/ErrorResponse.kt
1
475
package com.habitrpg.shared.habitica.models.responses class ErrorResponse { var message: String? = null var errors: List<HabiticaError>? = null val displayMessage: String get() { if (errors?.isNotEmpty() == true) { val error = errors?.get(0) if (error?.message?.isNotBlank() == true) { return error.message ?: "" } } return message ?: "" } }
gpl-3.0
77f2475d2bc777475145cc474e4fc434
28.6875
59
0.505263
4.70297
false
false
false
false
mitallast/netty-queue
src/main/java/org/mitallast/queue/crdt/bucket/DefaultBucket.kt
1
2245
package org.mitallast.queue.crdt.bucket import com.google.inject.assistedinject.Assisted import org.apache.logging.log4j.LogManager import org.mitallast.queue.crdt.log.DefaultCompactionFilter import org.mitallast.queue.crdt.log.ReplicatedLog import org.mitallast.queue.crdt.log.ReplicatedLogFactory import org.mitallast.queue.crdt.registry.CrdtRegistry import org.mitallast.queue.crdt.registry.CrdtRegistryFactory import org.mitallast.queue.crdt.replication.Replicator import org.mitallast.queue.crdt.replication.ReplicatorFactory import org.mitallast.queue.crdt.replication.state.ReplicaState import org.mitallast.queue.crdt.replication.state.ReplicaStateFactory import java.util.concurrent.locks.ReentrantLock import javax.inject.Inject class DefaultBucket @Inject constructor( @param:Assisted private val index: Int, @param:Assisted private val replica: Long, crdtRegistryFactory: CrdtRegistryFactory, logFactory: ReplicatedLogFactory, stateFactory: ReplicaStateFactory, replicatorFactory: ReplicatorFactory ) : Bucket { private val logger = LogManager.getLogger("replicator[$index]") private val lock = ReentrantLock() private val replicaState = stateFactory.create(index, replica) private val replicator = replicatorFactory.create(this) private val registry = crdtRegistryFactory.create(index, replica, replicator) private val log = logFactory.create(index, replica, DefaultCompactionFilter(registry)) init { replicator.start() } override fun index(): Int { return index } override fun replica(): Long { return replica } override fun lock(): ReentrantLock { return lock } override fun registry(): CrdtRegistry { return registry } override fun log(): ReplicatedLog { return log } override fun replicator(): Replicator { return replicator } override fun state(): ReplicaState { return replicaState } override fun close() { logger.info("close") replicator.stop() log.close() replicaState.close() } override fun delete() { logger.info("delete") log.delete() replicaState.delete() } }
mit
70c03255de61f0a76a6fe1360fad239b
28.155844
90
0.723385
4.325626
false
false
false
false
jiaminglu/kotlin-native
runtime/src/main/kotlin/konan/worker/Worker.kt
1
9069
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package konan.worker import konan.SymbolName import konan.internal.ExportForCppRuntime import kotlinx.cinterop.* /** * Workers: theory of operations. * * Worker represent asynchronous and concurrent computation, usually performed by other threads * in the same process. Object passing between workers is performed using transfer operation, so that * object graph belongs to one worker at the time, but can be disconnected and reconnected as needed. * See 'Object Transfer Basics' below for more details on how objects shall be transferred. * This approach ensures that no concurrent access happens to same object, while data may flow between * workers as needed. */ /** * State of the future object. */ enum class FutureState(val value: Int) { INVALID(0), // Future is scheduled for execution. SCHEDULED(1), // Future result is computed. COMPUTED(2), // Future is cancelled. CANCELLED(3) } /** * Object Transfer Basics. * * Objects can be passed between threads in one of two possible modes. * * - CHECKED - object subgraph is checked to be not reachable by other globals or locals, and passed * if so, otherwise an exception is thrown * - UNCHECKED - object is blindly passed to another worker, if there are references * left in the passing worker - it may lead to crash or program malfunction * * Checked mode checks if object is no longer used in passing worker, using memory-management * specific algorithm (ARC implementation relies on trial deletion on object graph rooted in * passed object), and throws IllegalStateException if object graph rooted in transferred object * is reachable by some other means, * * Unchecked mode, intended for most performance crititcal operations, where object graph ownership * is expected to be correct (such as application debugged earlier in CHECKED mode), just transfers * ownership without further checks. * * Note, that for some cases cycle collection need to be done to ensure that dead cycles do not affect * reachability of passed object graph. See `konan.internal.GC.collect()`. * */ enum class TransferMode(val value: Int) { CHECKED(0), UNCHECKED(1) // USE UNCHECKED MODE ONLY IF ABSOLUTELY SURE WHAT YOU'RE DOING!!! } /** * Unique identifier of the worker. Workers can be used from other workers. */ typealias WorkerId = Int /** * Unique identifier of the future. Futures can be used from other workers. */ typealias FutureId = Int /** * Class representing abstract computation, whose result may become available in the future. */ // TODO: make me value class! class Future<T> internal constructor(val id: FutureId) { /** * Blocks execution until the future is ready. */ fun consume(code: (T) -> Unit) { when (state) { FutureState.SCHEDULED, FutureState.COMPUTED -> { val value = @Suppress("UNCHECKED_CAST") (consumeFuture(id) as T) code(value) } FutureState.INVALID -> throw IllegalStateException("Future is in an invalid state: $state") FutureState.CANCELLED -> throw IllegalStateException("Future is cancelled") } } val state: FutureState get() = FutureState.values()[stateOfFuture(id)] override fun equals(other: Any?): Boolean { return (other is Future<*>) && (id == other.id) } override fun hashCode(): Int { return id } } /** * Class representing worker. */ // TODO: make me value class! class Worker(val id: WorkerId) { /** * Requests termination of the worker. `processScheduledJobs` controls is we shall wait * until all scheduled jobs processed, or terminate immediately. */ fun requestTermination(processScheduledJobs: Boolean = true) = Future<Any?>(requestTerminationInternal(id, processScheduledJobs)) /** * Schedule a job for further execution in the worker. Schedule is a two-phase operation, * first `producer` function is executed, and resulting object and whatever it refers to * is analyzed for being an isolated object subgraph, if in checked mode. * Afterwards, this disconnected object graph and `job` function pointer is being added to jobs queue * of the selected worker. Note that `job` must not capture any state itself, so that whole state is * explicitly stored in object produced by `producer`. Scheduled job is being executed by the worker, * and result of such a execution is being disconnected from worker's object graph. Whoever will consume * the future, can use result of worker's computations. */ @Suppress("UNUSED_PARAMETER") fun <T1, T2> schedule(mode: TransferMode, producer: () -> T1, @VolatileLambda job: (T1) -> T2): Future<T2> = /** * This function is a magical operation, handled by lowering in the compiler, and replaced with call to * scheduleImpl(worker, mode, producer, job) * but first ensuring that `job` parameter doesn't capture any state. */ throw RuntimeException("Shall not be called directly") override fun equals(other: Any?): Boolean { return (other is Worker) && (id == other.id) } override fun hashCode(): Int { return id } } /** * Start new scheduling primitive, such as thread, to accept new tasks via `schedule` interface. * Typically new worker may be needed for computations offload to another core, for IO it may be * better to use non-blocking IO combined with more lightweight coroutines. */ fun startWorker(): Worker = Worker(startInternal()) /** * Wait for availability of futures in the collection. Returns set with all futures which have * value available for the consumption. */ fun <T> Collection<Future<T>>.waitForMultipleFutures(millis: Int): Set<Future<T>> { val result = mutableSetOf<Future<T>>() while (true) { val versionToken = versionToken() for (future in this) { if (future.state == FutureState.COMPUTED) { result += future } } if (result.isNotEmpty()) return result if (waitForAnyFuture(versionToken, millis)) break } for (future in this) { if (future.state == FutureState.COMPUTED) { result += future } } return result } /** * Creates verbatim *shallow* copy of passed object, use carefully to create disjoint object graph. */ fun <T> T.shallowCopy(): T = @Suppress("UNCHECKED_CAST") (shallowCopyInternal(this) as T) /** * Creates verbatim *deep* copy of passed object's graph, use *VERY* carefully to create disjoint object graph. * Note that this function could potentially duplicate a lot of objects. */ fun <T> T.deepCopy(): T = TODO() // Implementation details. @konan.internal.ExportForCompiler internal fun scheduleImpl(worker: Worker, mode: TransferMode, producer: () -> Any?, job: CPointer<CFunction<*>>): Future<Any?> = Future<Any?>(scheduleInternal(worker.id, mode.value, producer, job)) @SymbolName("Kotlin_Worker_startInternal") external internal fun startInternal(): WorkerId @SymbolName("Kotlin_Worker_requestTerminationWorkerInternal") external internal fun requestTerminationInternal(id: WorkerId, processScheduledJobs: Boolean): FutureId @SymbolName("Kotlin_Worker_scheduleInternal") external internal fun scheduleInternal( id: WorkerId, mode: Int, producer: () -> Any?, job: CPointer<CFunction<*>>): FutureId @SymbolName("Kotlin_Worker_shallowCopyInternal") external internal fun shallowCopyInternal(value: Any?): Any? @SymbolName("Kotlin_Worker_stateOfFuture") external internal fun stateOfFuture(id: FutureId): Int @SymbolName("Kotlin_Worker_consumeFuture") external internal fun consumeFuture(id: FutureId): Any? @SymbolName("Kotlin_Worker_waitForAnyFuture") external internal fun waitForAnyFuture(versionToken: Int, millis: Int): Boolean @SymbolName("Kotlin_Worker_versionToken") external internal fun versionToken(): Int @ExportForCppRuntime internal fun ThrowWorkerUnsupported(): Unit = throw UnsupportedOperationException("Workers are not supported") @ExportForCppRuntime internal fun ThrowWorkerInvalidState(): Unit = throw IllegalStateException("Illegal transfer state") @ExportForCppRuntime internal fun WorkerLaunchpad(function: () -> Any?) = function()
apache-2.0
a9c5af4576537b5578ecd46ea843a058
36.320988
115
0.700959
4.368497
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/source/online/all/Hitomi.kt
1
15696
package eu.kanade.tachiyomi.source.online.all import android.net.Uri import android.os.Build import com.github.salomonbrys.kotson.array import com.github.salomonbrys.kotson.get import com.github.salomonbrys.kotson.string import com.google.gson.JsonParser import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.model.* import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.source.online.LewdSource import eu.kanade.tachiyomi.source.online.UrlImportableSource import eu.kanade.tachiyomi.util.asJsoup import exh.GalleryAddEvent import exh.HITOMI_SOURCE_ID import exh.hitomi.HitomiNozomi import exh.metadata.metadata.HitomiSearchMetadata import exh.metadata.metadata.HitomiSearchMetadata.Companion.BASE_URL import exh.metadata.metadata.HitomiSearchMetadata.Companion.LTN_BASE_URL import exh.metadata.metadata.HitomiSearchMetadata.Companion.TAG_TYPE_DEFAULT import exh.metadata.metadata.base.RaisedSearchMetadata.Companion.TAG_TYPE_VIRTUAL import exh.metadata.metadata.base.RaisedTag import exh.util.urlImportFetchSearchManga import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.vepta.vdm.ByteCursor import rx.Observable import rx.Single import rx.schedulers.Schedulers import uy.kohesive.injekt.injectLazy import java.text.SimpleDateFormat import java.util.* /** * Man, I hate this source :( */ class Hitomi : HttpSource(), LewdSource<HitomiSearchMetadata, Document>, UrlImportableSource { private val prefs: PreferencesHelper by injectLazy() private val jsonParser by lazy { JsonParser() } override val id = HITOMI_SOURCE_ID /** * Whether the source has support for latest updates. */ override val supportsLatest = true /** * Name of the source. */ override val name = "hitomi.la" /** * The class of the metadata used by this source */ override val metaClass = HitomiSearchMetadata::class private var cachedTagIndexVersion: Long? = null private var tagIndexVersionCacheTime: Long = 0 private fun tagIndexVersion(): Single<Long> { val sCachedTagIndexVersion = cachedTagIndexVersion return if(sCachedTagIndexVersion == null || tagIndexVersionCacheTime + INDEX_VERSION_CACHE_TIME_MS < System.currentTimeMillis()) { HitomiNozomi.getIndexVersion(client, "tagindex").subscribeOn(Schedulers.io()).doOnNext { cachedTagIndexVersion = it tagIndexVersionCacheTime = System.currentTimeMillis() }.toSingle() } else { Single.just(sCachedTagIndexVersion) } } private var cachedGalleryIndexVersion: Long? = null private var galleryIndexVersionCacheTime: Long = 0 private fun galleryIndexVersion(): Single<Long> { val sCachedGalleryIndexVersion = cachedGalleryIndexVersion return if(sCachedGalleryIndexVersion == null || galleryIndexVersionCacheTime + INDEX_VERSION_CACHE_TIME_MS < System.currentTimeMillis()) { HitomiNozomi.getIndexVersion(client, "galleriesindex").subscribeOn(Schedulers.io()).doOnNext { cachedGalleryIndexVersion = it galleryIndexVersionCacheTime = System.currentTimeMillis() }.toSingle() } else { Single.just(sCachedGalleryIndexVersion) } } /** * Parse the supplied input into the supplied metadata object */ override fun parseIntoMetadata(metadata: HitomiSearchMetadata, input: Document) { with(metadata) { url = input.location() tags.clear() thumbnailUrl = "https:" + input.selectFirst(".cover img").attr("src") val galleryElement = input.selectFirst(".gallery") title = galleryElement.selectFirst("h1").text() artists = galleryElement.select("h2 a").map { it.text() } tags += artists.map { RaisedTag("artist", it, TAG_TYPE_VIRTUAL) } input.select(".gallery-info tr").forEach { val content = it.child(1) when(it.child(0).text().toLowerCase()) { "group" -> { group = content.text() tags += RaisedTag("group", group!!, TAG_TYPE_VIRTUAL) } "type" -> { type = content.text() tags += RaisedTag("type", type!!, TAG_TYPE_VIRTUAL) } "series" -> { series = content.select("a").map { it.text() } tags += series.map { RaisedTag("series", it, TAG_TYPE_VIRTUAL) } } "language" -> { language = content.selectFirst("a")?.attr("href")?.split('-')?.get(1) language?.let { tags += RaisedTag("language", it, TAG_TYPE_VIRTUAL) } } "characters" -> { characters = content.select("a").map { it.text() } tags += characters.map { RaisedTag("character", it, TAG_TYPE_DEFAULT) } } "tags" -> { tags += content.select("a").map { val ns = if(it.attr("href").startsWith("/tag/male")) "male" else "female" RaisedTag(ns, it.text().dropLast(2), TAG_TYPE_DEFAULT) } } } } uploadDate = DATE_FORMAT.parse(input.selectFirst(".gallery-info .date").text()).time } } override val lang = "all" /** * Base url of the website without the trailing slash, like: http://mysite.com */ override val baseUrl = BASE_URL /** * Returns the request for the popular manga given the page. * * @param page the page number to retrieve. */ override fun popularMangaRequest(page: Int) = HitomiNozomi.rangedGet( "$LTN_BASE_URL/popular-all.nozomi", 100L * (page - 1), 99L + 100 * (page - 1) ) /** * Parses the response from the site and returns a [MangasPage] object. * * @param response the response from the site. */ override fun popularMangaParse(response: Response) = throw UnsupportedOperationException() /** * Returns the request for the search manga given the page. * * @param page the page number to retrieve. * @param query the search query. * @param filters the list of filters to apply. */ override fun searchMangaRequest(page: Int, query: String, filters: FilterList) = throw UnsupportedOperationException() override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { return urlImportFetchSearchManga(query) { val splitQuery = query.split(" ") val positive = splitQuery.filter { !it.startsWith('-') }.toMutableList() val negative = (splitQuery - positive).map { it.removePrefix("-") } // TODO Cache the results coming out of HitomiNozomi val hn = Single.zip(tagIndexVersion(), galleryIndexVersion()) { tv, gv -> tv to gv } .map { HitomiNozomi(client, it.first, it.second) } var base = if(positive.isEmpty()) { hn.flatMap { n -> n.getGalleryIdsFromNozomi(null, "index", "all").map { n to it.toSet() } } } else { val q = positive.removeAt(0) hn.flatMap { n -> n.getGalleryIdsForQuery(q).map { n to it.toSet() } } } base = positive.fold(base) { acc, q -> acc.flatMap { (nozomi, mangas) -> nozomi.getGalleryIdsForQuery(q).map { nozomi to mangas.intersect(it) } } } base = negative.fold(base) { acc, q -> acc.flatMap { (nozomi, mangas) -> nozomi.getGalleryIdsForQuery(q).map { nozomi to (mangas - it) } } } base.flatMap { (_, ids) -> val chunks = ids.chunked(PAGE_SIZE) nozomiIdsToMangas(chunks[page - 1]).map { mangas -> MangasPage(mangas, page < chunks.size) } }.toObservable() } } /** * Parses the response from the site and returns a [MangasPage] object. * * @param response the response from the site. */ override fun searchMangaParse(response: Response) = throw UnsupportedOperationException() /** * Returns the request for latest manga given the page. * * @param page the page number to retrieve. */ override fun latestUpdatesRequest(page: Int) = HitomiNozomi.rangedGet( "$LTN_BASE_URL/index-all.nozomi", 100L * (page - 1), 99L + 100 * (page - 1) ) /** * Parses the response from the site and returns a [MangasPage] object. * * @param response the response from the site. */ override fun latestUpdatesParse(response: Response) = throw UnsupportedOperationException() override fun fetchPopularManga(page: Int): Observable<MangasPage> { return client.newCall(popularMangaRequest(page)) .asObservableSuccess() .flatMap { responseToMangas(it) } } override fun fetchLatestUpdates(page: Int): Observable<MangasPage> { return client.newCall(latestUpdatesRequest(page)) .asObservableSuccess() .flatMap { responseToMangas(it) } } fun responseToMangas(response: Response): Observable<MangasPage> { val range = response.header("Content-Range")!! val total = range.substringAfter('/').toLong() val end = range.substringBefore('/').substringAfter('-').toLong() val body = response.body()!! return parseNozomiPage(body.bytes()) .map { MangasPage(it, end < total - 1) } } private fun parseNozomiPage(array: ByteArray): Observable<List<SManga>> { val cursor = ByteCursor(array) val ids = (1 .. array.size / 4).map { cursor.nextInt() } return nozomiIdsToMangas(ids).toObservable() } private fun nozomiIdsToMangas(ids: List<Int>): Single<List<SManga>> { return Single.zip(ids.map { client.newCall(GET("$LTN_BASE_URL/galleryblock/$it.html")) .asObservableSuccess() .subscribeOn(Schedulers.io()) // Perform all these requests in parallel .map { parseGalleryBlock(it) } .toSingle() }) { it.map { m -> m as SManga } } } private fun parseGalleryBlock(response: Response): SManga { val doc = response.asJsoup() return SManga.create().apply { val titleElement = doc.selectFirst("h1") title = titleElement.text() thumbnail_url = "https:" + if(prefs.eh_hl_useHighQualityThumbs().getOrDefault()) { doc.selectFirst("img").attr("data-srcset").substringBefore(' ') } else { doc.selectFirst("img").attr("data-src") } url = titleElement.child(0).attr("href") // TODO Parse tags and stuff } } /** * Returns an observable with the updated details for a manga. Normally it's not needed to * override this method. * * @param manga the manga to be updated. */ override fun fetchMangaDetails(manga: SManga): Observable<SManga> { return client.newCall(mangaDetailsRequest(manga)) .asObservableSuccess() .flatMap { parseToManga(manga, it.asJsoup()).andThen(Observable.just(manga.apply { initialized = true })) } } override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> { return Observable.just( listOf( SChapter.create().apply { url = manga.url name = "Chapter" chapter_number = 0.0f } ) ) } override fun pageListRequest(chapter: SChapter): Request { return GET("$LTN_BASE_URL/galleries/${HitomiSearchMetadata.hlIdFromUrl(chapter.url)}.js") } /** * Parses the response from the site and returns the details of a manga. * * @param response the response from the site. */ override fun mangaDetailsParse(response: Response) = throw UnsupportedOperationException() /** * Parses the response from the site and returns a list of chapters. * * @param response the response from the site. */ override fun chapterListParse(response: Response) = throw UnsupportedOperationException() /** * Parses the response from the site and returns a list of pages. * * @param response the response from the site. */ override fun pageListParse(response: Response): List<Page> { val hlId = response.request().url().pathSegments().last().removeSuffix(".js").toLong() val str = response.body()!!.string() val json = jsonParser.parse(str.removePrefix("var galleryinfo =")) return json.array.mapIndexed { index, jsonElement -> Page( index, "", "https://${subdomainFromGalleryId(hlId)}a.hitomi.la/galleries/$hlId/${jsonElement["name"].string}" ) } } private fun subdomainFromGalleryId(id: Long): Char { return (97 + id.rem(NUMBER_OF_FRONTENDS)).toChar() } /** * Parses the response from the site and returns the absolute url to the source image. * * @param response the response from the site. */ override fun imageUrlParse(response: Response) = throw UnsupportedOperationException() override fun imageRequest(page: Page): Request { val request = super.imageRequest(page) val hlId = request.url().pathSegments().let { it[it.lastIndex - 1] } return request.newBuilder() .header("Referer", "$BASE_URL/reader/$hlId.html") .build() } override val matchingHosts = listOf( "hitomi.la" ) override fun mapUrlToMangaUrl(uri: Uri): String? { val lcFirstPathSegment = uri.pathSegments.firstOrNull()?.toLowerCase() ?: return null if(lcFirstPathSegment != "galleries" && lcFirstPathSegment != "reader") return null return "https://hitomi.la/galleries/${uri.pathSegments[1].substringBefore('.')}.html" } companion object { private val INDEX_VERSION_CACHE_TIME_MS = 1000 * 60 * 10 private val PAGE_SIZE = 25 private val NUMBER_OF_FRONTENDS = 2 private val DATE_FORMAT by lazy { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) SimpleDateFormat("yyyy-MM-dd HH:mm:ssX", Locale.US) else SimpleDateFormat("yyyy-MM-dd HH:mm:ss'-05'", Locale.US) } } }
apache-2.0
ba16cecc81bd749241d951c6d9c52403
36.194313
110
0.586009
4.639669
false
false
false
false
GDGLima/CodeLab-Kotlin-Infosoft-2017
Infosoft2017/app/src/main/java/com/emedinaa/infosoft2017/ui/EventsActivityK.kt
1
3740
package com.emedinaa.infosoft2017.ui import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View import android.widget.TextView import com.emedinaa.infosoft2017.R import com.emedinaa.infosoft2017.data.model.EventResponseK import com.emedinaa.infosoft2017.data.storage.ApliClientK import com.emedinaa.infosoft2017.model.EntityK import com.emedinaa.infosoft2017.ui.adapterskt.EventAdapterK import kotlinx.android.synthetic.main.activity_events.* import kotlinx.android.synthetic.main.layout_progress.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response /** * Kotlin collections * https://kotlinlang.org/docs/reference/collections.html */ class EventsActivityK : BaseActivityK() { private var eventAdapter:EventAdapterK?=null private var currentView:TextView?=null val dates = listOf("2017/09/04", "2017/09/05", "2017/09/06","2017/09/07") var views:List<TextView> = mutableListOf() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_events) ui() requestFirst() } private fun requestFirst(){ currentView=views[0] val date:String = dates[0] updateViewSelected() requestEvents(date) } private fun updateViewPrev(){ currentView!!.setBackgroundColor(resources.getColor(android.R.color.white)) currentView!!.setTextColor(resources.getColor(android.R.color.black)) } private fun updateViewSelected() { currentView!!.setBackgroundColor(resources.getColor(R.color.greenInfosoft)) currentView!!.setTextColor(resources.getColor(android.R.color.white)) } private fun ui(){ supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title="Programa" val mLayoutManager: RecyclerView.LayoutManager = LinearLayoutManager(this) recyclerViewEvents.layoutManager= mLayoutManager views=listOf(textViewMon, textViewTue,textViewWed,textViewThu) //events views.forEach { it.setOnClickListener{ if(currentView!=null){ updateViewPrev() } val date:String = dates[views.indexOf(it)] requestEvents(date) currentView= it as TextView updateViewSelected() } } /*for (i in arr.indices) { println(arr[i]) }*/ } private fun renderEvents(events:List<EntityK.EventK>){ eventAdapter= EventAdapterK(events!!,this) recyclerViewEvents.setAdapter(eventAdapter!!) } //endpoints private val callback: Callback<EventResponseK> = object: Callback<EventResponseK> { override fun onResponse(call: Call<EventResponseK>?, response: Response<EventResponseK>?) { hideLoading() log({"onResponse $response.body()"}) renderEvents(response!!.body()!!.data) } override fun onFailure(call: Call<EventResponseK>?, t: Throwable?) { if(!call!!.isCanceled)hideLoading() log({"onFailure $t"}) } } private fun requestEvents(date:String){ showLoading() val call: Call<EventResponseK> = ApliClientK.getMyApiClient().events(date) call!!.enqueue(callback) } private fun showLoading(){ relativeLayoutProgress.visibility= View.VISIBLE } private fun hideLoading(){ relativeLayoutProgress.visibility= View.GONE } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } }
apache-2.0
1179139580889e1a88477da380b78dc2
29.16129
99
0.670053
4.622991
false
false
false
false
googlesamples/android-media-controller
mediacontroller/src/main/java/com/example/android/mediacontroller/testing/TestDescriptor.kt
1
16985
package com.example.android.mediacontroller.testing import android.content.Context import android.os.Build import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.session.MediaControllerCompat import android.widget.Toast import com.example.android.mediacontroller.* class TestDescriptor { var testList: List<TestOptionDetails>? = null var testSuites: List<MediaAppTestSuite>? = null fun setupTests(context: Context, mediaController: MediaControllerCompat, mediaAppDetails: MediaAppDetails?, mediaBrowser: MediaBrowserCompat?) { /** * Tests the play() transport control. The test can start in any state, might enter a * transition state, but must eventually end in STATE_PLAYING. The test will fail for * any terminal state other than the starting state and STATE_PLAYING. The test * will also fail if the metadata changes unless the test began with null metadata. */ val playTest = TestOptionDetails( 0, context.getString(R.string.play_test_title), context.getString(R.string.play_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> runPlayTest(testId, mediaController, callback) } /** * Tests the playFromSearch() transport control. The test can start in any state, might * enter a transition state, but must eventually end in STATE_PLAYING with playback * position at 0. The test will fail for any terminal state other than the starting state * and STATE_PLAYING. This test does not perform any metadata checks. */ val playFromSearch = TestOptionDetails( 1, context.getString(R.string.play_search_test_title), context.getString(R.string.play_search_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { query, callback, testId -> runPlayFromSearchTest( testId, query, mediaController, callback ) } /** * Tests the playFromMediaId() transport control. The test can start in any state, might * enter a transition state, but must eventually end in STATE_PLAYING with playback * position at 0. The test will fail for any terminal state other than the starting state * and STATE_PLAYING. The test will also fail if query is empty/null. This test does not * perform any metadata checks. */ val playFromMediaId = TestOptionDetails( 2, context.getString(R.string.play_media_id_test_title), context.getString(R.string.play_media_id_test_desc), TestResult.NONE, Test.NO_LOGS, true ) { query, callback, testId -> runPlayFromMediaIdTest( testId, query, mediaController, callback ) } /** * Tests the playFromUri() transport control. The test can start in any state, might * enter a transition state, but must eventually end in STATE_PLAYING with playback * position at 0. The test will fail for any terminal state other than the starting state * and STATE_PLAYING. The test will also fail if query is empty/null. This test does not * perform any metadata checks. */ val playFromUri = TestOptionDetails( 3, context.getString(R.string.play_uri_test_title), context.getString(R.string.play_uri_test_desc), TestResult.NONE, Test.NO_LOGS, true ) { query, callback, testId -> runPlayFromUriTest( testId, query, mediaController, callback ) } /** * Tests the pause() transport control. The test can start in any state, but must end in * STATE_PAUSED (but STATE_STOPPED is also okay if that is the state the test started with). * The test will fail for any terminal state other than the starting state, STATE_PAUSED, * and STATE_STOPPED. The test will also fail if the metadata changes unless the test began * with null metadata. */ val pauseTest = TestOptionDetails( 4, context.getString(R.string.pause_test_title), context.getString(R.string.pause_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> runPauseTest(testId, mediaController, callback) } /** * Tests the stop() transport control. The test can start in any state, but must end in * STATE_STOPPED or STATE_NONE. The test will fail for any terminal state other than the * starting state, STATE_STOPPED, and STATE_NONE. The test will also fail if the metadata * changes to a non-null media item different from the original media item. */ val stopTest = TestOptionDetails( 5, context.getString(R.string.stop_test_title), context.getString(R.string.stop_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> runStopTest(testId, mediaController, callback) } /** * Tests the skipToNext() transport control. The test can start in any state, might * enter a transition state, but must eventually end in STATE_PLAYING with the playback * position at 0 if a new media item is started or in the starting state if the media item * doesn't change. The test will fail for any terminal state other than the starting state * and STATE_PLAYING. The metadata must change, but might just "change" to be the same as * the original metadata (e.g. if the next media item is the same as the current one); the * test will not pass if the metadata doesn't get updated at some point. */ val skipToNextTest = TestOptionDetails( 6, context.getString(R.string.skip_next_test_title), context.getString(R.string.skip_next_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> runSkipToNextTest( testId, mediaController, callback ) } /** * Tests the skipToPrevious() transport control. The test can start in any state, might * enter a transition state, but must eventually end in STATE_PLAYING with the playback * position at 0 if a new media item is started or in the starting state if the media item * doesn't change. The test will fail for any terminal state other than the starting state * and STATE_PLAYING. The metadata must change, but might just "change" to be the same as * the original metadata (e.g. if the previous media item is the same as the current one); * the test will not pass if the metadata doesn't get updated at some point. */ val skipToPrevTest = TestOptionDetails( 7, context.getString(R.string.skip_prev_test_title), context.getString(R.string.skip_prev_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> runSkipToPrevTest( testId, mediaController, callback ) } /** * Tests the skipToQueueItem() transport control. The test can start in any state, might * enter a transition state, but must eventually end in STATE_PLAYING with the playback * position at 0 if a new media item is started or in the starting state if the media item * doesn't change. The test will fail for any terminal state other than the starting state * and STATE_PLAYING. The metadata must change, but might just "change" to be the same as * the original metadata (e.g. if the next media item is the same as the current one); the * test will not pass if the metadata doesn't get updated at some point. */ val skipToItemTest = TestOptionDetails( 8, context.getString(R.string.skip_item_test_title), context.getString(R.string.skip_item_test_desc), TestResult.NONE, Test.NO_LOGS, true ) { query, callback, testId -> runSkipToItemTest( testId, query, mediaController, callback ) } /** * Tests the seekTo() transport control. The test can start in any state, might enter a * transition state, but must eventually end in a terminal state with playback position at * the requested timestamp. While not required, it is expected that the test will end in * the same state as it started. Metadata might change for this test if the requested * timestamp is outside the bounds of the current media item. The query should either be * a position in seconds or a change in position (number of seconds prepended by '+' to go * forward or '-' to go backwards). The test will fail if the query can't be parsed to a * Long. */ val seekToTest = TestOptionDetails( 9, context.getString(R.string.seek_test_title), context.getString(R.string.seek_test_desc), TestResult.NONE, Test.NO_LOGS, true ) { query, callback, testId -> runSeekToTest( testId, query, mediaController, callback ) } /** * Automotive and Auto shared tests */ val browseTreeDepthTest = TestOptionDetails( 10, context.getString(R.string.browse_tree_depth_test_title), context.getString(R.string.browse_tree_depth_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { runBrowseTreeDepthTest( testId, mediaController, mediaBrowser, callback ) } else { Toast.makeText( context, "This test requires minSDK 24", Toast.LENGTH_SHORT ) .show() } } val mediaArtworkTest = TestOptionDetails( 11, context.getString(R.string.media_artwork_test_title), context.getString(R.string.media_artwork_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { runMediaArtworkTest( testId, mediaController, mediaBrowser, callback ) } else { Toast.makeText( context, "This test requires minSDK 24", Toast.LENGTH_SHORT ) .show() } } val contentStyleTest = TestOptionDetails( 12, context.getString(R.string.content_style_test_title), context.getString(R.string.content_style_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> runContentStyleTest( testId, mediaController, mediaBrowser, callback ) } val customActionIconTypeTest = TestOptionDetails( 13, context.getString(R.string.custom_actions_icon_test_title), context.getString(R.string.custom_actions_icon_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> runCustomActionIconTypeTest( testId, context, mediaController, mediaAppDetails!!, callback ) } val supportsSearchTest = TestOptionDetails( 14, context.getString(R.string.search_supported_test_title), context.getString(R.string.search_supported_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> runSearchTest( testId, mediaController, mediaBrowser, callback ) } val initialPlaybackStateTest = TestOptionDetails( -1, // this test must be run first context.getString(R.string.playback_state_test_title), context.getString(R.string.playback_state_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> runInitialPlaybackStateTest( testId, mediaController, callback ) } /** * Automotive specific tests */ val browseTreeStructureTest = TestOptionDetails( 16, context.getString(R.string.browse_tree_structure_test_title), context.getString(R.string.browse_tree_structure_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { runBrowseTreeStructureTest( testId, mediaController, mediaBrowser, callback ) } else { Toast.makeText( context, context.getString(R.string.test_error_minsdk), Toast.LENGTH_SHORT ) .show() } } val preferenceTest = TestOptionDetails( 17, context.getString(R.string.preference_activity_test_title), context.getString(R.string.preference_activity_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> runPreferenceTest( testId, mediaController, mediaAppDetails, context.packageManager, callback ) } val errorResolutionDataTest = TestOptionDetails( 18, context.getString(R.string.error_resolution_test_title), context.getString(R.string.error_resolution_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> runErrorResolutionDataTest( testId, mediaController, callback ) } val launcherTest = TestOptionDetails( 19, context.getString(R.string.launcher_intent_test_title), context.getString(R.string.launcher_intent_test_desc), TestResult.NONE, Test.NO_LOGS, false ) { _, callback, testId -> runLauncherTest( testId, mediaController, mediaAppDetails, context.packageManager, callback ) } val basicTests = arrayOf( playFromSearch, playFromMediaId, playFromUri, playTest, pauseTest, stopTest, skipToNextTest, skipToPrevTest, skipToItemTest, seekToTest ) val commonTests = arrayOf( browseTreeDepthTest, mediaArtworkTest, //TODO FIX contentStyleTest, customActionIconTypeTest, //TODO: FIX supportsSearchTest, initialPlaybackStateTest ) val automotiveTests = arrayOf( browseTreeStructureTest, preferenceTest, errorResolutionDataTest, launcherTest ) var testList = basicTests var testSuites: ArrayList<MediaAppTestSuite> = ArrayList() val basicTestSuite = MediaAppTestSuite("Basic Tests", "Basic media tests.", basicTests) testSuites.add(basicTestSuite) if (mediaAppDetails?.supportsAuto == true || mediaAppDetails?.supportsAutomotive == true) { testList += commonTests val autoTestSuite = MediaAppTestSuite("Auto Tests", "Includes support for android auto tests.", testList) testSuites.add(autoTestSuite) } if (mediaAppDetails?.supportsAutomotive == true) { testList += automotiveTests val automotiveTestSuite = MediaAppTestSuite("Automotive Tests", "Includes support for Android automotive tests.", testList) testSuites.add(automotiveTestSuite) } this.testList = testList.asList() this.testSuites = testSuites } }
apache-2.0
dd875d0c52618c1b529cb10732c9f000
39.061321
100
0.580336
4.851471
false
true
false
false
square/wire
wire-library/wire-gson-support/src/main/java/com/squareup/wire/WireTypeAdapterFactory.kt
1
3847
/* * Copyright 2013 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 com.squareup.wire import com.google.gson.Gson import com.google.gson.TypeAdapter import com.google.gson.TypeAdapterFactory import com.google.gson.reflect.TypeToken import com.squareup.wire.internal.EnumJsonFormatter import com.squareup.wire.internal.createRuntimeMessageAdapter /** * A [TypeAdapterFactory] that allows Wire messages to be serialized and deserialized * using the GSON Json library. To create a [Gson] instance that works with Wire, * use the [com.google.gson.GsonBuilder] interface: * * ``` * Gson gson = new GsonBuilder() * .registerTypeAdapterFactory(new WireTypeAdapterFactory()) * .create(); * ``` * * The resulting [Gson] instance will be able to serialize and deserialize any Wire * [Message] type, including extensions and unknown field values. The JSON encoding is * intended to be compatible with the * [protobuf-java-format](https://code.google.com/p/protobuf-java-format/) * library. Note that version 1.2 of that API has a * [bug](https://code.google.com/p/protobuf-java-format/issues/detail?id=47) * in the way it serializes unknown fields, so we use our own approach for this case. * * In Proto3, if a field is set to its default (or identity) value, it will be omitted in the * JSON-encoded data. Set [writeIdentityValues] to true if you want Wire to always write values, * including default ones. */ class WireTypeAdapterFactory @JvmOverloads constructor( private val typeUrlToAdapter: Map<String, ProtoAdapter<*>> = mapOf(), private val writeIdentityValues: Boolean = false, ) : TypeAdapterFactory { /** * Returns a new WireJsonAdapterFactory that can encode the messages for [adapters] if they're * used with [AnyMessage]. */ fun plus(adapters: List<ProtoAdapter<*>>): WireTypeAdapterFactory { val newMap = typeUrlToAdapter.toMutableMap() for (adapter in adapters) { val key = adapter.typeUrl ?: throw IllegalArgumentException( "recompile ${adapter.type} to use it with WireTypeAdapterFactory" ) newMap[key] = adapter } return WireTypeAdapterFactory(newMap, writeIdentityValues) } /** * Returns a new WireTypeAdapterFactory that can encode the messages for [adapter] if they're * used with [AnyMessage]. */ fun plus(adapter: ProtoAdapter<*>): WireTypeAdapterFactory { return plus(listOf(adapter)) } override fun <T> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? { val rawType = type.rawType return when { rawType == AnyMessage::class.java -> AnyMessageTypeAdapter(gson, typeUrlToAdapter) as TypeAdapter<T> Message::class.java.isAssignableFrom(rawType) -> { val messageAdapter = createRuntimeMessageAdapter<Nothing, Nothing>(rawType as Class<Nothing>, writeIdentityValues) val jsonAdapters = GsonJsonIntegration.jsonAdapters(messageAdapter, gson) MessageTypeAdapter(messageAdapter, jsonAdapters).nullSafe() as TypeAdapter<T> } WireEnum::class.java.isAssignableFrom(rawType) -> { val enumAdapter = RuntimeEnumAdapter.create(rawType as Class<Nothing>) val enumJsonFormatter = EnumJsonFormatter(enumAdapter) EnumTypeAdapter(enumJsonFormatter).nullSafe() as TypeAdapter<T> } else -> null } } }
apache-2.0
28415a1e5be415e5ef731c0598058d55
40.365591
122
0.731739
4.337091
false
false
false
false
hurricup/intellij-community
platform/configuration-store-impl/src/ImportSettingsAction.kt
1
5787
/* * 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.ide.actions import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.PluginManager import com.intellij.ide.startup.StartupActionScriptManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.Messages import com.intellij.openapi.updateSettings.impl.UpdateSettings import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.getParentPath import com.intellij.util.systemIndependentPath import gnu.trove.THashSet import java.io.File import java.io.IOException import java.io.InputStream import java.nio.file.Paths import java.util.zip.ZipException import java.util.zip.ZipInputStream private class ImportSettingsAction : AnAction(), DumbAware { override fun actionPerformed(e: AnActionEvent) { val dataContext = e.dataContext val component = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext) ChooseComponentsToExportDialog.chooseSettingsFile(PathManager.getConfigPath(), component, IdeBundle.message("title.import.file.location"), IdeBundle.message("prompt.choose.import.file.path")) .done { val saveFile = File(it) try { doImport(saveFile) } catch (e1: ZipException) { Messages.showErrorDialog( IdeBundle.message("error.reading.settings.file", presentableFileName(saveFile), e1.message, promptLocationMessage()), IdeBundle.message("title.invalid.file")) } catch (e1: IOException) { Messages.showErrorDialog(IdeBundle.message("error.reading.settings.file.2", presentableFileName(saveFile), e1.message), IdeBundle.message("title.error.reading.file")) } } } private fun doImport(saveFile: File) { if (!saveFile.exists()) { Messages.showErrorDialog(IdeBundle.message("error.cannot.find.file", presentableFileName(saveFile)), IdeBundle.message("title.file.not.found")) return } val relativePaths = getPaths(saveFile.inputStream()) if (!relativePaths.contains(ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER)) { Messages.showErrorDialog( IdeBundle.message("error.file.contains.no.settings.to.import", presentableFileName(saveFile), promptLocationMessage()), IdeBundle.message("title.invalid.file")) return } val configPath = FileUtil.toSystemIndependentName(PathManager.getConfigPath()) val dialog = ChooseComponentsToExportDialog(getExportableComponentsMap(false, true, onlyPaths = relativePaths), false, IdeBundle.message("title.select.components.to.import"), IdeBundle.message("prompt.check.components.to.import")) if (!dialog.showAndGet()) { return } val tempFile = File(PathManager.getPluginTempPath(), saveFile.name) FileUtil.copy(saveFile, tempFile) val filenameFilter = ImportSettingsFilenameFilter(getRelativeNamesToExtract(dialog.exportableComponents)) StartupActionScriptManager.addActionCommand(StartupActionScriptManager.UnzipCommand(tempFile, File(configPath), filenameFilter)) // remove temp file StartupActionScriptManager.addActionCommand(StartupActionScriptManager.DeleteCommand(tempFile)) UpdateSettings.getInstance().forceCheckForUpdateAfterRestart() val key = if (ApplicationManager.getApplication().isRestartCapable) "message.settings.imported.successfully.restart" else "message.settings.imported.successfully" if (Messages.showOkCancelDialog(IdeBundle.message(key, ApplicationNamesInfo.getInstance().productName, ApplicationNamesInfo.getInstance().fullProductName), IdeBundle.message("title.restart.needed"), Messages.getQuestionIcon()) == Messages.OK) { (ApplicationManager.getApplication() as ApplicationEx).restart(true) } } private fun getRelativeNamesToExtract(chosenComponents: Set<ExportableItem>): Set<String> { val result = THashSet<String>() val root = Paths.get(PathManager.getConfigPath()) for ((files) in chosenComponents) { for (exportFile in files) { result.add(root.relativize(exportFile).systemIndependentPath) } } result.add(PluginManager.INSTALLED_TXT) return result } private fun presentableFileName(file: File) = "'" + FileUtil.toSystemDependentName(file.path) + "'" private fun promptLocationMessage() = IdeBundle.message("message.please.ensure.correct.settings") } fun getPaths(input: InputStream): Set<String> { val result = THashSet<String>() val zipIn = ZipInputStream(input) try { while (true) { val entry = zipIn.nextEntry ?: break var path = entry.name result.add(path) while (true) { path = getParentPath(path) ?: break result.add("$path/") } } } finally { zipIn.close() } return result }
apache-2.0
ae5753b83070ff650d38f5ec059c8a4f
39.1875
195
0.745464
4.65942
false
false
false
false
maurocchi/chesslave
backend/src/main/java/io/chesslave/Extensions.kt
2
766
package io.chesslave.extensions // Stdlib fun <T> T?.nullableToList(): List<T> = if (this == null) emptyList() else listOf(this) fun <T> T?.nullableToSet(): Set<T> = if (this == null) emptySet() else setOf(this) inline val <T> T?.defined: Boolean get() = this != null inline val <T> T?.undefined: Boolean get() = this == null fun <T> T?.exists(predicate: (T) -> Boolean): Boolean = if (this != null) predicate(this) else false typealias Predicate<T> = (T) -> Boolean infix fun <T> Predicate<T>.and(predicate: Predicate<T>): Predicate<T> = { t -> this(t) && predicate(t) } infix fun <T> Predicate<T>.or(predicate: Predicate<T>): Predicate<T> = { t -> this(t) || predicate(t) } infix fun String.concat(other: String): String = this + other
gpl-2.0
2b33c458fd9ba402d4762c9721ccdb02
29.68
71
0.640992
3.139344
false
false
false
false
luojilab/DDComponentForAndroid
sharecomponentkotlin/src/main/java/com/luojilab/share/kotlin/ShareMessageActivity.kt
1
1008
package com.luojilab.share.kotlin import android.os.Bundle import com.luojilab.component.basicres.BaseActivity import com.luojilab.componentservice.share.bean.AuthorKt import com.luojilab.router.facade.annotation.Autowired import com.luojilab.router.facade.annotation.RouteNode import kotlinx.android.synthetic.main.kotlin_activity_share.* /** * Created by mrzhang on 2017/12/29. */ @RouteNode(path = "/shareMagazine", desc = "分享杂志页面") class ShareMessageActivity : BaseActivity() { @Autowired(name = "bookName") @JvmField var magazineName: String? = null @Autowired @JvmField var author: AuthorKt? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.kotlin_activity_share) share_title.text = "Magazine" share_tv_tag.setText(magazineName) share_tv_author.setText(author?.name ?: "zmq") share_tv_county.setText(author?.county ?: "China") } }
apache-2.0
aaa9e240761d7888e3d22c51edb11531
27.485714
61
0.722892
3.621818
false
false
false
false
Maccimo/intellij-community
plugins/settings-sync/src/com/intellij/settingsSync/SettingsSnapshotZipSerializer.kt
1
2154
package com.intellij.settingsSync import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.io.FileUtil import com.intellij.util.io.* import java.nio.file.Files import java.nio.file.Path import java.time.Instant import java.util.stream.Collectors import kotlin.io.path.div internal object SettingsSnapshotZipSerializer { private const val METAINFO = ".metainfo" private const val TIMESTAMP = "timestamp" private val LOG = logger<SettingsSnapshotZipSerializer>() fun serializeToZip(snapshot: SettingsSnapshot): Path { val file = FileUtil.createTempFile(SETTINGS_SYNC_SNAPSHOT_ZIP, null) Compressor.Zip(file) .use { zip -> zip.addFile("$METAINFO/$TIMESTAMP", snapshot.metaInfo.dateCreated.toEpochMilli().toString().toByteArray()) for (fileState in snapshot.fileStates) { val content = if (fileState is FileState.Modified) fileState.content else DELETED_FILE_MARKER.toByteArray() zip.addFile(fileState.file, content) } } return file.toPath() } fun extractFromZip(zipFile: Path): SettingsSnapshot { val tempDir = FileUtil.createTempDirectory("settings.sync.updates", null).toPath() Decompressor.Zip(zipFile).extract(tempDir) val metaInfoFolder = tempDir / METAINFO val metaInfo = parseMetaInfo(metaInfoFolder) val fileStates = Files.walk(tempDir) .filter { it.isFile() && !metaInfoFolder.isAncestor(it) } .map { getFileStateFromFileWithDeletedMarker(it, tempDir) } .collect(Collectors.toSet()) return SettingsSnapshot(metaInfo, fileStates) } private fun parseMetaInfo(path: Path): SettingsSnapshot.MetaInfo { try { val timestampFile = path / TIMESTAMP if (timestampFile.exists()) { val timestamp = timestampFile.readText() val date = Instant.ofEpochMilli(timestamp.toLong()) return SettingsSnapshot.MetaInfo(date) } else { LOG.warn("Timestamp file doesn't exist") } } catch (e: Throwable) { LOG.error("Couldn't read .metainfo from $SETTINGS_SYNC_SNAPSHOT_ZIP") } return SettingsSnapshot.MetaInfo(Instant.now()) } }
apache-2.0
53fad0c607537f213cbb78e703644ffb
34.327869
117
0.711235
4.334004
false
false
false
false
Maccimo/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/watcher/VirtualFileUrlWatcher.kt
3
9488
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.ide.impl.legacyBridge.watcher import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.workspaceModel.ide.JpsFileEntitySource import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.getInstance import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.api.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import com.intellij.workspaceModel.storage.bridgeEntities.api.modifyEntity import kotlin.reflect.KClass open class VirtualFileUrlWatcher(val project: Project) { private val virtualFileManager = VirtualFileUrlManager.getInstance(project) internal var isInsideFilePointersUpdate = false private set private val pointers = listOf( // Library roots LibraryRootFileWatcher(), // Library excluded roots EntityVirtualFileUrlWatcher( LibraryEntity::class, LibraryEntity.Builder::class, propertyName = LibraryEntity::excludedRoots.name, modificator = { oldVirtualFileUrl, newVirtualFileUrl -> excludedRoots = excludedRoots - oldVirtualFileUrl excludedRoots = excludedRoots + newVirtualFileUrl } ), // Content root urls EntityVirtualFileUrlWatcher( ContentRootEntity::class, ContentRootEntity.Builder::class, propertyName = ContentRootEntity::url.name, modificator = { _, newVirtualFileUrl -> url = newVirtualFileUrl } ), // Content root excluded urls EntityVirtualFileUrlWatcher( ContentRootEntity::class, ContentRootEntity.Builder::class, propertyName = ContentRootEntity::excludedUrls.name, modificator = { oldVirtualFileUrl, newVirtualFileUrl -> excludedUrls = excludedUrls - oldVirtualFileUrl excludedUrls = excludedUrls + newVirtualFileUrl } ), // Source roots EntityVirtualFileUrlWatcher( SourceRootEntity::class, SourceRootEntity.Builder::class, propertyName = SourceRootEntity::url.name, modificator = { _, newVirtualFileUrl -> url = newVirtualFileUrl } ), // Java module settings entity compiler output EntityVirtualFileUrlWatcher( JavaModuleSettingsEntity::class, JavaModuleSettingsEntity.Builder::class, propertyName = JavaModuleSettingsEntity::compilerOutput.name, modificator = { _, newVirtualFileUrl -> compilerOutput = newVirtualFileUrl } ), // Java module settings entity compiler output for tests EntityVirtualFileUrlWatcher( JavaModuleSettingsEntity::class, JavaModuleSettingsEntity.Builder::class, propertyName = JavaModuleSettingsEntity::compilerOutputForTests.name, modificator = { _, newVirtualFileUrl -> compilerOutputForTests = newVirtualFileUrl } ), EntitySourceFileWatcher(JpsFileEntitySource.ExactFile::class, { it.file.url }, { source, file -> source.copy(file = file) }), EntitySourceFileWatcher(JpsFileEntitySource.FileInDirectory::class, { it.directory.url }, { source, file -> source.copy(directory = file) }) ) fun onVfsChange(oldUrl: String, newUrl: String) { try { isInsideFilePointersUpdate = true val entityWithVirtualFileUrl = mutableListOf<EntityWithVirtualFileUrl>() WorkspaceModel.getInstance(project).updateProjectModel { diff -> val oldFileUrl = virtualFileManager.fromUrl(oldUrl) calculateAffectedEntities(diff, oldFileUrl, entityWithVirtualFileUrl) oldFileUrl.subTreeFileUrls.map { fileUrl -> calculateAffectedEntities(diff, fileUrl, entityWithVirtualFileUrl) } val result = entityWithVirtualFileUrl.filter { shouldUpdateThisEntity(it.entity) }.toList() pointers.forEach { it.onVfsChange(oldUrl, newUrl, result, virtualFileManager, diff) } } } finally { isInsideFilePointersUpdate = false } } // A workaround to have an opportunity to skip some entities from being updated (for now it's only for Rider to avoid update ContentRoots) open fun shouldUpdateThisEntity(entity: WorkspaceEntity): Boolean { return true } companion object { @JvmStatic fun getInstance(project: Project): VirtualFileUrlWatcher = project.getComponent(VirtualFileUrlWatcher::class.java) internal fun calculateAffectedEntities(storage: EntityStorage, virtualFileUrl: VirtualFileUrl, aggregator: MutableList<EntityWithVirtualFileUrl>) { storage.getVirtualFileUrlIndex().findEntitiesByUrl(virtualFileUrl).forEach { aggregator.add(EntityWithVirtualFileUrl(it.first, virtualFileUrl, it.second)) } } } } data class EntityWithVirtualFileUrl(val entity: WorkspaceEntity, val virtualFileUrl: VirtualFileUrl, val propertyName: String) private interface LegacyFileWatcher { fun onVfsChange(oldUrl: String, newUrl: String, entitiesWithVFU: List<EntityWithVirtualFileUrl>, virtualFileManager: VirtualFileUrlManager, diff: MutableEntityStorage) } private class EntitySourceFileWatcher<T : EntitySource>( val entitySource: KClass<T>, val containerToUrl: (T) -> String, val createNewSource: (T, VirtualFileUrl) -> T ) : LegacyFileWatcher { override fun onVfsChange(oldUrl: String, newUrl: String, entitiesWithVFU: List<EntityWithVirtualFileUrl>, virtualFileManager: VirtualFileUrlManager, diff: MutableEntityStorage) { val entities = diff.entitiesBySource { it::class == entitySource } for ((entitySource, mapOfEntities) in entities) { @Suppress("UNCHECKED_CAST") val urlFromContainer = containerToUrl(entitySource as T) if (!FileUtil.startsWith(urlFromContainer, oldUrl)) continue val newVfurl = virtualFileManager.fromUrl(newUrl + urlFromContainer.substring(oldUrl.length)) val newEntitySource = createNewSource(entitySource, newVfurl) mapOfEntities.values.flatten().forEach { diff.modifyEntity(ModifiableWorkspaceEntity::class.java, it) { this.entitySource = newEntitySource } } } } } /** * Legacy file pointer that can track and update urls stored in a [WorkspaceEntity]. * [entityClass] - class of a [WorkspaceEntity] that contains an url being tracked * [modifiableEntityClass] - class of modifiable entity of [entityClass] * [propertyName] - name of the field which contains [VirtualFileUrl] * [modificator] - function for modifying an entity * There 2 functions are created for better convenience. You should use only one from them. */ private class EntityVirtualFileUrlWatcher<E : WorkspaceEntity, M : ModifiableWorkspaceEntity<E>>( val entityClass: KClass<E>, val modifiableEntityClass: KClass<M>, val propertyName: String, val modificator: M.(VirtualFileUrl, VirtualFileUrl) -> Unit ) : LegacyFileWatcher { override fun onVfsChange(oldUrl: String, newUrl: String, entitiesWithVFU: List<EntityWithVirtualFileUrl>, virtualFileManager: VirtualFileUrlManager, diff: MutableEntityStorage) { entitiesWithVFU.filter { entityClass.isInstance(it.entity) && it.propertyName == propertyName }.forEach { entityWithVFU -> val existingVirtualFileUrl = entityWithVFU.virtualFileUrl val savedUrl = existingVirtualFileUrl.url val newTrackedUrl = newUrl + savedUrl.substring(oldUrl.length) val newContainer = virtualFileManager.fromUrl(newTrackedUrl) @Suppress("UNCHECKED_CAST") entityWithVFU.entity as E diff.modifyEntity(modifiableEntityClass.java, entityWithVFU.entity) { this.modificator(existingVirtualFileUrl, newContainer) } } } } /** * It's responsible for updating complex case than [VirtualFileUrl] contains not in the entity itself but in internal data class. * This is about LibraryEntity -> roots (LibraryRoot) -> url (VirtualFileUrl). */ private class LibraryRootFileWatcher : LegacyFileWatcher { private val propertyName = LibraryEntity::roots.name override fun onVfsChange(oldUrl: String, newUrl: String, entitiesWithVFU: List<EntityWithVirtualFileUrl>, virtualFileManager: VirtualFileUrlManager, diff: MutableEntityStorage) { entitiesWithVFU.filter { LibraryEntity::class.isInstance(it.entity) && it.propertyName == propertyName }.forEach { entityWithVFU -> val oldVFU = entityWithVFU.virtualFileUrl val newVFU = virtualFileManager.fromUrl(newUrl + oldVFU.url.substring(oldUrl.length)) entityWithVFU.entity as LibraryEntity val oldLibraryRoots = diff.resolve(entityWithVFU.entity.persistentId)?.roots?.filter { it.url == oldVFU } ?: error("Incorrect state of the VFU index") oldLibraryRoots.forEach { oldLibraryRoot -> val newLibraryRoot = LibraryRoot(newVFU, oldLibraryRoot.type, oldLibraryRoot.inclusionOptions) diff.modifyEntity(entityWithVFU.entity) { roots = roots - oldLibraryRoot roots = roots + newLibraryRoot } } } } }
apache-2.0
28643a23edcdecf5524deb21ad0d7709
45.287805
140
0.717433
5.571345
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/mark/MotionGotoFileMarkLineAction.kt
1
2039
/* * 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 com.maddyhome.idea.vim.action.motion.mark import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.MotionType import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.Motion import com.maddyhome.idea.vim.handler.MotionActionHandler import com.maddyhome.idea.vim.handler.toMotionOrError import java.util.* class MotionGotoFileMarkLineAction : MotionActionHandler.ForEachCaret() { override val motionType: MotionType = MotionType.LINE_WISE override val argumentType: Argument.Type = Argument.Type.CHARACTER override val flags: EnumSet<CommandFlags> = EnumSet.of(CommandFlags.FLAG_SAVE_JUMP) override fun getOffset( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Motion { if (argument == null) return Motion.Error val mark = argument.character return injector.motion.moveCaretToFileMark(editor, mark, false).toMotionOrError() } } class MotionGotoFileMarkLineNoSaveJumpAction : MotionActionHandler.ForEachCaret() { override val motionType: MotionType = MotionType.LINE_WISE override val argumentType: Argument.Type = Argument.Type.CHARACTER override fun getOffset( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Motion { if (argument == null) return Motion.Error val mark = argument.character return injector.motion.moveCaretToFileMark(editor, mark, true).toMotionOrError() } }
mit
1e4d4ad8ed956153219515824b972b2f
31.887097
85
0.777342
4.21281
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/fragment/impl/DefaultVerticalTabBar.kt
1
2116
package org.hexworks.zircon.internal.fragment.impl import org.hexworks.zircon.api.ComponentDecorations.margin import org.hexworks.zircon.api.Components import org.hexworks.zircon.api.component.AttachedComponent import org.hexworks.zircon.api.component.Component import org.hexworks.zircon.api.component.Panel import org.hexworks.zircon.api.component.VBox import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.dsl.component.buildHbox import org.hexworks.zircon.api.dsl.component.panel import org.hexworks.zircon.api.dsl.component.vbox import org.hexworks.zircon.api.fragment.Tab import org.hexworks.zircon.api.fragment.TabBar import org.hexworks.zircon.internal.component.renderer.NoOpComponentRenderer class DefaultVerticalTabBar internal constructor( size: Size, tabWidth: Int, defaultSelected: String, tabs: List<TabData> ) : TabBar { private lateinit var tabBar: VBox private lateinit var content: Panel private var currentContent: AttachedComponent? = null private val group = Components.radioButtonGroup().build() private val lookup = tabs.associate { (tab, content) -> group.addComponent(tab.tabButton) tab.key to TabData(tab, content) } override val root: Component = buildHbox { preferredSize = size componentRenderer = NoOpComponentRenderer() tabBar = vbox { preferredSize = Size.create(tabWidth, size.height) decoration = margin(1, 0) componentRenderer = NoOpComponentRenderer() childrenToAdd = lookup.map { it.value.tab.root } } content = panel { preferredSize = size.withRelativeWidth(-tabWidth) } group.selectedButtonProperty.onChange { (_, newValue) -> newValue?.let { button -> currentContent?.detach()?.moveTo(Position.defaultPosition()) currentContent = content.addComponent(lookup.getValue(button.key).content) } } lookup.getValue(defaultSelected).tab.isSelected = true } }
apache-2.0
b4188c1f8dedb5ea96c931bae959bb92
34.864407
90
0.712665
4.408333
false
false
false
false
duncte123/SkyBot
src/main/kotlin/ml/duncte123/skybot/commands/mod/SlowModeCommand.kt
1
2986
/* * Skybot, a multipurpose discord bot * Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32" * * 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 <https://www.gnu.org/licenses/>. */ package ml.duncte123.skybot.commands.mod import me.duncte123.botcommons.messaging.MessageUtils.sendMsg import me.duncte123.botcommons.messaging.MessageUtils.sendSuccess import me.duncte123.durationparser.DurationParser import ml.duncte123.skybot.commands.guild.mod.ModBaseCommand import ml.duncte123.skybot.objects.command.CommandContext import ml.duncte123.skybot.utils.AirUtils import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.TextChannel class SlowModeCommand : ModBaseCommand() { init { this.name = "slowmode" this.aliases = arrayOf("sm") this.help = "Sets the slowmode in the current channel" this.usage = "<seconds (0-${TextChannel.MAX_SLOWMODE})/off>" this.userPermissions = arrayOf(Permission.MESSAGE_MANAGE) this.botPermissions = arrayOf(Permission.MANAGE_CHANNEL) } override fun execute(ctx: CommandContext) { if (ctx.args.isEmpty()) { val currentMode = ctx.channel.slowmode val currentModeString = if (currentMode == 0) "disabled" else "$currentMode seconds" sendMsg(ctx, "Current slowmode is `$currentModeString`") return } val delay = ctx.args[0] if (delay == "off") { ctx.channel.manager.setSlowmode(0).reason("Requested by ${ctx.author.asTag}").queue() sendSuccess(ctx.message) return } val intDelay = if (!AirUtils.isInt(delay)) { val parser = DurationParser.parse(delay) if (parser.isEmpty) { sendMsg(ctx, "Provided argument is not an integer or duration") return } parser.get().seconds } else { delay.toLong() } if (intDelay < 0 || intDelay > TextChannel.MAX_SLOWMODE) { sendMsg(ctx, "$intDelay is not valid, a valid delay is a number in the range 0-${TextChannel.MAX_SLOWMODE} (21600 is 6 hours in seconds)") return } ctx.channel.manager.setSlowmode(intDelay.toInt()).reason("Requested by ${ctx.author.asTag}").queue() sendSuccess(ctx.message) } }
agpl-3.0
dd6636b68025d0091c83a28c55d30936
36.797468
150
0.668453
4.147222
false
false
false
false
JStege1206/AdventOfCode
aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day14.kt
1
2106
package nl.jstege.adventofcode.aoc2015.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.extractValues import nl.jstege.adventofcode.aoccommon.utils.extensions.transformTo /** * * @author Jelle Stege */ class Day14 : Day(title = "Reindeer Olympics") { private companion object Configuration { private const val TRAVEL_TIME = 2503 private const val INPUT_PATTERN_STRING = """\w+ can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds\.""" private val INPUT_REGEX = INPUT_PATTERN_STRING.toRegex() private const val SPEED_INDEX = 1 private const val TRAVEL_TIME_INDEX = 2 private const val REST_TIME_INDEX = 3 private val PARAM_INDICES = intArrayOf(SPEED_INDEX, TRAVEL_TIME_INDEX, REST_TIME_INDEX) } override fun first(input: Sequence<String>) = input .parse() .asSequence() .map { it.travel(TRAVEL_TIME).distanceTravelled } .max()!! override fun second(input: Sequence<String>) = (1..TRAVEL_TIME) .transformTo(input.parse().toList()) { rs, i -> rs.onEach { it.travel(i) } .filter { r -> r.distanceTravelled == rs.map { it.distanceTravelled }.max() } .forEach { it.score++ } } .asSequence() .map { it.score } .max()!! private fun Sequence<String>.parse() = this .map { it.extractValues(INPUT_REGEX, *PARAM_INDICES) } .map { (speed, travelTime, restTime) -> Reindeer(speed.toInt(), travelTime.toInt(), restTime.toInt()) } private data class Reindeer(val speed: Int, val travelTime: Int, val restTime: Int) { var distanceTravelled = 0 var score = 0 fun travel(currentTime: Int): Reindeer { distanceTravelled = speed * (currentTime / (travelTime + restTime) * travelTime + (Math.min(currentTime % (travelTime + restTime), travelTime))) return this } } }
mit
54b61862664aab8940d92900c4fa23e0
34.694915
98
0.601614
4.003802
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/mysite/MySiteCardAndItemDecoration.kt
1
1594
package org.wordpress.android.ui.mysite import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ItemDecoration class MySiteCardAndItemDecoration( private val horizontalMargin: Int, private val verticalMargin: Int ) : ItemDecoration() { override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { val position = parent.getChildAdapterPosition(view) if (position < 0) return when (parent.adapter?.getItemViewType(position)) { MySiteCardAndItem.Type.QUICK_LINK_RIBBON.ordinal -> { outRect.top = verticalMargin } MySiteCardAndItem.Type.INFO_ITEM.ordinal -> { outRect.top = verticalMargin outRect.left = horizontalMargin outRect.right = horizontalMargin } MySiteCardAndItem.Type.LIST_ITEM.ordinal, MySiteCardAndItem.Type.CATEGORY_HEADER_ITEM.ordinal -> { outRect.left = horizontalMargin outRect.right = horizontalMargin } MySiteCardAndItem.Type.SITE_INFO_CARD.ordinal, MySiteCardAndItem.Type.QUICK_START_DYNAMIC_CARD.ordinal -> Unit else -> { outRect.bottom = verticalMargin outRect.top = verticalMargin outRect.left = horizontalMargin outRect.right = horizontalMargin } } } }
gpl-2.0
b494baf505d68a2aa388f87f75d681d1
35.227273
75
0.621706
5.243421
false
false
false
false
ingokegel/intellij-community
platform/build-scripts/dev-server/src/IdeBuilder.kt
4
9364
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment") package org.jetbrains.intellij.build.devServer import com.intellij.util.PathUtilRt import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.BuildOptions import org.jetbrains.intellij.build.IdeaProjectLoaderUtil import org.jetbrains.intellij.build.ProductProperties import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.intellij.build.impl.* import org.jetbrains.intellij.build.impl.projectStructureMapping.LibraryFileEntry import org.jetbrains.intellij.build.impl.projectStructureMapping.ModuleOutputEntry import org.jetbrains.jps.model.artifact.JpsArtifactService import org.jetbrains.jps.model.library.JpsOrderRootType import org.jetbrains.jps.util.JpsPathUtil import java.net.URLClassLoader import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.TimeUnit internal const val UNMODIFIED_MARK_FILE_NAME = ".unmodified" class IdeBuilder(val pluginBuilder: PluginBuilder, homePath: Path, runDir: Path, outDir: Path, moduleNameToPlugin: Map<String, BuildItem>) { private class ModuleChangeInfo(@JvmField val moduleName: String, @JvmField var checkFile: Path, @JvmField var plugin: BuildItem) private val moduleChanges = moduleNameToPlugin.entries.map { val checkFile = outDir.resolve(it.key).resolve(UNMODIFIED_MARK_FILE_NAME) ModuleChangeInfo(moduleName = it.key, checkFile = checkFile, plugin = it.value) } init { Files.writeString(runDir.resolve("libClassPath.txt"), createLibClassPath(pluginBuilder.buildContext, homePath)) } fun checkChanged() { LOG.info("Checking changes...") var changedModules = 0 for (item in moduleChanges) { if (!Files.exists(item.checkFile)) { pluginBuilder.addDirtyPluginDir(item.plugin, item.moduleName) changedModules++ } } LOG.info("$changedModules changed modules") } } internal fun initialBuild(productConfiguration: ProductConfiguration, homePath: Path, outDir: Path): IdeBuilder { val productProperties = URLClassLoader.newInstance(productConfiguration.modules.map { outDir.resolve(it).toUri().toURL() }.toTypedArray()) .loadClass(productConfiguration.className) .getConstructor(Path::class.java).newInstance(homePath) as ProductProperties val pluginLayoutsFromProductProperties = productProperties.productLayout.pluginLayouts val bundledMainModuleNames = getBundledMainModuleNames(productProperties) val platformPrefix = productProperties.platformPrefix ?: "idea" val runDir = createRunDirForProduct(homePath, platformPrefix) val buildContext = BuildContextImpl.createContext( communityHome = getCommunityHomePath(homePath), projectHome = homePath, productProperties = productProperties, options = createBuildOptions(runDir), ) val pluginsDir = runDir.resolve("plugins") val mainModuleToNonTrivialPlugin = HashMap<String, BuildItem>(bundledMainModuleNames.size) for (plugin in pluginLayoutsFromProductProperties) { if (bundledMainModuleNames.contains(plugin.mainModule)) { val item = BuildItem(pluginsDir.resolve(getActualPluginDirectoryName(plugin, buildContext)), plugin) mainModuleToNonTrivialPlugin.put(plugin.mainModule, item) } } val moduleNameToPlugin = HashMap<String, BuildItem>() val pluginLayouts = bundledMainModuleNames.mapNotNull { mainModuleName -> // by intention, we don't use buildContext.findModule as getPluginsByModules does - module name must match // (old module names are not supported) var item = mainModuleToNonTrivialPlugin.get(mainModuleName) if (item == null) { val pluginLayout = PluginLayout.simplePlugin(mainModuleName) item = BuildItem(dir = pluginsDir.resolve(pluginLayout.directoryName), layout = pluginLayout) } else { for (entry in item.layout.getJarToIncludedModuleNames()) { if (!entry.key.contains('/')) { for (name in entry.value) { moduleNameToPlugin.put(name, item) } item.moduleNames.addAll(entry.value) } } } item.moduleNames.add(mainModuleName) moduleNameToPlugin.put(mainModuleName, item) item } val artifactOutDir = homePath.resolve("out/classes/artifacts").toString() for (artifact in JpsArtifactService.getInstance().getArtifacts(buildContext.project)) { artifact.outputPath = "$artifactOutDir/${PathUtilRt.getFileName(artifact.outputPath)}" } // initial building val start = System.currentTimeMillis() val pluginBuilder = PluginBuilder(buildContext, outDir) pluginBuilder.initialBuild(plugins = pluginLayouts) LOG.info("Initial full build of ${pluginLayouts.size} plugins in ${TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - start)}s") return IdeBuilder(pluginBuilder = pluginBuilder, homePath = homePath, runDir = runDir, outDir = outDir, moduleNameToPlugin = moduleNameToPlugin) } private fun createLibClassPath(context: BuildContext, homePath: Path): String { val platformLayout = createPlatformLayout(emptySet(), context) val isPackagedLib = System.getProperty("dev.server.pack.lib") == "true" val projectStructureMapping = processLibDirectoryLayout(moduleOutputPatcher = ModuleOutputPatcher(), platform = platformLayout, context = context, copyFiles = isPackagedLib).fork().join() // for some reasons maybe duplicated paths - use set val classPath = LinkedHashSet<String>() if (isPackagedLib) { projectStructureMapping.mapTo(classPath) { it.path.toString() } } else { for (entry in projectStructureMapping) { when (entry) { is ModuleOutputEntry -> { if (isPackagedLib) { classPath.add(entry.path.toString()) } else { classPath.add(context.getModuleOutputDir(context.findRequiredModule(entry.moduleName)).toString()) } } is LibraryFileEntry -> { if (isPackagedLib) { classPath.add(entry.path.toString()) } else { classPath.add(entry.libraryFile.toString()) } } else -> throw UnsupportedOperationException("Entry $entry is not supported") } } for (libName in platformLayout.projectLibrariesToUnpack.values()) { val library = context.project.libraryCollection.findLibrary(libName) ?: throw IllegalStateException("Cannot find library $libName") library.getRootUrls(JpsOrderRootType.COMPILED).mapTo(classPath) { JpsPathUtil.urlToPath(it) } } } val projectLibDir = homePath.resolve("lib") @Suppress("SpellCheckingInspection") val extraJarNames = listOf("ideaLicenseDecoder.jar", "ls-client-api.jar", "y.jar", "ysvg.jar") for (extraJarName in extraJarNames) { val extraJar = projectLibDir.resolve(extraJarName) if (Files.exists(extraJar)) { classPath.add(extraJar.toAbsolutePath().toString()) } } return classPath.joinToString(separator = "\n") } private fun getBundledMainModuleNames(productProperties: ProductProperties): Set<String> { val bundledPlugins = LinkedHashSet(productProperties.productLayout.bundledPluginModules) getAdditionalModules()?.let { println("Additional modules: ${it.joinToString()}") bundledPlugins.addAll(it) } bundledPlugins.removeAll(skippedPluginModules) return bundledPlugins } fun getAdditionalModules(): Sequence<String>? { return (System.getProperty("additional.modules") ?: System.getProperty("additional.plugins") ?: return null) .splitToSequence(',') .map(String::trim) .filter { it.isNotEmpty() } } private fun createRunDirForProduct(homePath: Path, platformPrefix: String): Path { // if symlinked to ram disk, use real path for performance reasons and avoid any issues in ant/other code var rootDir = homePath.resolve("out/dev-run") if (Files.exists(rootDir)) { // toRealPath must be called only on existing file rootDir = rootDir.toRealPath() } val runDir = rootDir.resolve(platformPrefix) // on start delete everything to avoid stale data clearDirContent(runDir) Files.createDirectories(runDir) return runDir } private fun getCommunityHomePath(homePath: Path): BuildDependenciesCommunityRoot { val communityDotIdea = homePath.resolve("community/.idea") return BuildDependenciesCommunityRoot(if (Files.isDirectory(communityDotIdea)) communityDotIdea.parent else homePath) } private fun createBuildOptions(runDir: Path): BuildOptions { val buildOptions = BuildOptions() buildOptions.useCompiledClassesFromProjectOutput = true buildOptions.targetOs = BuildOptions.OS_NONE buildOptions.cleanOutputFolder = false buildOptions.skipDependencySetup = true buildOptions.outputRootPath = runDir.toString() buildOptions.buildStepsToSkip.add(BuildOptions.PREBUILD_SHARED_INDEXES) return buildOptions }
apache-2.0
044c5e3f182ba6d316b935f4bd985da2
40.622222
140
0.720205
4.775115
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/erg/record/ErgPurseRecord.kt
1
3516
/* * ErgPurseRecord.kt * * Copyright 2015-2019 Michael Farrell <[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 au.id.micolous.metrodroid.transit.erg.record import au.id.micolous.metrodroid.multi.Parcelable import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.util.ImmutableByteArray /** * Represents a "purse" type record. * * These are simple transactions where there is either a credit or debit from the purse value. * * https://github.com/micolous/metrodroid/wiki/ERG-MFC#purse-records */ @Parcelize class ErgPurseRecord(val agency: Int, val day: Int, val minute: Int, val isCredit: Boolean, val transactionValue: Int, val isTrip: Boolean) : ErgRecord, Parcelable { override fun toString(): String { return "[ErgPurseRecord: agencyID=0x${agency.toString(16)}, day=$day, minute=$minute, isCredit=$isCredit, isTransfer=$isTrip, txnValue=$transactionValue]" } companion object { fun recordFromBytes(block: ImmutableByteArray): ErgRecord? { //if (input[0] != 0x02) throw new AssertionError("PurseRecord input[0] != 0x02"); val isCredit: Boolean val isTrip: Boolean when (block[3].toInt()) { 0x09, /* manly */ 0x0D /* chc */ -> { isCredit = false isTrip = false } 0x08 /* chc, manly */ -> { isCredit = true isTrip = false } 0x02 /* chc */ -> { // For every non-paid trip, CHC puts in a 0x02 // For every paid trip, CHC puts a 0x0d (purse debit) and 0x02 isCredit = false isTrip = true } else -> // May also be null or empty record... return null } val record = ErgPurseRecord( // Multiple agencyID IDs seen on chc cards -- might represent different operating companies. agency = block.byteArrayToInt(1, 2), day = block.getBitsFromBuffer(32, 20), minute = block.getBitsFromBuffer(52, 12), transactionValue = block.byteArrayToInt(8, 4), isCredit = isCredit, isTrip = isTrip ) if (record.day < 0) throw AssertionError("Day < 0") if (record.minute > 1440) throw AssertionError("Minute > 1440 (${record.minute})") if (record.minute < 0) throw AssertionError("Minute < 0 (${record.minute})") //if (record.mTransactionValue < 0) throw new AssertionError("Value < 0"); return record } } }
gpl-3.0
512d0a18e9b30705603656cc3e9a9cec
38.505618
162
0.57537
4.450633
false
false
false
false
anitaa1990/DeviceInfo-Sample
deviceinfo/src/main/java/com/an/deviceinfo/ads/AdvertisingIdClient.kt
1
4022
package com.an.deviceinfo.ads import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.content.pm.PackageManager import android.os.IBinder import android.os.IInterface import android.os.Looper import android.os.Parcel import android.os.RemoteException import android.util.Log import java.io.IOException import java.util.concurrent.LinkedBlockingQueue object AdvertisingIdClient { class AdIdInfo internal constructor(val id: String, val isLimitAdTrackingEnabled: Boolean) @Throws(Exception::class) fun getAdvertisingIdInfo(context: Context): AdIdInfo { if (Looper.myLooper() == Looper.getMainLooper()) throw IllegalStateException("Cannot be called from the main thread") try { val pm = context.packageManager pm.getPackageInfo("com.android.vending", 0) } catch (e: Exception) { throw e } val connection = AdvertisingConnection() val intent = Intent("com.google.android.gms.ads.identifier.service.START") intent.`package` = "com.google.android.gms" if (context.bindService(intent, connection, Context.BIND_AUTO_CREATE)) { try { val adInterface = AdvertisingInterface(connection.binder) val adIdInfo = AdIdInfo(adInterface.id, adInterface.isLimitAdTrackingEnabled(true)) Log.d("*****ADINFO***", adInterface.id) return adIdInfo } catch (exception: Exception) { throw exception } finally { context.unbindService(connection) } } throw IOException("Google Play connection failed") } private class AdvertisingConnection : ServiceConnection { internal var retrieved = false private val queue = LinkedBlockingQueue<IBinder>(1) val binder: IBinder @Throws(InterruptedException::class) get() { if (this.retrieved) throw IllegalStateException() this.retrieved = true return this.queue.take() as IBinder } override fun onServiceConnected(name: ComponentName, service: IBinder) { try { this.queue.put(service) } catch (localInterruptedException: InterruptedException) { } } override fun onServiceDisconnected(name: ComponentName) {} } private class AdvertisingInterface(private val binder: IBinder) : IInterface { val id: String @Throws(RemoteException::class) get() { val data = Parcel.obtain() val reply = Parcel.obtain() val id: String try { data.writeInterfaceToken("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService") binder.transact(1, data, reply, 0) reply.readException() id = reply.readString() } finally { reply.recycle() data.recycle() } return id } override fun asBinder(): IBinder { return binder } @Throws(RemoteException::class) fun isLimitAdTrackingEnabled(paramBoolean: Boolean): Boolean { val data = Parcel.obtain() val reply = Parcel.obtain() val limitAdTracking: Boolean try { data.writeInterfaceToken("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService") data.writeInt(if (paramBoolean) 1 else 0) binder.transact(2, data, reply, 0) reply.readException() limitAdTracking = 0 != reply.readInt() } finally { reply.recycle() data.recycle() } return limitAdTracking } } }
apache-2.0
33132da397ef463c32657c7774ece723
33.681034
125
0.593486
5.091139
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt
3
46915
// 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.util.psi.patternMatching import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.builtins.isExtensionFunctionType import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange.Empty import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiUnificationResult import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiUnificationResult.* import org.jetbrains.kotlin.idea.base.psi.unifier.toRange import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.refactoring.introduce.ExtractableSubstringInfo import org.jetbrains.kotlin.idea.refactoring.introduce.extractableSubstringInfo import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.lexer.KtToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorEquivalenceForOverrides import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind import org.jetbrains.kotlin.resolve.calls.util.getCall import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.isSafeCall import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.Receiver import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.error.ErrorUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.expressions.DoubleColonLHS import org.jetbrains.kotlin.types.expressions.OperatorConventions import java.util.* class UnifierParameter( val descriptor: DeclarationDescriptor, val expectedType: KotlinType? ) class KotlinPsiUnifier( parameters: Collection<UnifierParameter> = Collections.emptySet(), val allowWeakMatches: Boolean = false ) { companion object { val DEFAULT = KotlinPsiUnifier() } private inner class Context(val originalTarget: KotlinPsiRange, val originalPattern: KotlinPsiRange) { val patternContext: BindingContext = originalPattern.getBindingContext() val targetContext: BindingContext = originalTarget.getBindingContext() val substitution = HashMap<UnifierParameter, KtElement>() val declarationPatternsToTargets = MultiMap<DeclarationDescriptor, DeclarationDescriptor>() val weakMatches = HashMap<KtElement, KtElement>() var checkEquivalence: Boolean = false var targetSubstringInfo: ExtractableSubstringInfo? = null private fun KotlinPsiRange.getBindingContext(): BindingContext { val element = elements.firstOrNull() as? KtElement if ((element?.containingFile as? KtFile)?.doNotAnalyze != null) return BindingContext.EMPTY return element?.analyze() ?: BindingContext.EMPTY } private fun matchDescriptors(first: DeclarationDescriptor?, second: DeclarationDescriptor?): Boolean { if (DescriptorEquivalenceForOverrides.areEquivalent(first, second, allowCopiesFromTheSameDeclaration = true)) return true if (second in declarationPatternsToTargets[first] || first in declarationPatternsToTargets[second]) return true if (first == null || second == null) return false val firstPsi = DescriptorToSourceUtils.descriptorToDeclaration(first) as? KtDeclaration val secondPsi = DescriptorToSourceUtils.descriptorToDeclaration(second) as? KtDeclaration if (firstPsi == null || secondPsi == null) return false if (firstPsi == secondPsi) return true if ((firstPsi in originalTarget && secondPsi in originalPattern) || (secondPsi in originalTarget && firstPsi in originalPattern)) { return matchDeclarations(firstPsi, secondPsi, first, second) == true } return false } private fun matchReceivers(first: Receiver?, second: Receiver?): Boolean { return when { first is ExpressionReceiver && second is ExpressionReceiver -> doUnify(first.expression, second.expression) first is ImplicitReceiver && second is ImplicitReceiver -> matchDescriptors(first.declarationDescriptor, second.declarationDescriptor) else -> first == second } } private fun matchCalls(first: Call, second: Call): Boolean { return matchReceivers(first.explicitReceiver, second.explicitReceiver) && matchReceivers(first.dispatchReceiver, second.dispatchReceiver) } private fun matchArguments(first: ValueArgument, second: ValueArgument): Boolean { return when { first.isExternal() != second.isExternal() -> false (first.getSpreadElement() == null) != (second.getSpreadElement() == null) -> false else -> doUnify(first.getArgumentExpression(), second.getArgumentExpression()) } } private fun matchResolvedCalls(first: ResolvedCall<*>, second: ResolvedCall<*>): Boolean? { fun checkSpecialOperations(): Boolean { val op1 = (first.call.calleeExpression as? KtSimpleNameExpression)?.getReferencedNameElementType() val op2 = (second.call.calleeExpression as? KtSimpleNameExpression)?.getReferencedNameElementType() return when { op1 == op2 -> true op1 == KtTokens.NOT_IN || op2 == KtTokens.NOT_IN -> false op1 == KtTokens.EXCLEQ || op2 == KtTokens.EXCLEQ -> false op1 in OperatorConventions.COMPARISON_OPERATIONS || op2 in OperatorConventions.COMPARISON_OPERATIONS -> false else -> true } } fun checkArguments(): Boolean? { val firstArguments = first.resultingDescriptor?.valueParameters?.map { first.valueArguments[it] } ?: emptyList() val secondArguments = second.resultingDescriptor?.valueParameters?.map { second.valueArguments[it] } ?: emptyList() if (firstArguments.size != secondArguments.size) return false if (first.call.valueArguments.size != firstArguments.size || second.call.valueArguments.size != secondArguments.size) return null val mappedArguments = firstArguments.asSequence().zip(secondArguments.asSequence()) return mappedArguments.fold(true) { status, (firstArgument, secondArgument) -> status && when { firstArgument == secondArgument -> true firstArgument == null || secondArgument == null -> false else -> { val mappedInnerArguments = firstArgument.arguments.asSequence().zip(secondArgument.arguments.asSequence()) mappedInnerArguments.fold(true) { statusForArgument, pair -> statusForArgument && matchArguments(pair.first, pair.second) } } } } } fun checkImplicitReceiver(implicitCall: ResolvedCall<*>, explicitCall: ResolvedCall<*>): Boolean { val (implicitReceiver, explicitReceiver) = when (explicitCall.explicitReceiverKind) { ExplicitReceiverKind.EXTENSION_RECEIVER -> (implicitCall.extensionReceiver as? ImplicitReceiver) to (explicitCall.extensionReceiver as? ExpressionReceiver) ExplicitReceiverKind.DISPATCH_RECEIVER -> (implicitCall.dispatchReceiver as? ImplicitReceiver) to (explicitCall.dispatchReceiver as? ExpressionReceiver) else -> null to null } val thisExpression = explicitReceiver?.expression as? KtThisExpression if (implicitReceiver == null || thisExpression == null) return false return matchDescriptors( implicitReceiver.declarationDescriptor, thisExpression.getAdjustedResolvedCall()?.candidateDescriptor?.containingDeclaration ) } fun checkReceivers(): Boolean { return when { first.explicitReceiverKind == second.explicitReceiverKind -> { if (!matchReceivers(first.extensionReceiver, second.extensionReceiver)) { false } else { first.explicitReceiverKind == ExplicitReceiverKind.BOTH_RECEIVERS || matchReceivers(first.dispatchReceiver, second.dispatchReceiver) } } first.explicitReceiverKind == ExplicitReceiverKind.NO_EXPLICIT_RECEIVER -> checkImplicitReceiver(first, second) second.explicitReceiverKind == ExplicitReceiverKind.NO_EXPLICIT_RECEIVER -> checkImplicitReceiver(second, first) else -> false } } fun checkTypeArguments(): Boolean? { val firstTypeArguments = first.typeArguments.toList() val secondTypeArguments = second.typeArguments.toList() if (firstTypeArguments.size != secondTypeArguments.size) return false for ((firstTypeArgument, secondTypeArgument) in (firstTypeArguments.zip(secondTypeArguments))) { if (!matchDescriptors(firstTypeArgument.first, secondTypeArgument.first)) return false val status = matchTypes(firstTypeArgument.second, secondTypeArgument.second) if (status != true) return status } return true } return when { !checkSpecialOperations() -> false !matchDescriptors(first.candidateDescriptor, second.candidateDescriptor) -> false !checkReceivers() -> false first.call.isSafeCall() != second.call.isSafeCall() -> false else -> { val status = checkTypeArguments() if (status != true) status else checkArguments() } } } private val KtElement.bindingContext: BindingContext get() = if (this in originalPattern) patternContext else targetContext private fun KtElement.getAdjustedResolvedCall(): ResolvedCall<*>? { val rc = if (this is KtArrayAccessExpression) { bindingContext[BindingContext.INDEXED_LVALUE_GET, this] } else { getResolvedCall(bindingContext)?.let { when { it !is VariableAsFunctionResolvedCall -> it this is KtSimpleNameExpression -> it.variableCall else -> it.functionCall } } } return when { rc == null || ErrorUtils.isError(rc.candidateDescriptor) -> null else -> rc } } private fun matchCalls(first: KtElement, second: KtElement): Boolean? { if (first.shouldIgnoreResolvedCall() || second.shouldIgnoreResolvedCall()) return null val firstResolvedCall = first.getAdjustedResolvedCall() val secondResolvedCall = second.getAdjustedResolvedCall() return when { firstResolvedCall != null && secondResolvedCall != null -> matchResolvedCalls(firstResolvedCall, secondResolvedCall) firstResolvedCall == null && secondResolvedCall == null -> { val firstCall = first.getCall(first.bindingContext) val secondCall = second.getCall(second.bindingContext) when { firstCall != null && secondCall != null -> if (matchCalls(firstCall, secondCall)) null else false else -> if (firstCall == null && secondCall == null) null else false } } else -> false } } private fun matchTypes( firstType: KotlinType?, secondType: KotlinType?, firstTypeReference: KtTypeReference? = null, secondTypeReference: KtTypeReference? = null ): Boolean? { if (firstType != null && secondType != null) { val firstUnwrappedType = firstType.unwrap() val secondUnwrappedType = secondType.unwrap() if (firstUnwrappedType !== firstType || secondUnwrappedType !== secondType) return matchTypes( firstUnwrappedType, secondUnwrappedType, firstTypeReference, secondTypeReference ) if (firstType.isError || secondType.isError) return null if (firstType is AbbreviatedType != secondType is AbbreviatedType) return false if (firstType.isExtensionFunctionType != secondType.isExtensionFunctionType) return false if (TypeUtils.equalTypes(firstType, secondType)) return true if (firstType.isMarkedNullable != secondType.isMarkedNullable) return false if (!matchDescriptors( firstType.constructor.declarationDescriptor, secondType.constructor.declarationDescriptor ) ) return false val firstTypeArguments = firstType.arguments val secondTypeArguments = secondType.arguments if (firstTypeArguments.size != secondTypeArguments.size) return false for ((index, firstTypeArgument) in firstTypeArguments.withIndex()) { val secondTypeArgument = secondTypeArguments[index] if (!matchTypeArguments(index, firstTypeArgument, secondTypeArgument, firstTypeReference, secondTypeReference)) { return false } } return true } return if (firstType == null && secondType == null) null else false } private fun matchTypeArguments( argIndex: Int, firstArgument: TypeProjection, secondArgument: TypeProjection, firstTypeReference: KtTypeReference?, secondTypeReference: KtTypeReference? ): Boolean { val firstArgumentReference = firstTypeReference?.typeElement?.typeArgumentsAsTypes?.getOrNull(argIndex) val secondArgumentReference = secondTypeReference?.typeElement?.typeArgumentsAsTypes?.getOrNull(argIndex) if (firstArgument.projectionKind != secondArgument.projectionKind) return false val firstArgumentType = firstArgument.type val secondArgumentType = secondArgument.type // Substitution attempt using either arg1, or arg2 as a pattern type. Falls back to exact matching if substitution is not possible val status = if (!checkEquivalence && firstTypeReference != null && secondTypeReference != null) { val firstTypeDeclaration = firstArgumentType.constructor.declarationDescriptor?.source?.getPsi() val secondTypeDeclaration = secondArgumentType.constructor.declarationDescriptor?.source?.getPsi() descriptorToParameter[firstTypeDeclaration]?.let { substitute(it, secondArgumentReference) } ?: descriptorToParameter[secondTypeDeclaration]?.let { substitute(it, firstArgumentReference) } ?: matchTypes(firstArgumentType, secondArgumentType, firstArgumentReference, secondArgumentReference) } else matchTypes(firstArgumentType, secondArgumentType, firstArgumentReference, secondArgumentReference) return status == true } private fun matchTypes(firstTypes: Collection<KotlinType>, secondTypes: Collection<KotlinType>): Boolean { fun sortTypes(types: Collection<KotlinType>) = types.sortedBy { DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(it) } if (firstTypes.size != secondTypes.size) return false return (sortTypes(firstTypes).zip(sortTypes(secondTypes))) .all { (first, second) -> matchTypes(first, second) == true } } private fun KtElement.shouldIgnoreResolvedCall(): Boolean { return when (this) { is KtConstantExpression -> true is KtOperationReferenceExpression -> getReferencedNameElementType() == KtTokens.EXCLEXCL is KtIfExpression -> true is KtWhenExpression -> true is KtUnaryExpression -> when (operationReference.getReferencedNameElementType()) { KtTokens.EXCLEXCL, KtTokens.PLUSPLUS, KtTokens.MINUSMINUS -> true else -> false } is KtBinaryExpression -> operationReference.getReferencedNameElementType() == KtTokens.ELVIS is KtThisExpression -> true is KtSimpleNameExpression -> getStrictParentOfType<KtTypeElement>() != null else -> false } } private fun KtBinaryExpression.matchComplexAssignmentWithSimple(expression: KtBinaryExpression): Boolean { return when (doUnify(left, expression.left)) { false -> false else -> expression.right?.let { matchCalls(this, it) } ?: false } } private fun KtBinaryExpression.matchAssignment(element: KtElement): Boolean? { val operationType = operationReference.getReferencedNameElementType() as KtToken if (operationType == KtTokens.EQ) { if (element.shouldIgnoreResolvedCall()) return false if (KtPsiUtil.isAssignment(element) && !KtPsiUtil.isOrdinaryAssignment(element)) { return (element as KtBinaryExpression).matchComplexAssignmentWithSimple(this) } val lhs = left?.unwrap() if (lhs !is KtArrayAccessExpression) return null val setResolvedCall = bindingContext[BindingContext.INDEXED_LVALUE_SET, lhs] val resolvedCallToMatch = element.getAdjustedResolvedCall() return when { setResolvedCall == null || resolvedCallToMatch == null -> null else -> matchResolvedCalls(setResolvedCall, resolvedCallToMatch) } } val assignResolvedCall = getAdjustedResolvedCall() ?: return false val operationName = OperatorConventions.getNameForOperationSymbol(operationType) if (assignResolvedCall.resultingDescriptor?.name == operationName) return matchCalls(this, element) return if (KtPsiUtil.isAssignment(element)) null else false } private fun matchLabelTargets(first: KtLabelReferenceExpression, second: KtLabelReferenceExpression): Boolean { val firstTarget = first.bindingContext[BindingContext.LABEL_TARGET, first] val secondTarget = second.bindingContext[BindingContext.LABEL_TARGET, second] return firstTarget == secondTarget } private fun PsiElement.isIncrement(): Boolean { val parent = this.parent return parent is KtUnaryExpression && this == parent.operationReference && ((parent.operationToken as KtToken) in OperatorConventions.INCREMENT_OPERATIONS) } private fun KtCallableReferenceExpression.hasExpressionReceiver(): Boolean { return bindingContext[BindingContext.DOUBLE_COLON_LHS, receiverExpression] is DoubleColonLHS.Expression } private fun matchCallableReferences(first: KtCallableReferenceExpression, second: KtCallableReferenceExpression): Boolean? { if (first.hasExpressionReceiver() || second.hasExpressionReceiver()) return null val firstDescriptor = first.bindingContext[BindingContext.REFERENCE_TARGET, first.callableReference] val secondDescriptor = second.bindingContext[BindingContext.REFERENCE_TARGET, second.callableReference] return matchDescriptors(firstDescriptor, secondDescriptor) } private fun matchThisExpressions(e1: KtThisExpression, e2: KtThisExpression): Boolean { val d1 = e1.bindingContext[BindingContext.REFERENCE_TARGET, e1.instanceReference] val d2 = e2.bindingContext[BindingContext.REFERENCE_TARGET, e2.instanceReference] return matchDescriptors(d1, d2) } private fun matchDestructuringDeclarations(e1: KtDestructuringDeclaration, e2: KtDestructuringDeclaration): Boolean { val entries1 = e1.entries val entries2 = e2.entries if (entries1.size != entries2.size) return false return entries1.zip(entries2).all { p -> val (entry1, entry2) = p val rc1 = entry1.bindingContext[BindingContext.COMPONENT_RESOLVED_CALL, entry1] val rc2 = entry2.bindingContext[BindingContext.COMPONENT_RESOLVED_CALL, entry2] when { rc1 == null && rc2 == null -> true rc1 != null && rc2 != null -> matchResolvedCalls(rc1, rc2) == true else -> false } } } fun matchReceiverParameters(firstReceiver: ReceiverParameterDescriptor?, secondReceiver: ReceiverParameterDescriptor?): Boolean { val matchedReceivers = when { firstReceiver == null && secondReceiver == null -> true matchDescriptors(firstReceiver, secondReceiver) -> true firstReceiver != null && secondReceiver != null -> matchTypes(firstReceiver.type, secondReceiver.type) == true else -> false } if (matchedReceivers && firstReceiver != null) { declarationPatternsToTargets.putValue(firstReceiver, secondReceiver) } return matchedReceivers } private fun matchCallables( first: KtDeclaration, second: KtDeclaration, firstDescriptor: CallableDescriptor, secondDescriptor: CallableDescriptor ): Boolean { if (firstDescriptor is VariableDescriptor && firstDescriptor.isVar != (secondDescriptor as VariableDescriptor).isVar) { return false } if (!matchNames(first, second, firstDescriptor, secondDescriptor)) { return false } fun needToCompareReturnTypes(): Boolean { if (first !is KtCallableDeclaration) return true return first.typeReference != null || (second as KtCallableDeclaration).typeReference != null } if (needToCompareReturnTypes()) { val type1 = firstDescriptor.returnType val type2 = secondDescriptor.returnType if (type1 != type2 && (type1 == null || type2 == null || type1.isError || type2.isError || matchTypes( type1, type2 ) != true) ) { return false } } if (!matchReceiverParameters(firstDescriptor.extensionReceiverParameter, secondDescriptor.extensionReceiverParameter)) { return false } if (!matchReceiverParameters(firstDescriptor.dispatchReceiverParameter, secondDescriptor.dispatchReceiverParameter)) { return false } val params1 = firstDescriptor.valueParameters val params2 = secondDescriptor.valueParameters val zippedParams = params1.zip(params2) val parametersMatch = (params1.size == params2.size) && zippedParams.all { matchTypes(it.first.type, it.second.type) == true } if (!parametersMatch) return false zippedParams.forEach { declarationPatternsToTargets.putValue(it.first, it.second) } return doUnify( (first as? KtTypeParameterListOwner)?.typeParameters?.toRange() ?: Empty, (second as? KtTypeParameterListOwner)?.typeParameters?.toRange() ?: Empty ) && when (first) { is KtDeclarationWithBody -> doUnify(first.bodyExpression, (second as KtDeclarationWithBody).bodyExpression) is KtDeclarationWithInitializer -> doUnify(first.initializer, (second as KtDeclarationWithInitializer).initializer) is KtParameter -> doUnify(first.defaultValue, (second as KtParameter).defaultValue) else -> false } } private fun KtDeclaration.isNameRelevant(): Boolean { if (this is KtParameter && hasValOrVar()) return true val parent = parent return parent is KtClassBody || parent is KtFile } private fun matchNames( first: KtDeclaration, second: KtDeclaration, firstDescriptor: DeclarationDescriptor, secondDescriptor: DeclarationDescriptor ): Boolean { return (!first.isNameRelevant() && !second.isNameRelevant()) || firstDescriptor.name == secondDescriptor.name } private fun matchClasses( first: KtClassOrObject, second: KtClassOrObject, firstDescriptor: ClassDescriptor, secondDescriptor: ClassDescriptor ): Boolean { class OrderInfo<out T>( val orderSensitive: List<T>, val orderInsensitive: List<T> ) fun getMemberOrderInfo(cls: KtClassOrObject): OrderInfo<KtDeclaration> { val (orderInsensitive, orderSensitive) = (cls.body?.declarations ?: Collections.emptyList()).partition { it is KtClassOrObject || it is KtFunction } return OrderInfo(orderSensitive, orderInsensitive) } fun getDelegationOrderInfo(cls: KtClassOrObject): OrderInfo<KtSuperTypeListEntry> { val (orderInsensitive, orderSensitive) = cls.superTypeListEntries.partition { it is KtSuperTypeEntry } return OrderInfo(orderSensitive, orderInsensitive) } fun resolveAndSortDeclarationsByDescriptor(declarations: List<KtDeclaration>): List<Pair<KtDeclaration, DeclarationDescriptor?>> { return declarations.map { it to it.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] } .sortedBy { it.second?.let { descriptor -> IdeDescriptorRenderers.SOURCE_CODE.render(descriptor) } ?: "" } } fun sortDeclarationsByElementType(declarations: List<KtDeclaration>): List<KtDeclaration> { return declarations.sortedBy { it.node?.elementType?.index ?: -1 } } if (firstDescriptor.kind != secondDescriptor.kind) return false if (!matchNames(first, second, firstDescriptor, secondDescriptor)) return false declarationPatternsToTargets.putValue(firstDescriptor.thisAsReceiverParameter, secondDescriptor.thisAsReceiverParameter) val firstConstructor = firstDescriptor.unsubstitutedPrimaryConstructor val secondConstructor = secondDescriptor.unsubstitutedPrimaryConstructor if (firstConstructor != null && secondConstructor != null) { declarationPatternsToTargets.putValue(firstConstructor, secondConstructor) } val firstOrderInfo = getDelegationOrderInfo(first) val secondOrderInfo = getDelegationOrderInfo(second) if (firstOrderInfo.orderInsensitive.size != secondOrderInfo.orderInsensitive.size) return false outer@ for (firstSpecifier in firstOrderInfo.orderInsensitive) { for (secondSpecifier in secondOrderInfo.orderInsensitive) { if (doUnify(firstSpecifier, secondSpecifier)) continue@outer } return false } val firstParameters = (first as? KtClass)?.getPrimaryConstructorParameterList() val secondParameters = (second as? KtClass)?.getPrimaryConstructorParameterList() val status = doUnify(firstParameters, secondParameters) && doUnify((first as? KtClass)?.typeParameterList, (second as? KtClass)?.typeParameterList) && doUnify(firstOrderInfo.orderSensitive.toRange(), secondOrderInfo.orderSensitive.toRange()) if (!status) return false val firstMemberInfo = getMemberOrderInfo(first) val secondMemberInfo = getMemberOrderInfo(second) val firstSortedMembers = resolveAndSortDeclarationsByDescriptor(firstMemberInfo.orderInsensitive) val secondSortedMembers = resolveAndSortDeclarationsByDescriptor(secondMemberInfo.orderInsensitive) if ((firstSortedMembers.size != secondSortedMembers.size)) return false for ((index, firstSortedMember) in firstSortedMembers.withIndex()) { val (firstMember, firstMemberDescriptor) = firstSortedMember val (secondMember, secondMemberDescriptor) = secondSortedMembers[index] val memberResult = matchDeclarations(firstMember, secondMember, firstMemberDescriptor, secondMemberDescriptor) ?: doUnify(firstMember, secondMember) if (!memberResult) { return false } } return doUnify( sortDeclarationsByElementType(firstMemberInfo.orderSensitive).toRange(), sortDeclarationsByElementType(secondMemberInfo.orderSensitive).toRange() ) } private fun matchTypeParameters(first: TypeParameterDescriptor, second: TypeParameterDescriptor): Boolean { if (first.variance != second.variance) return false if (!matchTypes(first.upperBounds, second.upperBounds)) return false return true } private fun KtDeclaration.matchDeclarations(element: PsiElement): Boolean? { if (element !is KtDeclaration) return false val firstDescriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, this] val secondDescriptor = element.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, element] return matchDeclarations(this, element, firstDescriptor, secondDescriptor) } private fun matchDeclarations( decl1: KtDeclaration, decl2: KtDeclaration, desc1: DeclarationDescriptor?, desc2: DeclarationDescriptor? ): Boolean? { if (decl1::class.java != decl2::class.java) return false if (desc1 == null || desc2 == null) { return if (decl1 is KtParameter && decl2 is KtParameter && decl1.getStrictParentOfType<KtTypeElement>() != null && decl2.getStrictParentOfType<KtTypeElement>() != null ) null else false } if (ErrorUtils.isError(desc1) || ErrorUtils.isError(desc2)) return false if (desc1::class.java != desc2::class.java) return false declarationPatternsToTargets.putValue(desc1, desc2) val status = when (decl1) { is KtDeclarationWithBody, is KtDeclarationWithInitializer, is KtParameter -> matchCallables(decl1, decl2, desc1 as CallableDescriptor, desc2 as CallableDescriptor) is KtClassOrObject -> matchClasses(decl1, decl2 as KtClassOrObject, desc1 as ClassDescriptor, desc2 as ClassDescriptor) is KtTypeParameter -> matchTypeParameters(desc1 as TypeParameterDescriptor, desc2 as TypeParameterDescriptor) else -> null } if (status == false) { declarationPatternsToTargets.remove(desc1, desc2) } return status } private fun matchResolvedInfo(first: PsiElement, second: PsiElement): Boolean? { fun KtTypeReference.getType(): KotlinType? { return (bindingContext[BindingContext.ABBREVIATED_TYPE, this] ?: bindingContext[BindingContext.TYPE, this]) ?.takeUnless { it.isError } } return when { first !is KtElement || second !is KtElement -> null first is KtDestructuringDeclaration && second is KtDestructuringDeclaration -> if (matchDestructuringDeclarations(first, second)) null else false first is KtAnonymousInitializer && second is KtAnonymousInitializer -> null first is KtDeclaration -> first.matchDeclarations(second) second is KtDeclaration -> second.matchDeclarations(first) first is KtTypeElement && second is KtTypeElement && first.parent is KtTypeReference && second.parent is KtTypeReference -> matchResolvedInfo(first.parent, second.parent) first is KtTypeReference && second is KtTypeReference -> matchTypes(first.getType(), second.getType(), first, second) KtPsiUtil.isAssignment(first) -> (first as KtBinaryExpression).matchAssignment(second) KtPsiUtil.isAssignment(second) -> (second as KtBinaryExpression).matchAssignment(first) first is KtLabelReferenceExpression && second is KtLabelReferenceExpression -> matchLabelTargets(first, second) first.isIncrement() != second.isIncrement() -> false first is KtCallableReferenceExpression && second is KtCallableReferenceExpression -> matchCallableReferences(first, second) first is KtThisExpression && second is KtThisExpression -> matchThisExpressions(first, second) else -> matchCalls(first, second) } } private fun PsiElement.checkType(parameter: UnifierParameter): Boolean { val expectedType = parameter.expectedType ?: return true val targetElementType = (this as? KtExpression)?.let { it.bindingContext.getType(it) } return targetElementType != null && KotlinTypeChecker.DEFAULT.isSubtypeOf(targetElementType, expectedType) } private fun doUnifyStringTemplateFragments(target: KtStringTemplateExpression, pattern: ExtractableSubstringInfo): Boolean { val prefixLength = pattern.prefix.length val suffixLength = pattern.suffix.length val targetEntries = target.entries val patternEntries = pattern.entries.toList() for ((index, targetEntry) in targetEntries.withIndex()) { if (index + patternEntries.size > targetEntries.size) return false val targetEntryText = targetEntry.text if (pattern.startEntry == pattern.endEntry && (prefixLength > 0 || suffixLength > 0)) { if (targetEntry !is KtLiteralStringTemplateEntry) continue val patternText = with(pattern.startEntry.text) { substring(prefixLength, length - suffixLength) } val i = targetEntryText.indexOf(patternText) if (i < 0) continue val targetPrefix = targetEntryText.substring(0, i) val targetSuffix = targetEntryText.substring(i + patternText.length) targetSubstringInfo = ExtractableSubstringInfo(targetEntry, targetEntry, targetPrefix, targetSuffix, pattern.type) return true } val matchStartByText = pattern.startEntry is KtLiteralStringTemplateEntry val matchEndByText = pattern.endEntry is KtLiteralStringTemplateEntry val targetPrefix = if (matchStartByText) { if (targetEntry !is KtLiteralStringTemplateEntry) continue val patternText = pattern.startEntry.text.substring(prefixLength) if (!targetEntryText.endsWith(patternText)) continue targetEntryText.substring(0, targetEntryText.length - patternText.length) } else "" val lastTargetEntry = targetEntries[index + patternEntries.lastIndex] val targetSuffix = if (matchEndByText) { if (lastTargetEntry !is KtLiteralStringTemplateEntry) continue val patternText = with(pattern.endEntry.text) { substring(0, length - suffixLength) } val lastTargetEntryText = lastTargetEntry.text if (!lastTargetEntryText.startsWith(patternText)) continue lastTargetEntryText.substring(patternText.length) } else "" val fromIndex = if (matchStartByText) 1 else 0 val toIndex = if (matchEndByText) patternEntries.lastIndex - 1 else patternEntries.lastIndex val status = (fromIndex..toIndex).fold(true) { status, patternEntryIndex -> val targetEntryToUnify = targetEntries[index + patternEntryIndex] val patternEntryToUnify = patternEntries[patternEntryIndex] status && doUnify(targetEntryToUnify, patternEntryToUnify) } if (!status) continue targetSubstringInfo = ExtractableSubstringInfo(targetEntry, lastTargetEntry, targetPrefix, targetSuffix, pattern.type) return status } return false } fun doUnify(target: KotlinPsiRange, pattern: KotlinPsiRange): Boolean { (pattern.elements.singleOrNull() as? KtExpression)?.extractableSubstringInfo?.let { val targetTemplate = target.elements.singleOrNull() as? KtStringTemplateExpression ?: return false return doUnifyStringTemplateFragments(targetTemplate, it) } val targetElements = target.elements val patternElements = pattern.elements if (targetElements.size != patternElements.size) return false return (targetElements.asSequence().zip(patternElements.asSequence())).fold(true) { status, (first, second) -> status && doUnify(first, second) } } private fun ASTNode.getChildrenRange(): KotlinPsiRange = getChildren(null).mapNotNull { it.psi }.toRange() private fun PsiElement.unwrapWeakly(): KtElement? { return when { this is KtReturnExpression -> returnedExpression this is KtProperty -> initializer KtPsiUtil.isOrdinaryAssignment(this) -> (this as KtBinaryExpression).right this is KtExpression && this !is KtDeclaration -> this else -> null } } private fun doUnifyWeakly(targetElement: KtElement, patternElement: KtElement): Boolean { if (!allowWeakMatches) return false val targetElementUnwrapped = targetElement.unwrapWeakly() val patternElementUnwrapped = patternElement.unwrapWeakly() if (targetElementUnwrapped == null || patternElementUnwrapped == null) return false if (targetElementUnwrapped == targetElement && patternElementUnwrapped == patternElement) return false val status = doUnify(targetElementUnwrapped, patternElementUnwrapped) if (status && allowWeakMatches) { weakMatches[patternElement] = targetElement } return status } private fun substitute(parameter: UnifierParameter, targetElement: PsiElement?): Boolean { return when (val existingArgument = substitution[parameter]) { null -> { substitution[parameter] = targetElement as KtElement true } else -> { checkEquivalence = true val status = doUnify(existingArgument, targetElement) checkEquivalence = false status } } } fun doUnify( targetElement: PsiElement?, patternElement: PsiElement? ): Boolean { val targetElementUnwrapped = targetElement?.unwrap() val patternElementUnwrapped = patternElement?.unwrap() if (targetElementUnwrapped == patternElementUnwrapped) return true if (targetElementUnwrapped == null || patternElementUnwrapped == null) return false if (!checkEquivalence && targetElementUnwrapped !is KtBlockExpression) { val referencedPatternDescriptor = when (patternElementUnwrapped) { is KtReferenceExpression -> { if (targetElementUnwrapped !is KtExpression) return false patternElementUnwrapped.bindingContext[BindingContext.REFERENCE_TARGET, patternElementUnwrapped] } is KtUserType -> { if (targetElementUnwrapped !is KtUserType) return false patternElementUnwrapped.bindingContext[BindingContext.REFERENCE_TARGET, patternElementUnwrapped.referenceExpression] } else -> null } val referencedPatternDeclaration = (referencedPatternDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() val parameter = descriptorToParameter[referencedPatternDeclaration] if (referencedPatternDeclaration != null && parameter != null) { if (targetElementUnwrapped is KtExpression) { if (!targetElementUnwrapped.checkType(parameter)) return false } return substitute(parameter, targetElementUnwrapped) } } val targetNode = targetElementUnwrapped.node val patternNode = patternElementUnwrapped.node if (targetNode == null || patternNode == null) return false val resolvedStatus = matchResolvedInfo(targetElementUnwrapped, patternElementUnwrapped) if (resolvedStatus == true) return resolvedStatus if (targetElementUnwrapped is KtElement && patternElementUnwrapped is KtElement) { val weakStatus = doUnifyWeakly(targetElementUnwrapped, patternElementUnwrapped) if (weakStatus) return true } if (targetNode.elementType != patternNode.elementType) return false if (resolvedStatus != null) return resolvedStatus val targetChildren = targetNode.getChildrenRange() val patternChildren = patternNode.getChildrenRange() if (patternChildren.isEmpty && targetChildren.isEmpty) { return targetElementUnwrapped.unquotedText() == patternElementUnwrapped.unquotedText() } return doUnify(targetChildren, patternChildren) } } private val descriptorToParameter = parameters.associateBy { (it.descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() } private fun PsiElement.unwrap(): PsiElement? = when (this) { is KtExpression -> KtPsiUtil.deparenthesize(this) is KtStringTemplateEntryWithExpression -> KtPsiUtil.deparenthesize(expression) else -> this } private fun PsiElement.unquotedText(): String { val text = text ?: "" return if (this is LeafPsiElement) KtPsiUtil.unquoteIdentifier(text) else text } fun unify(target: KotlinPsiRange, pattern: KotlinPsiRange): KotlinPsiUnificationResult { return with(Context(target, pattern)) { val status = doUnify(target, pattern) when { substitution.size != descriptorToParameter.size -> Failure status -> { val targetRange = targetSubstringInfo?.createExpression()?.toRange() ?: target if (weakMatches.isEmpty()) { StrictSuccess(targetRange, substitution) } else { WeakSuccess(targetRange, substitution, weakMatches) } } else -> Failure } } } fun unify(targetElement: PsiElement?, patternElement: PsiElement?): KotlinPsiUnificationResult = unify(targetElement.toRange(), patternElement.toRange()) } fun PsiElement?.matches(e: PsiElement?): Boolean = KotlinPsiUnifier.DEFAULT.unify(this, e).isMatched fun KotlinPsiRange.matches(r: KotlinPsiRange): Boolean = KotlinPsiUnifier.DEFAULT.unify(this, r).isMatched fun KotlinPsiRange.match(scope: PsiElement, unifier: KotlinPsiUnifier): List<Success<UnifierParameter>> { return match(scope) { target, pattern -> @Suppress("UNCHECKED_CAST") unifier.unify(target, pattern) as? Success<UnifierParameter> } }
apache-2.0
563294d399b9274e775f970f7ba6df68
47.97286
158
0.627049
5.946134
false
false
false
false
lnr0626/cfn-templates
plugin/src/main/kotlin/com/lloydramey/cfn/gradle/internal/GradleExtensions.kt
1
1664
/* * Copyright 2017 Lloyd Ramey <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lloydramey.cfn.gradle.internal import org.gradle.api.file.FileCollection import org.gradle.api.internal.HasConvention import org.gradle.api.plugins.Convention import org.gradle.api.plugins.ExtensionAware import org.gradle.api.plugins.PluginManager import org.gradle.api.tasks.compile.AbstractCompile import kotlin.reflect.KClass internal fun PluginManager.apply(clazz: KClass<*>) = apply(clazz.java) internal fun <T : Any> Convention.getPlugin(clazz: KClass<T>) = getPlugin(clazz.java) internal inline fun <reified T : Any> Any.addConvention(name: String, plugin: T) { (this as HasConvention).convention.plugins[name] = plugin } internal inline fun <reified T : Any> Any.addExtension(name: String, extension: T) = (this as ExtensionAware).extensions.add(name, extension) internal fun Any.getConvention(name: String): Any? = (this as HasConvention).convention.plugins[name] internal fun AbstractCompile.mapClasspath(fn: () -> FileCollection) { conventionMapping.map("classpath", fn) } annotation class OpenForGradle
apache-2.0
9df38244fc707ed96f6969c23c20881a
36.840909
85
0.766226
3.878788
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/NullabilityAnnotationsConversion.kt
2
2048
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k.conversions import org.jetbrains.kotlin.j2k.ast.Nullability import org.jetbrains.kotlin.load.java.NOT_NULL_ANNOTATIONS import org.jetbrains.kotlin.load.java.NULLABLE_ANNOTATIONS import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.updateNullability class NullabilityAnnotationsConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKAnnotationListOwner) return recurse(element) val annotationsToRemove = mutableListOf<JKAnnotation>() for (annotation in element.annotationList.annotations) { val nullability = annotation.annotationNullability() ?: continue when (element) { is JKVariable -> element.type is JKMethod -> element.returnType is JKTypeElement -> element else -> null }?.let { typeElement -> annotationsToRemove += annotation typeElement.type = typeElement.type.updateNullability(nullability) } } element.annotationList.annotations -= annotationsToRemove return recurse(element) } private fun JKAnnotation.annotationNullability(): Nullability? = when (classSymbol.fqName) { in nullableAnnotationsFqNames -> Nullability.Nullable in notNullAnnotationsFqNames -> Nullability.NotNull else -> null } companion object { private val nullableAnnotationsFqNames = NULLABLE_ANNOTATIONS.map { it.asString() }.toSet() private val notNullAnnotationsFqNames = NOT_NULL_ANNOTATIONS.map { it.asString() }.toSet() } }
apache-2.0
eac0a173c858fb105880b21f34470355
40.816327
120
0.697266
5.171717
false
false
false
false
GunoH/intellij-community
plugins/kotlin/preferences/src/org/jetbrains/kotlin/idea/configuration/ExperimentalFeatures.kt
6
3047
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.configuration import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.util.registry.Registry import com.intellij.ui.components.JBCheckBox import org.jdesktop.swingx.VerticalLayout import org.jetbrains.kotlin.idea.base.plugin.KotlinBasePluginBundle import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import javax.swing.JCheckBox import javax.swing.JPanel object ExperimentalFeatures { val NewJ2k = RegistryExperimentalFeature( title = KotlinBasePluginBundle.message("configuration.feature.text.new.java.to.kotlin.converter"), registryKey = "kotlin.experimental.new.j2k", enabledByDefault = true ) val allFeatures: List<ExperimentalFeature> = listOf( NewJ2k, ) + ExperimentalFeature.EP_NAME.extensionList } abstract class ExperimentalFeature { abstract val title: String abstract var isEnabled: Boolean open fun shouldBeShown(): Boolean = true open fun onFeatureStatusChanged(enabled: Boolean) {} companion object { internal var EP_NAME = ExtensionPointName<ExperimentalFeature>("org.jetbrains.kotlin.experimentalFeature") } } open class RegistryExperimentalFeature( override val title: String, private val registryKey: String, private val enabledByDefault: Boolean ) : ExperimentalFeature() { final override var isEnabled get() = Registry.`is`(registryKey, enabledByDefault) set(value) { Registry.get(registryKey).setValue(value) } } class ExperimentalFeaturesPanel : JPanel(VerticalLayout(5)) { private val featuresWithCheckboxes = ExperimentalFeatures.allFeatures.map { feature -> FeatureWithCheckbox( feature, JBCheckBox(feature.title, feature.isEnabled) ) } init { featuresWithCheckboxes.forEach { (feature, checkBox) -> if (feature.shouldBeShown()) { add(checkBox) } } } private data class FeatureWithCheckbox( val feature: ExperimentalFeature, val checkbox: JCheckBox ) fun isModified() = featuresWithCheckboxes.any { (feature, checkBox) -> feature.isEnabled != checkBox.isSelected } fun applySelectedChanges() { featuresWithCheckboxes.forEach { (feature, checkBox) -> if (feature.isEnabled != checkBox.isSelected) { feature.isEnabled = checkBox.isSelected feature.onFeatureStatusChanged(checkBox.isSelected) } } } companion object { fun shouldBeShown(): Boolean { val kotlinVersion = KotlinPluginLayout.standaloneCompilerVersion return kotlinVersion.isPreRelease && kotlinVersion.kind !is IdeKotlinVersion.Kind.ReleaseCandidate } } }
apache-2.0
fc8c7b7746e0970f0e16e25c171b223d
32.855556
120
0.703971
4.867412
false
false
false
false
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUField.kt
4
3110
// 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.uast.kotlin import com.intellij.psi.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.uast.UElement import org.jetbrains.uast.UField import org.jetbrains.uast.UFieldEx import org.jetbrains.uast.internal.acceptList import org.jetbrains.uast.visitor.UastVisitor @ApiStatus.Internal open class KotlinUField( psi: PsiField, override val sourcePsi: KtElement?, givenParent: UElement? ) : AbstractKotlinUVariable(givenParent), UFieldEx, PsiField by psi { override fun getSourceElement() = sourcePsi ?: this override val javaPsi = unwrap<UField, PsiField>(psi) override val psi = javaPsi override fun getType(): PsiType { return delegateExpression?.getExpressionType() ?: javaPsi.type } override fun acceptsAnnotationTarget(target: AnnotationUseSiteTarget?): Boolean = target == AnnotationUseSiteTarget.FIELD || target == AnnotationUseSiteTarget.PROPERTY_DELEGATE_FIELD || (sourcePsi is KtProperty) && (target == null || target == AnnotationUseSiteTarget.PROPERTY) override fun getInitializer(): PsiExpression? { return super<AbstractKotlinUVariable>.getInitializer() } override fun getOriginalElement(): PsiElement? { return super<AbstractKotlinUVariable>.getOriginalElement() } override fun getNameIdentifier(): PsiIdentifier { return super.getNameIdentifier() } override fun getContainingFile(): PsiFile { return super.getContainingFile() } override fun isPhysical(): Boolean { return true } override fun accept(visitor: UastVisitor) { if (visitor.visitField(this)) return uAnnotations.acceptList(visitor) uastInitializer?.accept(visitor) delegateExpression?.accept(visitor) visitor.afterVisitField(this) } override fun asRenderString(): String = buildString { if (uAnnotations.isNotEmpty()) { uAnnotations.joinTo(this, separator = " ", postfix = " ") { it.asRenderString() } } append(javaPsi.renderModifiers()) // NB: use of (potentially delegated) `type`, instead of `javaPsiInternal.type`, is the only major difference. append("var ").append(javaPsi.name).append(": ").append(type.getCanonicalText(false)) uastInitializer?.let { initializer -> append(" = " + initializer.asRenderString()) } } } // copy of internal org.jetbrains.uast.InternalUastUtilsKt.renderModifiers // original function should be used instead as soon as becomes public private fun PsiModifierListOwner.renderModifiers(): String { val modifiers = PsiModifier.MODIFIERS.filter { hasModifierProperty(it) }.joinToString(" ") return if (modifiers.isEmpty()) "" else modifiers + " " }
apache-2.0
09d39522f6ee0a0f5240ba7d3edc07a1
37.875
158
0.717363
4.960128
false
false
false
false
GunoH/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/firstStep/BuildSystemTypeSettingComponent.kt
2
5333
// 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.tools.projectWizard.wizard.ui.firstStep import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionButtonLook import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.ActionButtonWithText import com.intellij.openapi.project.DumbAware import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult import org.jetbrains.kotlin.tools.projectWizard.core.entity.isSpecificError import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.DropDownSettingType import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType import org.jetbrains.kotlin.tools.projectWizard.wizard.OnUserSettingChangeStatisticsLogger import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.TitleComponentAlignment import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.IdeaBasedComponentValidator import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.SettingComponent import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.ValidationIndicator import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.awt.Dimension import java.awt.Insets import javax.swing.JComponent class BuildSystemTypeSettingComponent( context: Context ) : SettingComponent<BuildSystemType, DropDownSettingType<BuildSystemType>>( BuildSystemPlugin.type.reference, context ) { private val toolbar by lazy(LazyThreadSafetyMode.NONE) { val buildSystemTypes = read { setting.type.values.filter { setting.type.filter(this, reference, it) } } val actionGroup = DefaultActionGroup(buildSystemTypes.map(::BuildSystemTypeAction)) val buildSystemToolbar = BuildSystemToolbar(ActionPlaces.NEW_PROJECT_WIZARD, actionGroup, true) buildSystemToolbar.also { it.targetComponent = null } } override val alignment: TitleComponentAlignment get() = TitleComponentAlignment.AlignFormTopWithPadding(6) override val component: JComponent by lazy(LazyThreadSafetyMode.NONE) { toolbar } override val validationIndicator: ValidationIndicator = IdeaBasedComponentValidator(this, component) override fun navigateTo(error: ValidationResult.ValidationError) { if (validationIndicator.validationState.isSpecificError(error)) { component.requestFocus() } } private fun validateBuildSystem(buildSystem: BuildSystemType) = read { setting.validator.validate(this, buildSystem) } private inner class BuildSystemTypeAction( val buildSystemType: BuildSystemType ) : ToggleAction(buildSystemType.text, null, null), DumbAware { override fun isSelected(e: AnActionEvent): Boolean = value == buildSystemType override fun setSelected(e: AnActionEvent, state: Boolean) { if (state) { value = buildSystemType OnUserSettingChangeStatisticsLogger.logSettingValueChangedByUser( context.contextComponents.get(), BuildSystemPlugin.type.path, buildSystemType ) } } override fun update(e: AnActionEvent) { super.update(e) val validationResult = validateBuildSystem(buildSystemType) e.presentation.isEnabled = validationResult.isOk e.presentation.description = validationResult.safeAs<ValidationResult.ValidationError>()?.messages?.firstOrNull() } override fun getActionUpdateThread() = ActionUpdateThread.BGT } private inner class BuildSystemToolbar( place: String, actionGroup: ActionGroup, horizontal: Boolean ) : ActionToolbarImplWrapper(place, actionGroup, horizontal) { init { layoutPolicy = ActionToolbar.WRAP_LAYOUT_POLICY } override fun createToolbarButton( action: AnAction, look: ActionButtonLook?, place: String, presentation: Presentation, minimumSize: Dimension ): ActionButton = BuildSystemChooseButton(action as BuildSystemTypeAction, presentation, place, minimumSize) } private inner class BuildSystemChooseButton( action: BuildSystemTypeAction, presentation: Presentation, place: String, minimumSize: Dimension ) : ActionButtonWithText(action, presentation, place, minimumSize) { override fun getInsets(): Insets = super.getInsets().apply { right += left left = 0 } override fun getPreferredSize(): Dimension { val old = super.getPreferredSize() return Dimension(old.width + LEFT_RIGHT_PADDING * 2, old.height + TOP_BOTTOM_PADDING * 2) } } companion object { private const val LEFT_RIGHT_PADDING = 6 private const val TOP_BOTTOM_PADDING = 2 } }
apache-2.0
2f1e9aac56930a5840cc2f98c5380d9e
41.672
158
0.726983
5.182702
false
false
false
false
ftomassetti/kolasu
core/src/main/kotlin/com/strumenta/kolasu/parsing/Parsing.kt
1
5052
package com.strumenta.kolasu.parsing import com.strumenta.kolasu.model.* import com.strumenta.kolasu.validation.Issue import com.strumenta.kolasu.validation.IssueSeverity import com.strumenta.kolasu.validation.IssueType import com.strumenta.kolasu.validation.Result import org.antlr.v4.runtime.* import java.io.* import java.nio.charset.Charset open class CodeProcessingResult<D>( val issues: List<Issue>, val data: D?, val code: String? = null ) { val correct: Boolean get() = issues.none { it.severity != IssueSeverity.INFO } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is CodeProcessingResult<*>) return false if (issues != other.issues) return false if (data != other.data) return false if (code != other.code) return false return true } override fun hashCode(): Int { var result = issues.hashCode() result = 31 * result + (data?.hashCode() ?: 0) result = 31 * result + (code?.hashCode() ?: 0) return result } } class LexingResult( issues: List<Issue>, val tokens: List<Token>, code: String? = null, val time: Long? = null ) : CodeProcessingResult<List<Token>>(issues, tokens, code) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is LexingResult) return false if (!super.equals(other)) return false if (tokens != other.tokens) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + tokens.hashCode() return result } } class FirstStageParsingResult<C : ParserRuleContext>( issues: List<Issue>, val root: C?, code: String? = null, val incompleteNode: Node? = null, val time: Long? = null, val lexingTime: Long? = null, ) : CodeProcessingResult<C>(issues, root, code) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is FirstStageParsingResult<*>) return false if (!super.equals(other)) return false if (root != other.root) return false if (incompleteNode != other.incompleteNode) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + (root?.hashCode() ?: 0) result = 31 * result + (incompleteNode?.hashCode() ?: 0) return result } } class ParsingResult<RootNode : Node>( issues: List<Issue>, val root: RootNode?, code: String? = null, val incompleteNode: Node? = null, val firstStage: FirstStageParsingResult<*>? = null, val time: Long? = null ) : CodeProcessingResult<RootNode>(issues, root, code) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ParsingResult<*>) return false if (!super.equals(other)) return false if (root != other.root) return false if (incompleteNode != other.incompleteNode) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + (root?.hashCode() ?: 0) result = 31 * result + (incompleteNode?.hashCode() ?: 0) return result } fun toResult(): Result<RootNode> = Result(issues, root) } fun String.toStream(charset: Charset = Charsets.UTF_8) = ByteArrayInputStream(toByteArray(charset)) interface KLexer { fun lex(code: String): LexingResult = lex(code.toStream()) fun lex(file: File): LexingResult = lex(FileInputStream(file)) fun lex(inputStream: InputStream): LexingResult } fun Lexer.injectErrorCollectorInLexer(issues: MutableList<Issue>) { this.removeErrorListeners() this.addErrorListener(object : BaseErrorListener() { override fun syntaxError( p0: Recognizer<*, *>?, p1: Any?, line: Int, charPositionInLine: Int, errorMessage: String?, p5: RecognitionException? ) { issues.add( Issue( IssueType.LEXICAL, errorMessage ?: "unspecified", position = Point(line, charPositionInLine).asPosition ) ) } }) } fun Parser.injectErrorCollectorInParser(issues: MutableList<Issue>) { this.removeErrorListeners() this.addErrorListener(object : BaseErrorListener() { override fun syntaxError( p0: Recognizer<*, *>?, p1: Any?, line: Int, charPositionInLine: Int, errorMessage: String?, p5: RecognitionException? ) { issues.add( Issue( IssueType.SYNTACTIC, errorMessage ?: "unspecified", position = Point(line, charPositionInLine).asPosition ) ) } }) }
apache-2.0
a36e9b24fd21740f1f05017293c2bdef
28.372093
99
0.599565
4.381613
false
false
false
false
roylanceMichael/yaclib
core/src/main/java/org/roylance/yaclib/core/services/python/PythonProcessLanguageService.kt
1
1350
package org.roylance.yaclib.core.services.python import org.roylance.yaclib.YaclibModel import org.roylance.yaclib.core.services.IProcessLanguageService import org.roylance.yaclib.core.services.common.ReadmeBuilder class PythonProcessLanguageService : IProcessLanguageService { override fun buildInterface( projectInformation: YaclibModel.ProjectInformation): YaclibModel.AllFiles { val returnList = YaclibModel.AllFiles.newBuilder() returnList.addFiles(PropertiesBuilder(projectInformation.mainDependency).build()) returnList.addFiles(InitBuilder(projectInformation.mainDependency).build()) returnList.addFiles(ReadmeBuilder(projectInformation.mainDependency).build()) returnList.addFiles(SetupBuilder().build()) returnList.addFiles(SetupCFGBuilder().build()) projectInformation.controllers.controllerDependenciesList .filter { it.dependency.group == projectInformation.mainDependency.group && it.dependency.name == projectInformation.mainDependency.name } .forEach { controllerDependency -> controllerDependency.controllers.controllersList.forEach { controller -> returnList.addFiles( PythonServiceImplementationBuilder(projectInformation.mainDependency, controller).build()) } } return returnList.build() } }
mit
e73477af149930ee0fdded8c84bc05a2
44.033333
146
0.765185
5.357143
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-plugins/ktor-server-cors/jvmAndNix/src/io/ktor/server/plugins/cors/CORSUtils.kt
1
4370
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.cors import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* internal fun ApplicationCall.accessControlAllowOrigin( origin: String, allowsAnyHost: Boolean, allowCredentials: Boolean ) { val headerOrigin = if (allowsAnyHost && !allowCredentials) "*" else origin response.header(HttpHeaders.AccessControlAllowOrigin, headerOrigin) } internal fun ApplicationCall.corsVary() { val vary = response.headers[HttpHeaders.Vary] val varyValue = if (vary == null) HttpHeaders.Origin else vary + ", " + HttpHeaders.Origin response.header(HttpHeaders.Vary, varyValue) } internal fun ApplicationCall.accessControlAllowCredentials(allowCredentials: Boolean) { if (allowCredentials) { response.header(HttpHeaders.AccessControlAllowCredentials, "true") } } internal fun ApplicationCall.accessControlMaxAge(maxAgeHeaderValue: String?) { if (maxAgeHeaderValue != null) { response.header(HttpHeaders.AccessControlMaxAge, maxAgeHeaderValue) } } internal fun isSameOrigin(origin: String, point: RequestConnectionPoint, numberRegex: Regex): Boolean { val requestOrigin = "${point.scheme}://${point.serverHost}:${point.serverPort}" return normalizeOrigin(requestOrigin, numberRegex) == normalizeOrigin(origin, numberRegex) } internal fun corsCheckOrigins( origin: String, allowsAnyHost: Boolean, hostsNormalized: Set<String>, hostsWithWildcard: Set<Pair<String, String>>, originPredicates: List<(String) -> Boolean>, numberRegex: Regex ): Boolean { val normalizedOrigin = normalizeOrigin(origin, numberRegex) return allowsAnyHost || normalizedOrigin in hostsNormalized || hostsWithWildcard.any { (prefix, suffix) -> normalizedOrigin.startsWith(prefix) && normalizedOrigin.endsWith(suffix) } || originPredicates.any { it(origin) } } internal fun corsCheckRequestHeaders( requestHeaders: List<String>, allHeadersSet: Set<String>, headerPredicates: List<(String) -> Boolean> ): Boolean = requestHeaders.all { header -> header in allHeadersSet || headerMatchesAPredicate(header, headerPredicates) } internal fun headerMatchesAPredicate(header: String, headerPredicates: List<(String) -> Boolean>): Boolean = headerPredicates.any { it(header) } internal fun ApplicationCall.corsCheckCurrentMethod(methods: Set<HttpMethod>): Boolean = request.httpMethod in methods internal fun ApplicationCall.corsCheckRequestMethod(methods: Set<HttpMethod>): Boolean { val requestMethod = request.header(HttpHeaders.AccessControlRequestMethod)?.let { HttpMethod(it) } return requestMethod != null && requestMethod in methods } internal suspend fun ApplicationCall.respondCorsFailed() { respond(HttpStatusCode.Forbidden) } internal fun isValidOrigin(origin: String): Boolean { if (origin.isEmpty()) return false if (origin == "null") return true if ("%" in origin) return false val protoDelimiter = origin.indexOf("://") if (protoDelimiter <= 0) return false val protoValid = origin[0].isLetter() && origin.subSequence(0, protoDelimiter).all { ch -> ch.isLetter() || ch.isDigit() || ch == '-' || ch == '+' || ch == '.' } if (!protoValid) return false var portIndex = origin.length for (index in protoDelimiter + 3 until origin.length) { val ch = origin[index] if (ch == ':' || ch == '/') { portIndex = index + 1 break } if (ch == '?') return false } for (index in portIndex until origin.length) { if (!origin[index].isDigit()) return false } return true } internal fun normalizeOrigin(origin: String, numberRegex: Regex): String { if (origin == "null" || origin == "*") return origin val builder = StringBuilder(origin.length) builder.append(origin) if (!origin.substringAfterLast(":", "").matches(numberRegex)) { val port = when (origin.substringBefore(':')) { "http" -> "80" "https" -> "443" else -> null } if (port != null) { builder.append(":$port") } } return builder.toString() }
apache-2.0
45af5c7589f6b8e83e8ea297638f5b33
32.615385
119
0.689931
4.292731
false
false
false
false
marius-m/wt4
components/src/test/java/lt/markmerkk/timecounter/WorkGoalForecasterShouldFinishWeekTest.kt
1
9672
package lt.markmerkk.timecounter import lt.markmerkk.TimeProviderTest import org.assertj.core.api.Assertions import org.joda.time.Duration import org.joda.time.LocalTime import org.junit.Test class WorkGoalForecasterShouldFinishWeekTest { private val timeProvider = TimeProviderTest() private val now = timeProvider.now() private val workGoalForecaster = WorkGoalForecaster() @Test fun mon_workLeft_hasBreakIncluded() { // Assemble val localNow = now.plusDays(4) // mon .withTime( LocalTime.MIDNIGHT .plusHours(15) .plusMinutes(0) ) val durationWorked = Duration.standardHours(6) // Act val result = workGoalForecaster .forecastShouldFinishWeek( dtCurrent = localNow, durationWorked = durationWorked, ) // Assert val expectDtFinish = now.plusDays(4) .withTime( LocalTime.MIDNIGHT .plusHours(17) .plusMinutes(0) ) Assertions.assertThat(result).isEqualTo(expectDtFinish) } @Test fun tue_workFinished() { // Assemble val localNow = now.plusDays(5) // tue .withTime( LocalTime.MIDNIGHT .plusHours(17) .plusMinutes(0) ) val durationWorked = Duration.standardHours(16) // Act val result = workGoalForecaster .forecastShouldFinishWeek( dtCurrent = localNow, durationWorked = durationWorked, ) // Assert val expectDtFinish = now.plusDays(5) .withTime( LocalTime.MIDNIGHT .plusHours(17) .plusMinutes(0) ) Assertions.assertThat(result).isEqualTo(expectDtFinish) } @Test fun tue_workedAsNeeded() { // Assemble val localNow = now.plusDays(5) // tue .withTime( LocalTime.MIDNIGHT .plusHours(15) .plusMinutes(0) ) val durationWorked = Duration.standardHours(14) // Act val result = workGoalForecaster .forecastShouldFinishWeek( dtCurrent = localNow, durationWorked = durationWorked, ) // Assert val expectDtFinish = now.plusDays(5) .withTime( LocalTime.MIDNIGHT .plusHours(17) .plusMinutes(0) ) Assertions.assertThat(result).isEqualTo(expectDtFinish) } @Test fun tue_workedABitLess() { // Assemble val localNow = now.plusDays(5) // tue .withTime( LocalTime.MIDNIGHT .plusHours(15) .plusMinutes(0) ) val durationWorked = Duration.standardHours(12) // Act val result = workGoalForecaster .forecastShouldFinishWeek( dtCurrent = localNow, durationWorked = durationWorked, ) // Assert val expectDtFinish = now.plusDays(5) .withTime( LocalTime.MIDNIGHT .plusHours(19) .plusMinutes(0) ) Assertions.assertThat(result).isEqualTo(expectDtFinish) } @Test fun tue_workedWayMore() { // Assemble val localNow = now.plusDays(5) // tue .withTime( LocalTime.MIDNIGHT .plusHours(15) .plusMinutes(0) ) val durationWorked = Duration.standardHours(20) // Act val result = workGoalForecaster .forecastShouldFinishWeek( dtCurrent = localNow, durationWorked = durationWorked, ) // Assert val expectDtFinish = now.plusDays(5) .withTime( LocalTime.MIDNIGHT .plusHours(15) .plusMinutes(0) ) Assertions.assertThat(result).isEqualTo(expectDtFinish) } @Test fun mon_workedAsNeeded_noBreak() { // Assemble val localNow = now.plusDays(4) // mon .withTime( LocalTime.MIDNIGHT .plusHours(11) .plusMinutes(0) ) val durationWorked = Duration.standardHours(3) // Act val result = workGoalForecaster .forecastShouldFinishWeek( dtCurrent = localNow, durationWorked = durationWorked, ) // Assert val expectDtFinish = now.plusDays(4) .withTime( LocalTime.MIDNIGHT .plusHours(16) .plusMinutes(0) ) Assertions.assertThat(result).isEqualTo(expectDtFinish) } @Test fun mon_workedAsNeeded_middleOfBreak() { // Assemble val localNow = now.plusDays(4) // mon .withTime( LocalTime.MIDNIGHT .plusHours(12) .plusMinutes(30) ) val durationWorked = Duration.standardHours(4) // Act val result = workGoalForecaster .forecastShouldFinishWeek( dtCurrent = localNow, durationWorked = durationWorked, ) // Assert val expectDtFinish = now.plusDays(4) .withTime( LocalTime.MIDNIGHT .plusHours(16) .plusMinutes(30) ) Assertions.assertThat(result).isEqualTo(expectDtFinish) } @Test fun fri_endOfDay_workedAsNeeded() { // Assemble val localNow = now.plusDays(8) // fri .withTime( LocalTime.MIDNIGHT .plusHours(17) .plusMinutes(0) ) val durationWorked = Duration.standardHours(40) // Act val result = workGoalForecaster .forecastShouldFinishWeek( dtCurrent = localNow, durationWorked = durationWorked, ) // Assert val expectDtFinish = now.plusDays(8) .withTime( LocalTime.MIDNIGHT .plusHours(17) ) Assertions.assertThat(result).isEqualTo(expectDtFinish) } @Test fun fri_endOfDay_missingWork() { // Assemble val localNow = now.plusDays(8) // fri .withTime( LocalTime.MIDNIGHT .plusHours(17) .plusMinutes(0) ) val durationWorked = Duration.standardHours(38) // Act val result = workGoalForecaster .forecastShouldFinishWeek( dtCurrent = localNow, durationWorked = durationWorked, ) // Assert val expectDtFinish = now.plusDays(8) .withTime( LocalTime.MIDNIGHT .plusHours(19) ) Assertions.assertThat(result).isEqualTo(expectDtFinish) } @Test fun fri_endOfDay_lotsOfMissingWork() { // Assemble val localNow = now.plusDays(8) // fri .withTime( LocalTime.MIDNIGHT .plusHours(17) .plusMinutes(0) ) val durationWorked = Duration.standardHours(20) // Act val result = workGoalForecaster .forecastShouldFinishWeek( dtCurrent = localNow, durationWorked = durationWorked, ) // Assert val expectDtFinish = now.plusDays(9) // next day .withTime( LocalTime.MIDNIGHT .plusHours(13) ) Assertions.assertThat(result).isEqualTo(expectDtFinish) } @Test fun fri_workDayLeft_alreadyFinished() { // Assemble val localNow = now.plusDays(8) // fri .withTime( LocalTime.MIDNIGHT .plusHours(15) ) val durationWorked = Duration.standardHours(40) // Act val result = workGoalForecaster .forecastShouldFinishWeek( dtCurrent = localNow, durationWorked = durationWorked, ) // Assert val expectDtFinish = now.plusDays(8) .withTime( LocalTime.MIDNIGHT .plusHours(15) .plusMinutes(0) ) Assertions.assertThat(result).isEqualTo(expectDtFinish) } @Test fun fri_workDayLeft_early_alreadyFinished() { // Assemble val localNow = now.plusDays(8) // fri .withTime( LocalTime.MIDNIGHT .plusHours(10) ) val durationWorked = Duration.standardHours(40) // Act val result = workGoalForecaster .forecastShouldFinishWeek( dtCurrent = localNow, durationWorked = durationWorked, ) // Assert val expectDtFinish = now.plusDays(8) .withTime( LocalTime.MIDNIGHT .plusHours(10) .plusMinutes(0) ) Assertions.assertThat(result).isEqualTo(expectDtFinish) } }
apache-2.0
d28eeede6c86056dbae94c718dda1fd8
27.037681
63
0.503412
5.288136
false
false
false
false
cnevinc/Bandhook-Kotlin
app/src/main/java/com/antonioleiva/bandhookkotlin/App.kt
4
1209
/* * Copyright (C) 2015 Antonio Leiva * * 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.antonioleiva.bandhookkotlin import android.app.Application import com.antonioleiva.bandhookkotlin.di.* class App : Application() { override fun onCreate() { super.onCreate() instantiateInjector() } fun instantiateInjector() { val appModule = AppModuleImpl(this) val dataModule = DataModuleImpl(appModule) val repositoryModule = RepositoryModuleImpl(appModule, dataModule) val domainModule = DomainModuleImpl(repositoryModule) Inject.instance = InjectorImpl(appModule, domainModule, repositoryModule, dataModule) } }
apache-2.0
42523ada4b635a65cd14008013120d7c
31.675676
93
0.725393
4.494424
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_framebuffer_sRGB.kt
4
3519
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val ARB_framebuffer_sRGB = "ARBFramebufferSRGB".nativeClassGL("ARB_framebuffer_sRGB") { documentation = """ Native bindings to the $registryLink extension. Conventionally, OpenGL assumes framebuffer color components are stored in a linear color space. In particular, framebuffer blending is a linear operation. The sRGB color space is based on typical (non-linear) monitor characteristics expected in a dimly lit office. It has been standardized by the International Electrotechnical Commission (IEC) as IEC 61966-2-1. The sRGB color space roughly corresponds to 2.2 gamma correction. This extension adds a framebuffer capability for sRGB framebuffer update and blending. When blending is disabled but the new sRGB updated mode is enabled (assume the framebuffer supports the capability), high-precision linear color component values for red, green, and blue generated by fragment coloring are encoded for sRGB prior to being written into the framebuffer. When blending is enabled along with the new sRGB update mode, red, green, and blue framebuffer color components are treated as sRGB values that are converted to linear color values, blended with the high-precision color values generated by fragment coloring, and then the blend result is encoded for sRGB just prior to being written into the framebuffer. The primary motivation for this extension is that it allows OpenGL applications to render into a framebuffer that is scanned to a monitor configured to assume framebuffer color values are sRGB encoded. This assumption is roughly true of most PC monitors with default gamma correction. This allows applications to achieve faithful color reproduction for OpenGL rendering without adjusting the monitor's gamma correction. Requires ${ARB_framebuffer_object.link}. ${GL30.promoted} """ IntConstant( """ Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev. """, "FRAMEBUFFER_SRGB"..0x8DB9 ) } val GLX_ARB_framebuffer_sRGB = "GLXARBFramebufferSRGB".nativeClassGLX("GLX_ARB_framebuffer_sRGB", ARB) { documentation = """ Native bindings to the ${registryLink("ARB_framebuffer_sRGB")} extension. GLX functionality for ${ARB_framebuffer_sRGB.link}. """ IntConstant( "Accepted by the {@code attribList} parameter of #ChooseVisual(), and by the {@code attrib} parameter of #GetConfig().", "FRAMEBUFFER_SRGB_CAPABLE_ARB"..0x20B2 ) } val WGL_ARB_framebuffer_sRGB = "WGLARBFramebufferSRGB".nativeClassWGL("WGL_ARB_framebuffer_sRGB", ARB) { documentation = """ Native bindings to the ${registryLink("ARB_framebuffer_sRGB")} extension. WGL functionality for ${ARB_framebuffer_sRGB.link}. Requires ${WGL_EXT_extensions_string.link}, ${WGL_ARB_pixel_format.link} and ${ARB_framebuffer_object.link}. """ IntConstant( """ Accepted by the {@code attributes} parameter of #GetPixelFormatAttribivARB() and the {@code attribIList} of #ChoosePixelFormatARB(). """, "FRAMEBUFFER_SRGB_CAPABLE_ARB"..0x20A9 ) }
bsd-3-clause
632dc20c1257454300bed9ad0c13e729
44.714286
160
0.712134
4.787755
false
false
false
false
MichaelRocks/grip
library/src/test/java/io/michaelrocks/grip/ClassRegistryToAnnotationTest.kt
1
12008
/* * Copyright 2021 Michael Rozumyanskiy * * 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 io.michaelrocks.grip import io.michaelrocks.grip.annotations.AnnotationGenerator import io.michaelrocks.grip.annotations.createAnnotationMirror import io.michaelrocks.grip.annotations.getAnnotationType import io.michaelrocks.grip.mirrors.EnumMirror import io.michaelrocks.grip.mirrors.ReflectorImpl import io.michaelrocks.grip.mirrors.Type import io.michaelrocks.grip.mirrors.getArrayType import io.michaelrocks.grip.mirrors.getObjectTypeByInternalName import io.michaelrocks.grip.mirrors.getType import io.michaelrocks.mockito.given import io.michaelrocks.mockito.mock import io.michaelrocks.mockito.notNull import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test import org.objectweb.asm.ClassWriter class ClassRegistryToAnnotationTest { @Test fun testEmptyAnnotation() { val annotationType = getObjectTypeByInternalName("EmptyAnnotation") val classRegistry = createClassRegistry( annotationType to generateAnnotation(annotationType) ) val actualAnnotation = classRegistry.getAnnotationMirror(annotationType) assertEquals(annotationType, actualAnnotation.type) assertTrue(actualAnnotation.values.isEmpty()) } @Test fun testExplicitValueAnnotation() { val annotationType = getObjectTypeByInternalName("ExplicitValueAnnotation") val classRegistry = createClassRegistry( annotationType to generateAnnotation(annotationType) { addMethod("explicitValue", getType<String>()) } ) val actualAnnotation = classRegistry.getAnnotationMirror(annotationType) assertEquals(annotationType, actualAnnotation.type) assertTrue(actualAnnotation.values.isEmpty()) } @Test fun testImplicitValueAnnotation() { val annotationType = getObjectTypeByInternalName("ImplicitValueAnnotation") val classRegistry = createClassRegistry( annotationType to generateAnnotation(annotationType) { addMethod("implicitValue", getType<String>(), "defaultImplicitValue") } ) val actualAnnotation = classRegistry.getAnnotationMirror(annotationType) assertEquals(annotationType, actualAnnotation.type) assertEquals("defaultImplicitValue", actualAnnotation.values["implicitValue"]) assertEquals(1, actualAnnotation.values.size.toLong()) } @Test fun testExplicitAndImplicitValuesAnnotation() { val annotationType = getObjectTypeByInternalName("ExplicitAndImplicitValuesAnnotation") val classRegistry = createClassRegistry( annotationType to generateAnnotation(annotationType) { addMethod("explicitValue", getType<String>()) addMethod("implicitValue", getType<String>(), "defaultImplicitValue") } ) val actualAnnotation = classRegistry.getAnnotationMirror(annotationType) assertEquals(annotationType, actualAnnotation.type) assertEquals("defaultImplicitValue", actualAnnotation.values["implicitValue"]) assertEquals(1, actualAnnotation.values.size.toLong()) } @Test fun testSimpleValuesAnnotation() { val annotationType = getObjectTypeByInternalName("PrimitiveValuesAnnotation") val classRegistry = createClassRegistry( annotationType to generateAnnotation(annotationType) { addMethod("booleanValue", Type.Primitive.Boolean, true) addMethod("byteValue", Type.Primitive.Byte, 42.toByte()) addMethod("charValue", Type.Primitive.Char, 'x') addMethod("floatValue", Type.Primitive.Float, Math.E.toFloat()) addMethod("doubleValue", Type.Primitive.Double, Math.PI) addMethod("intValue", Type.Primitive.Int, 42) addMethod("longValue", Type.Primitive.Long, 42L) addMethod("shortValue", Type.Primitive.Short, 42.toShort()) addMethod("stringValue", getType<String>(), "x") } ) val actualAnnotation = classRegistry.getAnnotationMirror(annotationType) assertEquals(annotationType, actualAnnotation.type) assertEquals(true, actualAnnotation.values["booleanValue"]) assertEquals(42.toByte(), actualAnnotation.values["byteValue"]) assertEquals('x', actualAnnotation.values["charValue"]) assertEquals(Math.E.toFloat(), actualAnnotation.values["floatValue"] as Float, 0f) assertEquals(Math.PI, actualAnnotation.values["doubleValue"] as Double, 0.0) assertEquals(42, actualAnnotation.values["intValue"]) assertEquals(42L, actualAnnotation.values["longValue"]) assertEquals(42.toShort(), actualAnnotation.values["shortValue"]) assertEquals("x", actualAnnotation.values["stringValue"]) assertEquals(9, actualAnnotation.values.size.toLong()) } @Test fun testArrayValuesAnnotation() { val annotationType = getObjectTypeByInternalName("ArrayValuesAnnotation") val classRegistry = createClassRegistry( annotationType to generateAnnotation(annotationType) { addMethod("booleanArrayValue", getType<BooleanArray>(), booleanArrayOf(true, false, true)) addMethod("byteArrayValue", getType<ByteArray>(), byteArrayOf(42, 43, 44)) addMethod("charArrayValue", getType<CharArray>(), charArrayOf('x', 'y', 'z')) addMethod("floatArrayValue", getType<FloatArray>(), floatArrayOf(42f, 43f, 44f)) addMethod("doubleArrayValue", getType<DoubleArray>(), doubleArrayOf(42.0, 43.0, 44.0)) addMethod("intArrayValue", getType<IntArray>(), intArrayOf(42, 43, 44)) addMethod("longArrayValue", getType<LongArray>(), longArrayOf(42, 43, 44)) addMethod("shortArrayValue", getType<ShortArray>(), shortArrayOf(42, 43, 44)) addMethod("stringArrayValue", getType<Array<String>>(), arrayOf("x", "y", "z")) } ) val actualAnnotation = classRegistry.getAnnotationMirror(annotationType) assertEquals(annotationType, actualAnnotation.type) assertArrayEquals(booleanArrayOf(true, false, true), actualAnnotation.values["booleanArrayValue"] as BooleanArray) assertArrayEquals(byteArrayOf(42, 43, 44), actualAnnotation.values["byteArrayValue"] as ByteArray) assertArrayEquals(charArrayOf('x', 'y', 'z'), actualAnnotation.values["charArrayValue"] as CharArray) assertArrayEquals(floatArrayOf(42f, 43f, 44f), actualAnnotation.values["floatArrayValue"] as FloatArray, 0f) assertArrayEquals(doubleArrayOf(42.0, 43.0, 44.0), actualAnnotation.values["doubleArrayValue"] as DoubleArray, 0.0) assertArrayEquals(intArrayOf(42, 43, 44), actualAnnotation.values["intArrayValue"] as IntArray) assertArrayEquals(longArrayOf(42, 43, 44), actualAnnotation.values["longArrayValue"] as LongArray) assertArrayEquals(shortArrayOf(42, 43, 44), actualAnnotation.values["shortArrayValue"] as ShortArray) @Suppress("UNCHECKED_CAST") assertEquals(listOf("x", "y", "z"), actualAnnotation.values["stringArrayValue"]) assertEquals(9, actualAnnotation.values.size.toLong()) } @Test fun testEnumAnnotation() { val enumType = getObjectTypeByInternalName("TestEnum") val enumValue = EnumMirror(enumType, "TEST") val annotationType = getObjectTypeByInternalName("EnumAnnotation") val classRegistry = createClassRegistry( annotationType to generateAnnotation(annotationType) { addMethod("enumValue", enumType, enumValue) } ) val actualAnnotation = classRegistry.getAnnotationMirror(annotationType) assertEquals(annotationType, actualAnnotation.type) assertEquals(enumValue, actualAnnotation.values["enumValue"]) assertEquals(1, actualAnnotation.values.size.toLong()) } @Test fun testEnumArrayAnnotation() { val enumType = getObjectTypeByInternalName("TestEnum") val enumArrayType = getArrayType("[${enumType.descriptor}") val enumValues = arrayOf( EnumMirror(enumType, "TEST1"), EnumMirror(enumType, "TEST2"), EnumMirror(enumType, "TEST3") ) val annotationType = getObjectTypeByInternalName("testEnumArrayAnnotation") val classRegistry = createClassRegistry( annotationType to generateAnnotation(annotationType) { addMethod("enumArrayValue", enumArrayType, enumValues) } ) val actualAnnotation = classRegistry.getAnnotationMirror(annotationType) assertEquals(annotationType, actualAnnotation.type) assertEquals(listOf(*enumValues), actualAnnotation.values["enumArrayValue"]) assertEquals(1, actualAnnotation.values.size.toLong()) } @Test fun testNestedAnnotationAnnotation() { val nestedAnnotationType = getAnnotationType("NestedAnnotation") val nestedAnnotation = createAnnotationMirror("NestedAnnotation", "Nested", visible = true) val annotationType = getObjectTypeByInternalName("NestedAnnotationAnnotation") val classRegistry = createClassRegistry( nestedAnnotationType to generateAnnotation(nestedAnnotationType), annotationType to generateAnnotation(annotationType) { addMethod("annotationValue", nestedAnnotation.type, nestedAnnotation) } ) val actualAnnotation = classRegistry.getAnnotationMirror(annotationType) assertEquals(annotationType, actualAnnotation.type) assertEquals(nestedAnnotation, actualAnnotation.values["annotationValue"]) assertEquals(1, actualAnnotation.values.size.toLong()) } @Test fun testNestedAnnotationArrayAnnotation() { val nestedAnnotationType = getAnnotationType("NestedAnnotation") val nestedAnnotations = arrayOf( createAnnotationMirror("NestedAnnotation", "Nested1", visible = true), createAnnotationMirror("NestedAnnotation", "Nested2", visible = true), createAnnotationMirror("NestedAnnotation", "Nested3", visible = true) ) val annotationArrayType = getArrayType("[${nestedAnnotations[0].type.descriptor}") val annotationType = getObjectTypeByInternalName("NestedAnnotationArrayAnnotation") val classRegistry = createClassRegistry( nestedAnnotationType to generateAnnotation(nestedAnnotationType), annotationType to generateAnnotation(annotationType) { addMethod("annotationArrayValue", annotationArrayType, nestedAnnotations) } ) val actualAnnotation = classRegistry.getAnnotationMirror(annotationType) assertEquals(annotationType, actualAnnotation.type) assertEquals(listOf(*nestedAnnotations), actualAnnotation.values["annotationArrayValue"]) assertEquals(1, actualAnnotation.values.size.toLong()) } private fun generateAnnotation(type: Type.Object): ByteArray = generateAnnotation(type) {} private inline fun generateAnnotation(type: Type.Object, builder: AnnotationGenerator.() -> Unit): ByteArray = ClassWriter(ClassWriter.COMPUTE_FRAMES or ClassWriter.COMPUTE_MAXS).let { writer -> AnnotationGenerator .create(writer, type) .apply { builder() } .generate() writer.toByteArray() } private fun createClassRegistry(vararg entries: Pair<Type.Object, ByteArray>): ClassRegistry = ClassRegistryImpl(createFileRegistry(*entries), ReflectorImpl(GripFactory.ASM_API_DEFAULT)) private fun createFileRegistry(vararg entries: Pair<Type.Object, ByteArray>): FileRegistry = mock<FileRegistry>().apply { given(contains(notNull<Type.Object>())).thenAnswer { invocation -> entries.any { it.first == invocation.arguments[0] } } given(findTypesForFile(notNull())).thenReturn(entries.map { it.first }) for ((type, data) in entries) { given(readClass(type)).thenReturn(data) } } }
apache-2.0
796d31ec0b9a4953fa4d3c3d644a6e71
46.462451
119
0.752998
4.919295
false
true
false
false
AshishKayastha/Movie-Guide
app/src/main/kotlin/com/ashish/movieguide/ui/people/detail/PersonDetailActivity.kt
1
5272
package com.ashish.movieguide.ui.people.detail import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import com.ashish.movieguide.R import com.ashish.movieguide.data.models.Credit import com.ashish.movieguide.data.models.Movie import com.ashish.movieguide.data.models.Person import com.ashish.movieguide.data.models.PersonDetail import com.ashish.movieguide.data.models.ProfileImages import com.ashish.movieguide.data.models.TVShow import com.ashish.movieguide.di.modules.ActivityModule import com.ashish.movieguide.di.multibindings.activity.ActivityComponentBuilderHost import com.ashish.movieguide.ui.base.detail.BaseDetailActivity import com.ashish.movieguide.ui.base.detail.BaseDetailView import com.ashish.movieguide.ui.common.adapter.OnItemClickListener import com.ashish.movieguide.ui.common.adapter.RecyclerViewAdapter import com.ashish.movieguide.ui.movie.detail.MovieDetailActivity import com.ashish.movieguide.ui.tvshow.detail.TVShowDetailActivity import com.ashish.movieguide.utils.Constants.ADAPTER_TYPE_PERSON import com.ashish.movieguide.utils.Constants.MEDIA_TYPE_MOVIE import com.ashish.movieguide.utils.Constants.MEDIA_TYPE_TV import com.ashish.movieguide.utils.Constants.TMDB_URL import com.ashish.movieguide.utils.extensions.getOriginalImageUrl import com.ashish.movieguide.utils.extensions.getProfileUrl import com.ashish.movieguide.utils.extensions.isNotNullOrEmpty import icepick.State /** * Created by Ashish on Jan 04. */ class PersonDetailActivity : BaseDetailActivity<PersonDetail, BaseDetailView<PersonDetail>, PersonDetailPresenter>() { companion object { private const val EXTRA_PERSON = "person" @JvmStatic fun createIntent(context: Context, person: Person?): Intent { return Intent(context, PersonDetailActivity::class.java) .putExtra(EXTRA_PERSON, person) } } @JvmField @State var person: Person? = null private val onCastItemClickListener = object : OnItemClickListener { override fun onItemClick(position: Int, view: View) { onPersonCreditItemClicked(castAdapter, position, view) } } private val onCrewItemClickListener = object : OnItemClickListener { override fun onItemClick(position: Int, view: View) { onPersonCreditItemClicked(crewAdapter, position, view) } } private fun onPersonCreditItemClicked(adapter: RecyclerViewAdapter<Credit>?, position: Int, view: View) { val credit = adapter?.getItem<Credit>(position) val mediaType = credit?.mediaType if (MEDIA_TYPE_MOVIE == mediaType) { val movie = Movie(credit.id, credit.title, posterPath = credit.posterPath) val intent = MovieDetailActivity.createIntent(this@PersonDetailActivity, movie) startNewActivityWithTransition(view, R.string.transition_movie_poster, intent) } else if (MEDIA_TYPE_TV == mediaType) { val tvShow = TVShow(credit.id, credit.name, posterPath = credit.posterPath) val intent = TVShowDetailActivity.createIntent(this@PersonDetailActivity, tvShow) startNewActivityWithTransition(view, R.string.transition_tv_poster, intent) } } override fun injectDependencies(builderHost: ActivityComponentBuilderHost) { builderHost.getActivityComponentBuilder(PersonDetailActivity::class.java, PersonDetailComponent.Builder::class.java) .withModule(ActivityModule(this)) .build() .inject(this) } override fun getLayoutId() = R.layout.activity_detail_person override fun getIntentExtras(extras: Bundle?) { person = extras?.getParcelable(EXTRA_PERSON) } override fun getTransitionNameId() = R.string.transition_person_profile override fun loadDetailContent() { presenter?.loadDetailContent(person?.id) } override fun getBackdropPath() = "" override fun getPosterPath() = person?.profilePath.getProfileUrl() override fun showDetailContent(detailContent: PersonDetail) { detailContent.apply { titleText.text = name [email protected] = imdbId showProfileBackdropImage(detailContent.images) } super.showDetailContent(detailContent) } private fun showProfileBackdropImage(images: ProfileImages?) { val profileImages = images?.profiles if (profileImages.isNotNullOrEmpty()) { val backdropPath = profileImages!![profileImages.size - 1].filePath if (getBackdropPath().isNullOrEmpty() && backdropPath.isNotNullOrEmpty()) { showBackdropImage(backdropPath.getOriginalImageUrl()) } } else { showBackdropImage(getPosterPath()) } } override fun getDetailContentType() = ADAPTER_TYPE_PERSON override fun getItemTitle() = person?.name ?: "" override fun getCastItemClickListener() = onCastItemClickListener override fun getCrewItemClickListener() = onCrewItemClickListener override fun getShareText(): CharSequence { return person!!.name + "\n\n" + TMDB_URL + "person/" + person!!.id } }
apache-2.0
476339be102d450da38a3253c5b30b3e
38.350746
109
0.723065
4.669619
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinCatchParameterFixer.kt
6
1629
// 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.editor.fixers import com.intellij.lang.SmartEnterProcessorWithFixers import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtCatchClause import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import kotlin.math.min class KotlinCatchParameterFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() { override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, psiElement: PsiElement) { if (psiElement !is KtCatchClause) return val catchEnd = psiElement.node.findChildByType(KtTokens.CATCH_KEYWORD)!!.textRange!!.endOffset val parameterList = psiElement.parameterList if (parameterList == null || parameterList.node.findChildByType(KtTokens.RPAR) == null) { val endOffset = min(psiElement.endOffset, psiElement.catchBody?.startOffset ?: Int.MAX_VALUE) val parameter = parameterList?.parameters?.firstOrNull()?.text ?: "" editor.document.replaceString(catchEnd, endOffset, "($parameter)") processor.registerUnresolvedError(endOffset - 1) } else if (parameterList.parameters.firstOrNull()?.text.isNullOrBlank()) { processor.registerUnresolvedError(parameterList.startOffset + 1) } } }
apache-2.0
22b2fa1796fcb222f4069ed0182ee37f
51.580645
158
0.760589
4.833828
false
false
false
false
dahlstrom-g/intellij-community
platform/lang-impl/src/com/intellij/lang/documentation/ide/actions/DocumentationViewExternalAction.kt
4
1341
// 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.lang.documentation.ide.actions import com.intellij.codeInsight.hint.HintManagerImpl.ActionToIgnore import com.intellij.lang.documentation.ide.impl.DocumentationBrowser import com.intellij.lang.documentation.ide.impl.openUrl import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataContext internal class DocumentationViewExternalAction : AnAction(), ActionToIgnore { /** * TODO consider exposing [DocumentationBrowser.currentExternalUrl] * in [com.intellij.lang.documentation.ide.DocumentationBrowserFacade] * to get rid of the cast */ private fun browser(dc: DataContext): DocumentationBrowser? = dc.getData(DOCUMENTATION_BROWSER) as? DocumentationBrowser override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = browser(e.dataContext)?.currentExternalUrl() != null } override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val browser = browser(e.dataContext) ?: return val url = browser.currentExternalUrl() ?: return openUrl(project, browser.targetPointer, url) } }
apache-2.0
5055506781b297a88f406cc0990b337d
43.7
158
0.787472
4.47
false
false
false
false
ngthtung2805/dalatlaptop
app/src/main/java/com/tungnui/dalatlaptop/ux/Order/OrderCreateAddressFragment.kt
1
4748
package com.tungnui.dalatlaptop.ux.Order import android.app.ProgressDialog import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.tungnui.dalatlaptop.R import com.tungnui.dalatlaptop.SettingsMy import com.tungnui.dalatlaptop.api.CustomerServices import com.tungnui.dalatlaptop.api.ServiceGenerator import com.tungnui.dalatlaptop.models.Billing import com.tungnui.dalatlaptop.models.Customer import com.tungnui.dalatlaptop.models.Shipping import com.tungnui.dalatlaptop.libraryhelper.Utils import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.fragment_order_create_address.* import org.jetbrains.anko.noButton import org.jetbrains.anko.sdk25.coroutines.onCheckedChange import org.jetbrains.anko.support.v4.alert import org.jetbrains.anko.support.v4.toast import org.jetbrains.anko.yesButton class OrderCreateAddressFragment : Fragment() { private var mCompositeDisposable: CompositeDisposable val customerService: CustomerServices init { mCompositeDisposable = CompositeDisposable() customerService = ServiceGenerator.createService(CustomerServices::class.java) } private lateinit var progressDialog: ProgressDialog override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_order_create_address, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) progressDialog = Utils.generateProgressDialog(activity, false) refreshLayout() order_create_address_add.setOnClickListener { (activity as OrderActivity).onAddAddress() } order_create_address_delete.setOnClickListener { alert("", "Bạn muốn xóa địa chỉ này?") { yesButton { deleteAddress() } noButton {} }.show() } order_create_address_update.setOnClickListener { (activity as OrderActivity).onAddAddress(isUpdate = true) } order_create_address_rd1.onCheckedChange { buttonView, isChecked -> if (isChecked) { order_create_address_rd2.isChecked = false } } order_create_address_rd2.onCheckedChange { buttonView, isChecked -> if (isChecked) { order_create_address_rd1.isChecked = false } } order_create_step1_next.setOnClickListener { var note:String="" if(order_create_address_rd2.isChecked) note= "Nhận hàng tại cửa hàng" (activity as OrderActivity).onNextStep2(note) } } fun deleteAddress() { progressDialog.show() val user = SettingsMy.getActiveUser() user?.let { val data = Customer(billing = Billing("", "", "", "", "", "", "", "", "", "", ""), shipping = Shipping("", "", "", "", "", "", "", "", "")) val disposable = customerService.update(it.id!!, data) .subscribeOn((Schedulers.io())) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ response -> SettingsMy.setActiveUser(response) refreshLayout() progressDialog.cancel() }, { error -> toast("Lỗi cập nhật!") progressDialog.cancel() }) mCompositeDisposable.add(disposable) } } fun refreshLayout() { val user = SettingsMy.getActiveUser() if (user?.billing?.firstName == "" || user?.billing?.address1 == "") { order_create_address_layout.visibility = View.GONE order_create_address_add.visibility = View.VISIBLE } else { order_create_address_layout.visibility = View.VISIBLE order_create_address_add.visibility = View.GONE var shipAddress = user?.billing shipAddress?.let { order_create_address_name.text = "${shipAddress.firstName}" order_create_address_phone.text = shipAddress.phone order_create_address_address.text = shipAddress.address1 } } } override fun onStop() { super.onStop() progressDialog.cancel() } }
mit
1c27f0d5a427f88f86f7bb1329825411
36.19685
116
0.627567
4.780364
false
false
false
false
fwcd/kotlin-language-server
server/src/test/resources/references/ReferenceOperator.kt
1
753
private class ReferenceOperator { override operator fun equals(other: Any?): Boolean = TODO() operator fun compareTo(other: ReferenceOperator): Int = TODO() operator fun inc(): ReferenceOperator = TODO() operator fun dec(): ReferenceOperator = TODO() operator fun plus(value: Int): Int = TODO() operator fun minus(value: Int): Int = TODO() operator fun not(): Int = TODO() } private class ReferenceEquals { override fun equals(other: Any?): Boolean = TODO() } private fun main() { var example = ReferenceOperator() assert(example == example) example > example example++ example-- example + 1 example - 1 !example val example2 = ReferenceEquals() assert(example2 == example2) }
mit
2e7b32924d4a0e1508dd6fef9102af8a
25
66
0.660027
4.352601
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/marketplace/statistics/PluginManagerUsageCollector.kt
5
5843
// 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.plugins.marketplace.statistics import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.PluginEnableDisableAction import com.intellij.ide.plugins.enums.PluginsGroupType import com.intellij.ide.plugins.marketplace.statistics.enums.DialogAcceptanceResultEnum import com.intellij.ide.plugins.marketplace.statistics.enums.InstallationSourceEnum import com.intellij.ide.plugins.marketplace.statistics.enums.SignatureVerificationResult import com.intellij.ide.plugins.newui.PluginsGroup import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.events.BaseEventId import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.PrimitiveEventField import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.internal.statistic.utils.getPluginInfoByDescriptor import com.intellij.internal.statistic.utils.getPluginInfoById import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.project.Project class PluginManagerUsageCollector : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = EVENT_GROUP companion object { private val EVENT_GROUP = EventLogGroup("plugin.manager", 3) private val PLUGINS_GROUP_TYPE = EventFields.Enum<PluginsGroupType>("group") private val ENABLE_DISABLE_ACTION = EventFields.Enum<PluginEnableDisableAction>("states") { it.name } private val ACCEPTANCE_RESULT = EventFields.Enum<DialogAcceptanceResultEnum>("acceptance_result") private val PLUGIN_SOURCE = EventFields.Enum<InstallationSourceEnum>("source") private val PREVIOUS_VERSION = PluginVersionEventField("previous_version") private val SIGNATURE_CHECK_RESULT = EventFields.Enum<SignatureVerificationResult>("signature_check_result") private val PLUGIN_CARD_OPENED = EVENT_GROUP.registerEvent( "plugin.search.card.opened", EventFields.PluginInfo, PLUGINS_GROUP_TYPE, EventFields.Int("index") ) private val THIRD_PARTY_ACCEPTANCE_CHECK = EVENT_GROUP.registerEvent("plugin.install.third.party.check", ACCEPTANCE_RESULT) private val PLUGIN_SIGNATURE_WARNING = EVENT_GROUP.registerEvent( "plugin.signature.warning.shown", EventFields.PluginInfo, ACCEPTANCE_RESULT ) private val PLUGIN_SIGNATURE_CHECK_RESULT = EVENT_GROUP.registerEvent( "plugin.signature.check.result", EventFields.PluginInfo, SIGNATURE_CHECK_RESULT ) private val PLUGIN_STATE_CHANGED = EVENT_GROUP.registerEvent( "plugin.state.changed", EventFields.PluginInfo, ENABLE_DISABLE_ACTION ) private val PLUGIN_INSTALLATION_STARTED = EVENT_GROUP.registerEvent( "plugin.installation.started", PLUGIN_SOURCE, EventFields.PluginInfo, PREVIOUS_VERSION ) private val PLUGIN_INSTALLATION_FINISHED = EVENT_GROUP.registerEvent("plugin.installation.finished", EventFields.PluginInfo) private val PLUGIN_REMOVED = EVENT_GROUP.registerEvent("plugin.was.removed", EventFields.PluginInfo) @JvmStatic fun pluginCardOpened(descriptor: IdeaPluginDescriptor, group: PluginsGroup?) = group?.let { PLUGIN_CARD_OPENED.log(getPluginInfoByDescriptor(descriptor), it.type, it.getPluginIndex(descriptor.pluginId)) } @JvmStatic fun thirdPartyAcceptanceCheck(result: DialogAcceptanceResultEnum) = THIRD_PARTY_ACCEPTANCE_CHECK.getIfInitializedOrNull()?.log(result) @JvmStatic fun pluginsStateChanged( descriptors: Collection<IdeaPluginDescriptor>, action: PluginEnableDisableAction, project: Project? = null, ) { descriptors.asSequence().map { getPluginInfoByDescriptor(it) }.forEach { PLUGIN_STATE_CHANGED.getIfInitializedOrNull()?.log(project, it, action) } } @JvmStatic fun pluginRemoved(pluginId: PluginId) = PLUGIN_REMOVED.getIfInitializedOrNull()?.log(getPluginInfoById(pluginId)) @JvmStatic fun pluginInstallationStarted( descriptor: IdeaPluginDescriptor, source: InstallationSourceEnum, previousVersion: String? = null ) { val pluginInfo = getPluginInfoByDescriptor(descriptor) PLUGIN_INSTALLATION_STARTED.getIfInitializedOrNull()?.log(source, pluginInfo, if (pluginInfo.isSafeToReport()) previousVersion else null) } @JvmStatic fun pluginInstallationFinished(descriptor: IdeaPluginDescriptor) = getPluginInfoByDescriptor(descriptor).let { PLUGIN_INSTALLATION_FINISHED.getIfInitializedOrNull()?.log(it) } fun signatureCheckResult(descriptor: IdeaPluginDescriptor, result: SignatureVerificationResult) = PLUGIN_SIGNATURE_CHECK_RESULT.getIfInitializedOrNull()?.log(getPluginInfoByDescriptor(descriptor), result) fun signatureWarningShown(descriptor: IdeaPluginDescriptor, result: DialogAcceptanceResultEnum) = PLUGIN_SIGNATURE_WARNING.getIfInitializedOrNull()?.log(getPluginInfoByDescriptor(descriptor), result) } private data class PluginVersionEventField(override val name: String): PrimitiveEventField<String?>() { override val validationRule: List<String> get() = listOf("{util#plugin_version}") override fun addData(fuData: FeatureUsageData, value: String?) { if (!value.isNullOrEmpty()) { fuData.addData(name, value) } } } } // We don't want to log actions when app did not initialized yet (e.g. migration process) private fun <T: BaseEventId> T.getIfInitializedOrNull(): T? = if (ApplicationManager.getApplication() == null) null else this
apache-2.0
668412d85733b9d8eb92123278de98d9
50.263158
158
0.782132
4.663208
false
false
false
false
itohiro73/intellij-custom-language-support-kotlin
src/main/kotlin/jp/itohiro/intellij/simpleplugin/SimpleAnnotator.kt
1
1453
package jp.itohiro.intellij.simpleplugin import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiLiteralExpression public class SimpleAnnotator: Annotator { override fun annotate(element: PsiElement, holder: AnnotationHolder) { if(element is PsiLiteralExpression) { val literalExpression: PsiLiteralExpression = element val value = literalExpression.value as String if (value.startsWith("simple:")) { val project = element.project val key = value.substring(7) val properties = SimpleUtil.findProperties(project, key) if (properties?.size() == 1) { val range = TextRange(element.textRange.startOffset + 7, element.textRange.startOffset + 7) val annotation = holder.createInfoAnnotation(range, null) annotation.textAttributes = DefaultLanguageHighlighterColors.LINE_COMMENT } else if (properties?.size() == 0) { val range = TextRange( element.textRange.startOffset + 8, element.textRange.endOffset) holder.createErrorAnnotation(range, "Unresolved property") } } } } }
apache-2.0
2313b8811aa0aa14b4d51f954de34567
45.903226
111
0.662078
5.341912
false
false
false
false
dahlstrom-g/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OoChildWithNullableParentEntityImpl.kt
3
7567
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.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.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToOneParent import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class OoChildWithNullableParentEntityImpl: OoChildWithNullableParentEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(OoParentEntity::class.java, OoChildWithNullableParentEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, true) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val parentEntity: OoParentEntity? get() = snapshot.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this) override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: OoChildWithNullableParentEntityData?): ModifiableWorkspaceEntityBase<OoChildWithNullableParentEntity>(), OoChildWithNullableParentEntity.Builder { constructor(): this(OoChildWithNullableParentEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity OoChildWithNullableParentEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field OoChildWithNullableParentEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var parentEntity: OoParentEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? OoParentEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? OoParentEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // 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 entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override fun getEntityData(): OoChildWithNullableParentEntityData = result ?: super.getEntityData() as OoChildWithNullableParentEntityData override fun getEntityClass(): Class<OoChildWithNullableParentEntity> = OoChildWithNullableParentEntity::class.java } } class OoChildWithNullableParentEntityData : WorkspaceEntityData<OoChildWithNullableParentEntity>() { override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<OoChildWithNullableParentEntity> { val modifiable = OoChildWithNullableParentEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): OoChildWithNullableParentEntity { val entity = OoChildWithNullableParentEntityImpl() entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return OoChildWithNullableParentEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as OoChildWithNullableParentEntityData if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as OoChildWithNullableParentEntityData return true } override fun hashCode(): Int { var result = entitySource.hashCode() return result } }
apache-2.0
82cf4317336b4fb3f719a1d11dfb8b31
40.582418
202
0.655874
6.0536
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KtControlFlowBuilder.kt
3
80534
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.dfa import com.intellij.codeInsight.Nullability import com.intellij.codeInspection.dataFlow.TypeConstraint import com.intellij.codeInspection.dataFlow.TypeConstraints import com.intellij.codeInspection.dataFlow.interpreter.DataFlowInterpreter import com.intellij.codeInspection.dataFlow.java.inst.* import com.intellij.codeInspection.dataFlow.jvm.SpecialField import com.intellij.codeInspection.dataFlow.jvm.TrapTracker import com.intellij.codeInspection.dataFlow.jvm.transfer.* import com.intellij.codeInspection.dataFlow.jvm.transfer.TryCatchTrap.CatchClauseDescriptor import com.intellij.codeInspection.dataFlow.lang.ir.* import com.intellij.codeInspection.dataFlow.lang.ir.ControlFlow.ControlFlowOffset import com.intellij.codeInspection.dataFlow.lang.ir.ControlFlow.DeferredOffset import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeBinOp import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeSet import com.intellij.codeInspection.dataFlow.types.* import com.intellij.codeInspection.dataFlow.value.* import com.intellij.codeInspection.dataFlow.value.DfaControlTransferValue.TransferTarget import com.intellij.codeInspection.dataFlow.value.DfaControlTransferValue.Trap import com.intellij.codeInspection.dataFlow.value.VariableDescriptor import com.intellij.openapi.diagnostic.logger import com.intellij.psi.* import com.intellij.psi.tree.TokenSet import com.intellij.psi.util.MethodSignatureUtil import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.FList import com.siyeh.ig.psiutils.TypeUtils import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.builtins.getReturnTypeFromFunctionType import org.jetbrains.kotlin.contracts.description.CallsEffectDeclaration import org.jetbrains.kotlin.contracts.description.ContractProviderKey import org.jetbrains.kotlin.contracts.description.EventOccurrencesRange import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.core.resolveType import org.jetbrains.kotlin.idea.inspections.dfa.KotlinAnchor.* import org.jetbrains.kotlin.idea.inspections.dfa.KotlinProblem.* import org.jetbrains.kotlin.idea.intentions.loopToCallChain.targetLoop import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.refactoring.move.moveMethod.type import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.VarargValueArgument import org.jetbrains.kotlin.resolve.constants.IntegerLiteralTypeConstructor import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.* import org.jetbrains.kotlin.utils.addIfNotNull import java.util.concurrent.ConcurrentHashMap class KtControlFlowBuilder(val factory: DfaValueFactory, val context: KtExpression) { private val flow = ControlFlow(factory, context) private val trapTracker = TrapTracker(factory, KtClassDef.typeConstraintFactory(context)) private val stringType = KtClassDef.getClassConstraint(context, StandardNames.FqNames.string) private var broken: Boolean = false fun buildFlow(): ControlFlow? { processExpression(context) if (broken) return null addInstruction(PopInstruction()) // return value flow.finish() return flow } private fun processExpression(expr: KtExpression?) { flow.startElement(expr) when (expr) { null -> pushUnknown() is KtBlockExpression -> processBlock(expr) is KtParenthesizedExpression -> processExpression(expr.expression) is KtBinaryExpression -> processBinaryExpression(expr) is KtBinaryExpressionWithTypeRHS -> processAsExpression(expr) is KtPrefixExpression -> processPrefixExpression(expr) is KtPostfixExpression -> processPostfixExpression(expr) is KtIsExpression -> processIsExpression(expr) is KtCallExpression -> processCallExpression(expr) is KtConstantExpression -> processConstantExpression(expr) is KtSimpleNameExpression -> processReferenceExpression(expr) is KtDotQualifiedExpression -> processQualifiedReferenceExpression(expr) is KtSafeQualifiedExpression -> processQualifiedReferenceExpression(expr) is KtReturnExpression -> processReturnExpression(expr) is KtContinueExpression -> processLabeledJumpExpression(expr) is KtBreakExpression -> processLabeledJumpExpression(expr) is KtThrowExpression -> processThrowExpression(expr) is KtIfExpression -> processIfExpression(expr) is KtWhenExpression -> processWhenExpression(expr) is KtWhileExpression -> processWhileExpression(expr) is KtDoWhileExpression -> processDoWhileExpression(expr) is KtForExpression -> processForExpression(expr) is KtProperty -> processDeclaration(expr) is KtLambdaExpression -> processLambda(expr) is KtStringTemplateExpression -> processStringTemplate(expr) is KtArrayAccessExpression -> processArrayAccess(expr) is KtAnnotatedExpression -> processExpression(expr.baseExpression) is KtClassLiteralExpression -> processClassLiteralExpression(expr) is KtLabeledExpression -> processExpression(expr.baseExpression) is KtThisExpression -> processThisExpression(expr) is KtSuperExpression -> pushUnknown() is KtCallableReferenceExpression -> processCallableReference(expr) is KtTryExpression -> processTryExpression(expr) is KtDestructuringDeclaration -> processDestructuringDeclaration(expr) is KtObjectLiteralExpression -> processObjectLiteral(expr) is KtNamedFunction -> processCodeDeclaration(expr) is KtClass -> processCodeDeclaration(expr) else -> { // unsupported construct if (LOG.isDebugEnabled) { val className = expr.javaClass.name if (unsupported.add(className)) { LOG.debug("Unsupported expression in control flow: $className") } } broken = true } } flow.finishElement(expr) } private fun processCodeDeclaration(expr: KtExpression) { processEscapes(expr) pushUnknown() } private fun processObjectLiteral(expr: KtObjectLiteralExpression) { processEscapes(expr) for (superTypeListEntry in expr.objectDeclaration.superTypeListEntries) { if (superTypeListEntry is KtSuperTypeCallEntry) { // super-constructor call: may be impure addInstruction(FlushFieldsInstruction()) } } val dfType = expr.getKotlinType().toDfType() addInstruction(PushValueInstruction(dfType, KotlinExpressionAnchor(expr))) } private fun processDestructuringDeclaration(expr: KtDestructuringDeclaration) { processExpression(expr.initializer) for (entry in expr.entries) { addInstruction(FlushVariableInstruction(factory.varFactory.createVariableValue(KtVariableDescriptor(entry)))) } } data class KotlinCatchClauseDescriptor(val clause : KtCatchClause): CatchClauseDescriptor { override fun parameter(): VariableDescriptor? { val parameter = clause.catchParameter ?: return null return KtVariableDescriptor(parameter) } override fun constraints(): MutableList<TypeConstraint> { val parameter = clause.catchParameter ?: return mutableListOf() return mutableListOf(TypeConstraint.fromDfType(parameter.type().toDfType())) } } private fun processTryExpression(statement: KtTryExpression) { inlinedBlock(statement) { val tryBlock = statement.tryBlock val finallyBlock = statement.finallyBlock val finallyStart = DeferredOffset() val finallyDescriptor = if (finallyBlock != null) EnterFinallyTrap(finallyBlock, finallyStart) else null finallyDescriptor?.let { trapTracker.pushTrap(it) } val tempVar = flow.createTempVariable(DfType.TOP) val sections = statement.catchClauses val clauses = LinkedHashMap<CatchClauseDescriptor, DeferredOffset>() if (sections.isNotEmpty()) { for (section in sections) { val catchBlock = section.catchBody if (catchBlock != null) { clauses[KotlinCatchClauseDescriptor(section)] = DeferredOffset() } } trapTracker.pushTrap(TryCatchTrap(statement, clauses)) } processExpression(tryBlock) addInstruction(JvmAssignmentInstruction(null, tempVar)) val gotoEnd = createTransfer(statement, tryBlock, tempVar, true) val singleFinally = FList.createFromReversed<Trap>(ContainerUtil.createMaybeSingletonList(finallyDescriptor)) controlTransfer(gotoEnd, singleFinally) if (sections.isNotEmpty()) { trapTracker.popTrap(TryCatchTrap::class.java) } for (section in sections) { val offset = clauses[KotlinCatchClauseDescriptor(section)] if (offset == null) continue setOffset(offset) val catchBlock = section.catchBody processExpression(catchBlock) addInstruction(JvmAssignmentInstruction(null, tempVar)) controlTransfer(gotoEnd, singleFinally) } if (finallyBlock != null) { setOffset(finallyStart) trapTracker.popTrap(EnterFinallyTrap::class.java) trapTracker.pushTrap(InsideFinallyTrap(finallyBlock)) processExpression(finallyBlock.finalExpression) addInstruction(PopInstruction()) controlTransfer(ExitFinallyTransfer(finallyDescriptor!!), FList.emptyList()) trapTracker.popTrap(InsideFinallyTrap::class.java) } } } private fun processCallableReference(expr: KtCallableReferenceExpression) { processExpression(expr.receiverExpression) addInstruction(KotlinCallableReferenceInstruction(expr)) } private fun processThisExpression(expr: KtThisExpression) { val exprType = expr.getKotlinType() val bindingContext = expr.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL) // Might differ from expression type if smartcast occurred val thisType = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, expr.instanceReference]?.type val dfType = thisType.toDfType() val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, expr.instanceReference] if (descriptor != null) { val varDesc = KtThisDescriptor(descriptor, dfType) addInstruction(JvmPushInstruction(factory.varFactory.createVariableValue(varDesc), KotlinExpressionAnchor(expr))) addImplicitConversion(expr, thisType, exprType) } else { addInstruction(PushValueInstruction(dfType, KotlinExpressionAnchor(expr))) } } private fun processClassLiteralExpression(expr: KtClassLiteralExpression) { val kotlinType = expr.getKotlinType() val receiver = expr.receiverExpression if (kotlinType != null) { if (receiver is KtSimpleNameExpression && receiver.mainReference.resolve() is KtClass) { val arguments = kotlinType.arguments if (arguments.size == 1) { val kType = arguments[0].type val kClassPsiType = TypeConstraint.fromDfType(kotlinType.toDfType()) if (kClassPsiType != TypeConstraints.TOP) { val kClassConstant: DfType = DfTypes.referenceConstant(kType, kClassPsiType) addInstruction(PushValueInstruction(kClassConstant, KotlinExpressionAnchor(expr))) return } } } } processExpression(receiver) addInstruction(PopInstruction()) addInstruction(PushValueInstruction(kotlinType.toDfType())) // TODO: support kotlin-class as a variable; link to TypeConstraint } private fun processAsExpression(expr: KtBinaryExpressionWithTypeRHS) { val operand = expr.left val typeReference = expr.right val type = getTypeCheckDfType(typeReference) val ref = expr.operationReference if (ref.text != "as?" && ref.text != "as") { broken = true return } processExpression(operand) if (type == DfType.TOP) { // Unknown/generic type: we cannot evaluate addInstruction(EvalUnknownInstruction(KotlinExpressionAnchor(expr), 1, expr.getKotlinType().toDfType())) return } val operandType = operand.getKotlinType() if (operandType.toDfType() is DfPrimitiveType) { addInstruction(WrapDerivedVariableInstruction(DfTypes.NOT_NULL_OBJECT, SpecialField.UNBOX)) } if (ref.text == "as?") { val tempVariable: DfaVariableValue = flow.createTempVariable(DfTypes.OBJECT_OR_NULL) addInstruction(JvmAssignmentInstruction(null, tempVariable)) addInstruction(PushValueInstruction(type, null)) addInstruction(InstanceofInstruction(null, false)) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.FALSE)) val anchor = KotlinExpressionAnchor(expr) addInstruction(JvmPushInstruction(tempVariable, anchor)) val endOffset = DeferredOffset() addInstruction(GotoInstruction(endOffset)) setOffset(offset) addInstruction(PushValueInstruction(DfTypes.NULL, anchor)) setOffset(endOffset) } else { val transfer = trapTracker.maybeTransferValue("kotlin.ClassCastException") addInstruction(EnsureInstruction(KotlinCastProblem(operand, expr), RelationType.IS, type, transfer)) if (typeReference != null) { val castType = typeReference.getAbbreviatedTypeOrType(typeReference.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL)) if (castType.toDfType() is DfPrimitiveType) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } } } } private fun processArrayAccess(expr: KtArrayAccessExpression, storedValue: KtExpression? = null) { val arrayExpression = expr.arrayExpression processExpression(arrayExpression) val kotlinType = arrayExpression?.getKotlinType() var curType = kotlinType val indexes = expr.indexExpressions for (idx in indexes) { processExpression(idx) val lastIndex = idx == indexes.last() val anchor = if (lastIndex) KotlinExpressionAnchor(expr) else null val expectedType = if (lastIndex) expr.getKotlinType()?.toDfType() ?: DfType.TOP else DfType.TOP var indexType = idx.getKotlinType() val constructor = indexType?.constructor as? IntegerLiteralTypeConstructor if (constructor != null) { indexType = constructor.getApproximatedType() } if (indexType == null || !indexType.fqNameEquals("kotlin.Int")) { if (lastIndex && storedValue != null) { processExpression(storedValue) addInstruction(PopInstruction()) } addInstruction(EvalUnknownInstruction(anchor, 2, expectedType)) addInstruction(FlushFieldsInstruction()) continue } if (curType != null && KotlinBuiltIns.isArrayOrPrimitiveArray(curType)) { if (indexType.canBeNull()) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } val transfer = trapTracker.maybeTransferValue("kotlin.IndexOutOfBoundsException") val elementType = expr.builtIns.getArrayElementType(curType) if (lastIndex && storedValue != null) { processExpression(storedValue) addImplicitConversion(storedValue, storedValue.getKotlinType(), curType.getArrayElementType()) addInstruction(ArrayStoreInstruction(anchor, KotlinArrayIndexProblem(SpecialField.ARRAY_LENGTH, idx), transfer, null)) } else { addInstruction(ArrayAccessInstruction(anchor, KotlinArrayIndexProblem(SpecialField.ARRAY_LENGTH, idx), transfer, null)) addImplicitConversion(expr, curType.getArrayElementType(), elementType) } curType = elementType } else { if (KotlinBuiltIns.isString(kotlinType)) { if (indexType.canBeNull()) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } val transfer = trapTracker.maybeTransferValue("kotlin.IndexOutOfBoundsException") addInstruction(EnsureIndexInBoundsInstruction(KotlinArrayIndexProblem(SpecialField.STRING_LENGTH, idx), transfer)) if (lastIndex && storedValue != null) { processExpression(storedValue) addInstruction(PopInstruction()) } addInstruction(PushValueInstruction(DfTypes.typedObject(PsiType.CHAR, Nullability.UNKNOWN), anchor)) } else if (kotlinType != null && (KotlinBuiltIns.isListOrNullableList(kotlinType) || kotlinType.supertypes().any { type -> KotlinBuiltIns.isListOrNullableList(type) })) { if (indexType.canBeNull()) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } val transfer = trapTracker.maybeTransferValue("kotlin.IndexOutOfBoundsException") addInstruction(EnsureIndexInBoundsInstruction(KotlinArrayIndexProblem(SpecialField.COLLECTION_SIZE, idx), transfer)) if (lastIndex && storedValue != null) { processExpression(storedValue) addInstruction(PopInstruction()) } pushUnknown() } else { if (lastIndex && storedValue != null) { processExpression(storedValue) addInstruction(PopInstruction()) } addInstruction(EvalUnknownInstruction(anchor, 2, expectedType)) addInstruction(FlushFieldsInstruction()) } } } } private fun processIsExpression(expr: KtIsExpression) { processExpression(expr.leftHandSide) val type = getTypeCheckDfType(expr.typeReference) if (type == DfType.TOP) { pushUnknown() } else { addInstruction(PushValueInstruction(type)) if (expr.isNegated) { addInstruction(InstanceofInstruction(null, false)) addInstruction(NotInstruction(KotlinExpressionAnchor(expr))) } else { addInstruction(InstanceofInstruction(KotlinExpressionAnchor(expr), false)) } } } private fun processStringTemplate(expr: KtStringTemplateExpression) { var first = true val entries = expr.entries if (entries.isEmpty()) { addInstruction(PushValueInstruction(DfTypes.referenceConstant("", stringType))) return } val lastEntry = entries.last() for (entry in entries) { when (entry) { is KtEscapeStringTemplateEntry -> addInstruction(PushValueInstruction(DfTypes.referenceConstant(entry.unescapedValue, stringType))) is KtLiteralStringTemplateEntry -> addInstruction(PushValueInstruction(DfTypes.referenceConstant(entry.text, stringType))) is KtStringTemplateEntryWithExpression -> processExpression(entry.expression) else -> pushUnknown() } if (!first) { val anchor = if (entry == lastEntry) KotlinExpressionAnchor(expr) else null addInstruction(StringConcatInstruction(anchor, stringType)) } first = false } if (entries.size == 1 && entries[0] !is KtLiteralStringTemplateEntry) { // Implicit toString conversion for "$myVar" string addInstruction(PushValueInstruction(DfTypes.referenceConstant("", stringType))) addInstruction(StringConcatInstruction(KotlinExpressionAnchor(expr), stringType)) } } private fun processLambda(expr: KtLambdaExpression) { val element = expr.bodyExpression if (element != null) { processEscapes(element) addInstruction(ClosureInstruction(listOf(element))) } pushUnknown() } private fun processEscapes(expr: KtExpression) { val vars = mutableSetOf<DfaVariableValue>() val existingVars = factory.values.asSequence() .filterIsInstance<DfaVariableValue>() .filter { v -> v.qualifier == null } .map { v -> v.descriptor } .filterIsInstance<KtVariableDescriptor>() .map { v -> v.variable } .toSet() PsiTreeUtil.processElements(expr, KtSimpleNameExpression::class.java) { ref -> val target = ref.mainReference.resolve() if (target != null && existingVars.contains(target)) { vars.addIfNotNull(KtVariableDescriptor.createFromSimpleName(factory, ref)) } return@processElements true } if (vars.isNotEmpty()) { addInstruction(EscapeInstruction(vars)) } } private fun processCallExpression(expr: KtCallExpression, qualifierOnStack: Boolean = false) { val call = expr.resolveToCall() var argCount: Int if (call != null) { argCount = pushResolvedCallArguments(call) } else { argCount = pushUnresolvedCallArguments(expr) } if (inlineKnownMethod(expr, argCount, qualifierOnStack)) return val lambda = getInlineableLambda(expr) if (lambda != null) { if (qualifierOnStack && inlineKnownLambdaCall(expr, lambda.lambda)) return val kind = getLambdaOccurrenceRange(expr, lambda.descriptor.original) inlineLambda(lambda.lambda, kind) } else { for (lambdaArg in expr.lambdaArguments) { processExpression(lambdaArg.getLambdaExpression()) argCount++ } } addCall(expr, argCount, qualifierOnStack) } private fun pushUnresolvedCallArguments(expr: KtCallExpression): Int { val args = expr.valueArgumentList?.arguments var argCount = 0 if (args != null) { for (arg: KtValueArgument in args) { val argExpr = arg.getArgumentExpression() if (argExpr != null) { processExpression(argExpr) argCount++ } } } return argCount } private fun pushResolvedCallArguments(call: ResolvedCall<out CallableDescriptor>): Int { val valueArguments = call.valueArguments var argCount = 0 for ((descriptor, valueArg) in valueArguments) { when (valueArg) { is VarargValueArgument -> { val arguments = valueArg.arguments val singleArg = arguments.singleOrNull() if (singleArg?.getSpreadElement() != null) { processExpression(singleArg.getArgumentExpression()) } else { for (arg in arguments) { processExpression(arg.getArgumentExpression()) } addInstruction(FoldArrayInstruction(null, descriptor.type.toDfType(), arguments.size)) } argCount++ } is ExpressionValueArgument -> { val valueArgument = valueArg.valueArgument if (valueArgument !is KtLambdaArgument) { processExpression(valueArgument?.getArgumentExpression()) argCount++ } } else -> { pushUnknown() argCount++ } } } return argCount } private fun inlineKnownMethod(expr: KtCallExpression, argCount: Int, qualifierOnStack: Boolean): Boolean { if (argCount == 0 && qualifierOnStack) { val descriptor = expr.resolveToCall()?.resultingDescriptor ?: return false val name = descriptor.name.asString() if (name == "isEmpty" || name == "isNotEmpty") { val containingDeclaration = descriptor.containingDeclaration val containingPackage = if (containingDeclaration is PackageFragmentDescriptor) containingDeclaration.fqName else (containingDeclaration as? ClassDescriptor)?.containingPackage() if (containingPackage?.asString() == "kotlin.collections") { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.COLLECTION_SIZE)) addInstruction(PushValueInstruction(DfTypes.intValue(0))) addInstruction( BooleanBinaryInstruction( if (name == "isEmpty") RelationType.EQ else RelationType.NE, false, KotlinExpressionAnchor(expr) ) ) val kotlinType = expr.getKotlinType() if (kotlinType?.isMarkedNullable == true) { addInstruction(WrapDerivedVariableInstruction(kotlinType.toDfType(), SpecialField.UNBOX)) } return true } } } return false } private fun inlineKnownLambdaCall(expr: KtCallExpression, lambda: KtLambdaExpression): Boolean { // TODO: this-binding methods (apply, run) // TODO: non-qualified methods (run, repeat) // TODO: collection methods (forEach, map, etc.) val resolvedCall = expr.resolveToCall() ?: return false val descriptor = resolvedCall.resultingDescriptor val packageFragment = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false val bodyExpression = lambda.bodyExpression val receiver = (expr.parent as? KtQualifiedExpression)?.receiverExpression if (packageFragment.fqName.asString() == "kotlin" && resolvedCall.valueArguments.size == 1) { val name = descriptor.name.asString() if (name == "let" || name == "also" || name == "takeIf" || name == "takeUnless") { val parameter = KtVariableDescriptor.getSingleLambdaParameter(factory, lambda) ?: return false // qualifier is on stack val receiverType = receiver?.getKotlinType() val argType = if (expr.parent is KtSafeQualifiedExpression) receiverType?.makeNotNullable() else receiverType addImplicitConversion(receiver, argType) addInstruction(JvmAssignmentInstruction(null, parameter)) when (name) { "let" -> { addInstruction(PopInstruction()) val lambdaResultType = lambda.resolveType()?.getReturnTypeFromFunctionType() val result = flow.createTempVariable(lambdaResultType.toDfType()) inlinedBlock(lambda) { processExpression(bodyExpression) flow.finishElement(lambda.functionLiteral) addInstruction(JvmAssignmentInstruction(null, result)) addInstruction(PopInstruction()) } addInstruction(JvmPushInstruction(result, null)) addImplicitConversion(expr, lambdaResultType, expr.getKotlinType()) } "also" -> { inlinedBlock(lambda) { processExpression(bodyExpression) flow.finishElement(lambda.functionLiteral) addInstruction(PopInstruction()) } addImplicitConversion(receiver, argType, expr.getKotlinType()) addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr))) } "takeIf", "takeUnless" -> { val result = flow.createTempVariable(DfTypes.BOOLEAN) inlinedBlock(lambda) { processExpression(bodyExpression) flow.finishElement(lambda.functionLiteral) addInstruction(JvmAssignmentInstruction(null, result)) addInstruction(PopInstruction()) } addInstruction(JvmPushInstruction(result, null)) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.booleanValue(name == "takeIf"))) addInstruction(PopInstruction()) addInstruction(PushValueInstruction(DfTypes.NULL)) val endOffset = DeferredOffset() addInstruction(GotoInstruction(endOffset)) setOffset(offset) addImplicitConversion(receiver, argType, expr.getKotlinType()) setOffset(endOffset) } } addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr))) return true } } return false } private fun getLambdaOccurrenceRange(expr: KtCallExpression, descriptor: ValueParameterDescriptor): EventOccurrencesRange { val contractDescription = expr.resolveToCall()?.resultingDescriptor?.getUserData(ContractProviderKey)?.getContractDescription() if (contractDescription != null) { val callEffect = contractDescription.effects .singleOrNull { e -> e is CallsEffectDeclaration && e.variableReference.descriptor == descriptor } as? CallsEffectDeclaration if (callEffect != null) { return callEffect.kind } } return EventOccurrencesRange.UNKNOWN } private fun inlineLambda(lambda: KtLambdaExpression, kind: EventOccurrencesRange) { /* We encode unknown call with inlineable lambda as unknownCode() while(condition1) { if(condition2) { lambda() } unknownCode() } */ addInstruction(FlushFieldsInstruction()) val offset = ControlFlow.FixedOffset(flow.instructionCount) val endOffset = DeferredOffset() if (kind != EventOccurrencesRange.EXACTLY_ONCE && kind != EventOccurrencesRange.MORE_THAN_ONCE && kind != EventOccurrencesRange.AT_LEAST_ONCE) { pushUnknown() addInstruction(ConditionalGotoInstruction(endOffset, DfTypes.TRUE)) } inlinedBlock(lambda) { val functionLiteral = lambda.functionLiteral val bodyExpression = lambda.bodyExpression if (bodyExpression != null) { val singleParameter = KtVariableDescriptor.getSingleLambdaParameter(factory, lambda) if (singleParameter != null) { addInstruction(FlushVariableInstruction(singleParameter)) } else { for (parameter in lambda.valueParameters) { flushParameter(parameter) } } } processExpression(bodyExpression) flow.finishElement(functionLiteral) addInstruction(PopInstruction()) } setOffset(endOffset) addInstruction(FlushFieldsInstruction()) if (kind != EventOccurrencesRange.AT_MOST_ONCE && kind != EventOccurrencesRange.EXACTLY_ONCE) { pushUnknown() addInstruction(ConditionalGotoInstruction(offset, DfTypes.TRUE)) } } private inline fun inlinedBlock(element: KtElement, fn : () -> Unit) { // Transfer value is pushed to avoid emptying stack beyond this point trapTracker.pushTrap(InsideInlinedBlockTrap(element)) addInstruction(JvmPushInstruction(factory.controlTransfer(DfaControlTransferValue.RETURN_TRANSFER, FList.emptyList()), null)) fn() trapTracker.popTrap(InsideInlinedBlockTrap::class.java) // Pop transfer value addInstruction(PopInstruction()) } private fun addCall(expr: KtExpression, args: Int, qualifierOnStack: Boolean = false) { val transfer = trapTracker.maybeTransferValue("kotlin.Throwable") addInstruction(KotlinFunctionCallInstruction(expr, args, qualifierOnStack, transfer)) } private fun processQualifiedReferenceExpression(expr: KtQualifiedExpression) { val receiver = expr.receiverExpression processExpression(receiver) val offset = DeferredOffset() if (expr is KtSafeQualifiedExpression) { addInstruction(DupInstruction()) addInstruction(ConditionalGotoInstruction(offset, DfTypes.NULL)) } val selector = expr.selectorExpression if (!pushJavaClassField(receiver, selector, expr)) { val specialField = findSpecialField(expr) if (specialField != null) { addInstruction(UnwrapDerivedVariableInstruction(specialField)) if (expr is KtSafeQualifiedExpression) { addInstruction(WrapDerivedVariableInstruction(expr.getKotlinType().toDfType(), SpecialField.UNBOX)) } } else { when (selector) { is KtCallExpression -> processCallExpression(selector, true) is KtSimpleNameExpression -> processReferenceExpression(selector, true) else -> { addInstruction(PopInstruction()) processExpression(selector) } } } addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr))) } if (expr is KtSafeQualifiedExpression) { val endOffset = DeferredOffset() addInstruction(GotoInstruction(endOffset)) setOffset(offset) addInstruction(PopInstruction()) addInstruction(PushValueInstruction(DfTypes.NULL, KotlinExpressionAnchor(expr))) setOffset(endOffset) } } private fun pushJavaClassField(receiver: KtExpression, selector: KtExpression?, expr: KtQualifiedExpression): Boolean { if (selector == null || !selector.textMatches("java")) return false if (!receiver.getKotlinType().fqNameEquals("kotlin.reflect.KClass")) return false val kotlinType = expr.getKotlinType() ?: return false val classType = TypeConstraint.fromDfType(kotlinType.toDfType()) if (!classType.isExact(CommonClassNames.JAVA_LANG_CLASS)) return false addInstruction(KotlinClassToJavaClassInstruction(KotlinExpressionAnchor(expr), classType)) return true } private fun findSpecialField(type: KotlinType?): SpecialField? { type ?: return null return when { type.isEnum() -> SpecialField.ENUM_ORDINAL KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type) -> SpecialField.ARRAY_LENGTH KotlinBuiltIns.isCollectionOrNullableCollection(type) || KotlinBuiltIns.isMapOrNullableMap(type) || type.supertypes().any { st -> KotlinBuiltIns.isCollectionOrNullableCollection(st) || KotlinBuiltIns.isMapOrNullableMap(st)} -> SpecialField.COLLECTION_SIZE KotlinBuiltIns.isStringOrNullableString(type) -> SpecialField.STRING_LENGTH else -> null } } private fun findSpecialField(expr: KtQualifiedExpression): SpecialField? { val selector = expr.selectorExpression ?: return null val receiver = expr.receiverExpression val selectorText = selector.text if (selectorText != "size" && selectorText != "length" && selectorText != "ordinal") return null val field = findSpecialField(receiver.getKotlinType()) ?: return null val expectedFieldName = if (field == SpecialField.ARRAY_LENGTH) "size" else field.toString() if (selectorText != expectedFieldName) return null return field } private fun processPrefixExpression(expr: KtPrefixExpression) { val operand = expr.baseExpression processExpression(operand) val anchor = KotlinExpressionAnchor(expr) if (operand != null) { val dfType = operand.getKotlinType().toDfType() val dfVar = KtVariableDescriptor.createFromQualified(factory, operand) val ref = expr.operationReference.text if (dfType is DfIntegralType) { when (ref) { "++", "--" -> { if (dfVar != null) { addInstruction(PushValueInstruction(dfType.meetRange(LongRangeSet.point(1)))) addInstruction(NumericBinaryInstruction(if (ref == "++") LongRangeBinOp.PLUS else LongRangeBinOp.MINUS, null)) addInstruction(JvmAssignmentInstruction(anchor, dfVar)) return } } "+" -> { return } "-" -> { addInstruction(PushValueInstruction(dfType.meetRange(LongRangeSet.point(0)))) addInstruction(SwapInstruction()) addInstruction(NumericBinaryInstruction(LongRangeBinOp.MINUS, anchor)) return } } } if (dfType is DfBooleanType && ref == "!") { addInstruction(NotInstruction(anchor)) return } if (dfVar != null && (ref == "++" || ref == "--")) { // Custom inc/dec may update the variable addInstruction(FlushVariableInstruction(dfVar)) } } addInstruction(EvalUnknownInstruction(anchor, 1, expr.getKotlinType()?.toDfType() ?: DfType.TOP)) } private fun processPostfixExpression(expr: KtPostfixExpression) { val operand = expr.baseExpression processExpression(operand) val anchor = KotlinExpressionAnchor(expr) val ref = expr.operationReference.text if (ref == "++" || ref == "--") { if (operand != null) { val dfType = operand.getKotlinType().toDfType() val dfVar = KtVariableDescriptor.createFromQualified(factory, operand) if (dfVar != null) { if (dfType is DfIntegralType) { addInstruction(DupInstruction()) addInstruction(PushValueInstruction(dfType.meetRange(LongRangeSet.point(1)))) addInstruction(NumericBinaryInstruction(if (ref == "++") LongRangeBinOp.PLUS else LongRangeBinOp.MINUS, null)) addInstruction(JvmAssignmentInstruction(anchor, dfVar)) addInstruction(PopInstruction()) } else { // Custom inc/dec may update the variable addInstruction(FlushVariableInstruction(dfVar)) } } else { // Unknown value updated addInstruction(FlushFieldsInstruction()) } } } else if (ref == "!!") { val transfer: DfaControlTransferValue? = trapTracker.maybeTransferValue("kotlin.NullPointerException") val operandType = operand?.getKotlinType() if (operandType?.canBeNull() == true) { addInstruction(EnsureInstruction(KotlinNullCheckProblem(expr), RelationType.NE, DfTypes.NULL, transfer)) // Probably unbox addImplicitConversion(expr, operandType, expr.getKotlinType()) } } else { addInstruction(EvalUnknownInstruction(anchor, 1, expr.getKotlinType()?.toDfType() ?: DfType.TOP)) } } private fun processDoWhileExpression(expr: KtDoWhileExpression) { inlinedBlock(expr) { val offset = ControlFlow.FixedOffset(flow.instructionCount) processExpression(expr.body) addInstruction(PopInstruction()) processExpression(expr.condition) addInstruction(ConditionalGotoInstruction(offset, DfTypes.TRUE)) flow.finishElement(expr) } pushUnknown() addInstruction(FinishElementInstruction(expr)) } private fun processWhileExpression(expr: KtWhileExpression) { inlinedBlock(expr) { val startOffset = ControlFlow.FixedOffset(flow.instructionCount) val condition = expr.condition processExpression(condition) val endOffset = DeferredOffset() addInstruction(ConditionalGotoInstruction(endOffset, DfTypes.FALSE, condition)) processExpression(expr.body) addInstruction(PopInstruction()) addInstruction(GotoInstruction(startOffset)) setOffset(endOffset) flow.finishElement(expr) } pushUnknown() addInstruction(FinishElementInstruction(expr)) } private fun processForExpression(expr: KtForExpression) { inlinedBlock(expr) { val parameter = expr.loopParameter if (parameter == null) { broken = true return@inlinedBlock } val parameterVar = factory.varFactory.createVariableValue(KtVariableDescriptor(parameter)) val parameterType = parameter.type() val pushLoopCondition = processForRange(expr, parameterVar, parameterType) val startOffset = ControlFlow.FixedOffset(flow.instructionCount) val endOffset = DeferredOffset() flushParameter(parameter) pushLoopCondition() addInstruction(ConditionalGotoInstruction(endOffset, DfTypes.FALSE)) processExpression(expr.body) addInstruction(PopInstruction()) addInstruction(GotoInstruction(startOffset)) setOffset(endOffset) flow.finishElement(expr) } pushUnknown() addInstruction(FinishElementInstruction(expr)) } private fun flushParameter(parameter: KtParameter) { val destructuringDeclaration = parameter.destructuringDeclaration if (destructuringDeclaration != null) { for (entry in destructuringDeclaration.entries) { addInstruction(FlushVariableInstruction(factory.varFactory.createVariableValue(KtVariableDescriptor(entry)))) } } else { addInstruction(FlushVariableInstruction(factory.varFactory.createVariableValue(KtVariableDescriptor(parameter)))) } } private fun processForRange(expr: KtForExpression, parameterVar: DfaVariableValue, parameterType: KotlinType?): () -> Unit { val range = expr.loopRange if (parameterVar.dfType is DfIntegralType) { when (range) { is KtDotQualifiedExpression -> { val selector = range.selectorExpression val receiver = range.receiverExpression if (selector != null && selector.textMatches("indices")) { val kotlinType = receiver.getKotlinType() if (kotlinType != null && !kotlinType.canBeNull()) { val dfVar = KtVariableDescriptor.createFromSimpleName(factory, receiver) if (dfVar != null) { val sf = when { KotlinBuiltIns.isCollectionOrNullableCollection(kotlinType) || kotlinType.supertypes().any { st -> KotlinBuiltIns.isCollectionOrNullableCollection(st) } -> SpecialField.COLLECTION_SIZE KotlinBuiltIns.isArrayOrPrimitiveArray(kotlinType) -> SpecialField.ARRAY_LENGTH else -> null } if (sf != null) { val size = sf.createValue(factory, dfVar) return rangeFunction(expr, parameterVar, factory.fromDfType(DfTypes.intValue(0)), RelationType.GE, size, RelationType.LT) } } } } } is KtBinaryExpression -> { val ref = range.operationReference.text val (leftRelation, rightRelation) = when (ref) { ".." -> RelationType.GE to RelationType.LE "until" -> RelationType.GE to RelationType.LT "downTo" -> RelationType.LE to RelationType.GE else -> null to null } if (leftRelation != null && rightRelation != null) { val left = range.left val right = range.right val leftType = left?.getKotlinType() val rightType = right?.getKotlinType() if (leftType.toDfType() is DfIntegralType && rightType.toDfType() is DfIntegralType) { processExpression(left) val leftVar = flow.createTempVariable(parameterVar.dfType) addImplicitConversion(left, parameterType) addInstruction(JvmAssignmentInstruction(null, leftVar)) addInstruction(PopInstruction()) processExpression(right) val rightVar = flow.createTempVariable(parameterVar.dfType) addImplicitConversion(right, parameterType) addInstruction(JvmAssignmentInstruction(null, rightVar)) addInstruction(PopInstruction()) return rangeFunction(expr, parameterVar, leftVar, leftRelation, rightVar, rightRelation) } } } } } processExpression(range) if (range != null) { val kotlinType = range.getKotlinType() val lengthField = findSpecialField(kotlinType) if (lengthField != null) { val collectionVar = flow.createTempVariable(kotlinType.toDfType()) addInstruction(JvmAssignmentInstruction(null, collectionVar)) addInstruction(PopInstruction()) return { addInstruction(JvmPushInstruction(lengthField.createValue(factory, collectionVar), null)) addInstruction(PushValueInstruction(DfTypes.intValue(0))) addInstruction(BooleanBinaryInstruction(RelationType.GT, false, null)) pushUnknown() addInstruction(BooleanAndOrInstruction(false, KotlinForVisitedAnchor(expr))) } } } addInstruction(PopInstruction()) return { pushUnknown() } } private fun rangeFunction( expr: KtForExpression, parameterVar: DfaVariableValue, leftVar: DfaValue, leftRelation: RelationType, rightVar: DfaValue, rightRelation: RelationType ): () -> Unit = { val forAnchor = KotlinForVisitedAnchor(expr) addInstruction(JvmPushInstruction(parameterVar, null)) addInstruction(JvmPushInstruction(leftVar, null)) addInstruction(BooleanBinaryInstruction(leftRelation, false, null)) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.FALSE)) addInstruction(JvmPushInstruction(parameterVar, null)) addInstruction(JvmPushInstruction(rightVar, null)) addInstruction(BooleanBinaryInstruction(rightRelation, false, forAnchor)) val finalOffset = DeferredOffset() addInstruction(GotoInstruction(finalOffset)) setOffset(offset) addInstruction(PushValueInstruction(DfTypes.FALSE, forAnchor)) setOffset(finalOffset) } private fun processBlock(expr: KtBlockExpression) { val statements = expr.statements if (statements.isEmpty()) { pushUnknown() } else { for (child in statements) { processExpression(child) if (child != statements.last()) { addInstruction(PopInstruction()) } if (broken) return } addInstruction(FinishElementInstruction(expr)) } } private fun processDeclaration(variable: KtProperty) { val initializer = variable.initializer if (initializer == null) { pushUnknown() return } val dfaVariable = factory.varFactory.createVariableValue(KtVariableDescriptor(variable)) if (variable.isLocal && !variable.isVar && variable.type()?.isBoolean() == true) { // Boolean true/false constant: do not track; might be used as a feature knob or explanatory variable if (initializer.node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT) { pushUnknown() return } } processExpression(initializer) addImplicitConversion(initializer, variable.type()) addInstruction(JvmAssignmentInstruction(KotlinExpressionAnchor(variable), dfaVariable)) } private fun processReturnExpression(expr: KtReturnExpression) { val returnedExpression = expr.returnedExpression processExpression(returnedExpression) if (expr.labeledExpression != null) { val targetFunction = expr.getTargetFunction(expr.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL)) if (targetFunction != null && PsiTreeUtil.isAncestor(context, targetFunction, true)) { val transfer: InstructionTransfer if (returnedExpression != null) { val retVar = flow.createTempVariable(returnedExpression.getKotlinType().toDfType()) addInstruction(JvmAssignmentInstruction(null, retVar)) transfer = createTransfer(targetFunction, targetFunction, retVar) } else { transfer = createTransfer(targetFunction, targetFunction, factory.unknown) } addInstruction(ControlTransferInstruction(factory.controlTransfer(transfer, trapTracker.getTrapsInsideElement(targetFunction)))) return } } addInstruction(ReturnInstruction(factory, trapTracker.trapStack(), expr)) } private fun controlTransfer(target: TransferTarget, traps: FList<Trap>) { addInstruction(ControlTransferInstruction(factory.controlTransfer(target, traps))) } private fun createTransfer(exitedStatement: PsiElement, blockToFlush: PsiElement, resultValue: DfaValue, exitBlock: Boolean = false): InstructionTransfer { val varsToFlush = PsiTreeUtil.findChildrenOfType( blockToFlush, KtProperty::class.java ).map { property -> KtVariableDescriptor(property) } return KotlinTransferTarget(resultValue, flow.getEndOffset(exitedStatement), exitBlock, varsToFlush) } private class KotlinTransferTarget( val resultValue: DfaValue, val offset: ControlFlowOffset, val exitBlock: Boolean, val varsToFlush: List<KtVariableDescriptor> ) : InstructionTransfer(offset, varsToFlush) { override fun dispatch(state: DfaMemoryState, interpreter: DataFlowInterpreter): MutableList<DfaInstructionState> { if (exitBlock) { val value = state.pop() check(!(value !is DfaControlTransferValue || value.target !== DfaControlTransferValue.RETURN_TRANSFER)) { "Expected control transfer on stack; got $value" } } state.push(resultValue) return super.dispatch(state, interpreter) } override fun bindToFactory(factory: DfaValueFactory): TransferTarget { return KotlinTransferTarget(resultValue.bindToFactory(factory), offset, exitBlock, varsToFlush) } override fun toString(): String { return super.toString() + "; result = " + resultValue } } private fun processLabeledJumpExpression(expr: KtExpressionWithLabel) { val targetLoop = expr.targetLoop() if (targetLoop == null || !PsiTreeUtil.isAncestor(context, targetLoop, false)) { addInstruction(ControlTransferInstruction(trapTracker.transferValue(DfaControlTransferValue.RETURN_TRANSFER))) } else { val body = if (expr is KtBreakExpression) targetLoop else targetLoop.body!! val transfer = factory.controlTransfer(createTransfer(body, body, factory.unknown), trapTracker.getTrapsInsideElement(body)) addInstruction(ControlTransferInstruction(transfer)) } } private fun processThrowExpression(expr: KtThrowExpression) { val exception = expr.thrownExpression processExpression(exception) addInstruction(PopInstruction()) if (exception != null) { val constraint = TypeConstraint.fromDfType(exception.getKotlinType().toDfType()) if (constraint != TypeConstraints.TOP) { val kind = ExceptionTransfer(constraint) addInstruction(ThrowInstruction(trapTracker.transferValue(kind), expr)) return } } pushUnknown() } private fun processReferenceExpression(expr: KtSimpleNameExpression, qualifierOnStack: Boolean = false) { val dfVar = KtVariableDescriptor.createFromSimpleName(factory, expr) if (dfVar != null) { if (qualifierOnStack) { addInstruction(PopInstruction()) } addInstruction(JvmPushInstruction(dfVar, KotlinExpressionAnchor(expr))) var realExpr: KtExpression = expr while (true) { val parent = realExpr.parent if (parent is KtQualifiedExpression && parent.selectorExpression == realExpr) { realExpr = parent } else break } val exprType = realExpr.getKotlinType() val declaredType = when (val desc = dfVar.descriptor) { is KtVariableDescriptor -> desc.variable.type() is KtItVariableDescriptor -> desc.type else -> null } addImplicitConversion(expr, declaredType, exprType) return } var topExpr: KtExpression = expr while ((topExpr.parent as? KtQualifiedExpression)?.selectorExpression === topExpr) { topExpr = topExpr.parent as KtExpression } val target = expr.mainReference.resolve() val value: DfType? = getReferenceValue(topExpr, target) if (value != null) { if (qualifierOnStack) { addInstruction(PopInstruction()) } addInstruction(PushValueInstruction(value, KotlinExpressionAnchor(expr))) } else { addCall(expr, 0, qualifierOnStack) } } private fun getReferenceValue(expr: KtExpression, target: PsiElement?): DfType? { return when (target) { // Companion object qualifier is KtObjectDeclaration -> DfType.TOP is PsiClass -> DfType.TOP is PsiVariable -> { val constantValue = target.computeConstantValue() val dfType = expr.getKotlinType().toDfType() if (constantValue != null && constantValue !is Boolean && dfType != DfType.TOP) { DfTypes.constant(constantValue, dfType) } else { dfType } } is KtEnumEntry -> { val ktClass = target.containingClass() val enumConstant = ktClass?.toLightClass()?.fields?.firstOrNull { f -> f is PsiEnumConstant && f.name == target.name } val dfType = expr.getKotlinType().toDfType() if (enumConstant != null && dfType is DfReferenceType) { DfTypes.constant(enumConstant, dfType) } else { DfType.TOP } } else -> null } } private fun processConstantExpression(expr: KtConstantExpression) { addInstruction(PushValueInstruction(getConstant(expr), KotlinExpressionAnchor(expr))) } private fun pushUnknown() { addInstruction(PushValueInstruction(DfType.TOP)) } private fun processBinaryExpression(expr: KtBinaryExpression) { val token = expr.operationToken val relation = relationFromToken(token) if (relation != null) { processBinaryRelationExpression(expr, relation, token == KtTokens.EXCLEQ || token == KtTokens.EQEQ) return } val leftKtType = expr.left?.getKotlinType() if (token === KtTokens.PLUS && (KotlinBuiltIns.isString(leftKtType) || KotlinBuiltIns.isString(expr.right?.getKotlinType()))) { processExpression(expr.left) processExpression(expr.right) addInstruction(StringConcatInstruction(KotlinExpressionAnchor(expr), stringType)) return } if (leftKtType?.toDfType() is DfIntegralType) { val mathOp = mathOpFromToken(expr.operationReference) if (mathOp != null) { processMathExpression(expr, mathOp) return } } if (token === KtTokens.ANDAND || token === KtTokens.OROR) { processShortCircuitExpression(expr, token === KtTokens.ANDAND) return } if (ASSIGNMENT_TOKENS.contains(token)) { processAssignmentExpression(expr) return } if (token === KtTokens.ELVIS) { processNullSafeOperator(expr) return } if (token === KtTokens.IN_KEYWORD) { val left = expr.left processExpression(left) processInCheck(left?.getKotlinType(), expr.right, KotlinExpressionAnchor(expr), false) return } if (token === KtTokens.NOT_IN) { val left = expr.left processExpression(left) processInCheck(left?.getKotlinType(), expr.right, KotlinExpressionAnchor(expr), true) return } processExpression(expr.left) processExpression(expr.right) addCall(expr, 2) } private fun processInCheck(kotlinType: KotlinType?, range: KtExpression?, anchor: KotlinAnchor, negated: Boolean) { if (kotlinType != null && (kotlinType.isInt() || kotlinType.isLong())) { if (range is KtBinaryExpression) { val ref = range.operationReference.text if (ref == ".." || ref == "until") { val left = range.left val right = range.right val leftType = left?.getKotlinType() val rightType = right?.getKotlinType() if (leftType.toDfType() is DfIntegralType && rightType.toDfType() is DfIntegralType) { processExpression(left) addImplicitConversion(left, kotlinType) processExpression(right) addImplicitConversion(right, kotlinType) addInstruction(SpliceInstruction(3, 2, 0, 2, 1)) addInstruction(BooleanBinaryInstruction(RelationType.GE, false, null)) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.FALSE)) var relationType = if (ref == "until") RelationType.LT else RelationType.LE if (negated) { relationType = relationType.negated } addInstruction(BooleanBinaryInstruction(relationType, false, anchor)) val finalOffset = DeferredOffset() addInstruction(GotoInstruction(finalOffset)) setOffset(offset) addInstruction(SpliceInstruction(2)) addInstruction(PushValueInstruction(if (negated) DfTypes.TRUE else DfTypes.FALSE, anchor)) setOffset(finalOffset) return } } } } processExpression(range) addInstruction(EvalUnknownInstruction(anchor, 2, DfTypes.BOOLEAN)) addInstruction(FlushFieldsInstruction()) } private fun processNullSafeOperator(expr: KtBinaryExpression) { val left = expr.left processExpression(left) addInstruction(DupInstruction()) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.NULL)) val endOffset = DeferredOffset() addImplicitConversion(expr, left?.getKotlinType(), expr.getKotlinType()) addInstruction(GotoInstruction(endOffset)) setOffset(offset) addInstruction(PopInstruction()) processExpression(expr.right) setOffset(endOffset) addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr))) } private fun processAssignmentExpression(expr: KtBinaryExpression) { val left = expr.left val right = expr.right val token = expr.operationToken if (left is KtArrayAccessExpression && token == KtTokens.EQ) { // TODO: compound-assignment for arrays processArrayAccess(left, right) return } val dfVar = KtVariableDescriptor.createFromQualified(factory, left) val leftType = left?.getKotlinType() val rightType = right?.getKotlinType() if (dfVar == null) { processExpression(left) addInstruction(PopInstruction()) processExpression(right) addImplicitConversion(right, leftType) // TODO: support safe-qualified assignments addInstruction(FlushFieldsInstruction()) return } val mathOp = mathOpFromAssignmentToken(token) if (mathOp != null) { val resultType = balanceType(leftType, rightType) processExpression(left) addImplicitConversion(left, resultType) processExpression(right) addImplicitConversion(right, resultType) addInstruction(NumericBinaryInstruction(mathOp, KotlinExpressionAnchor(expr))) addImplicitConversion(right, resultType, leftType) } else { processExpression(right) addImplicitConversion(right, leftType) } // TODO: support overloaded assignment addInstruction(JvmAssignmentInstruction(KotlinExpressionAnchor(expr), dfVar)) addInstruction(FinishElementInstruction(expr)) } private fun processShortCircuitExpression(expr: KtBinaryExpression, and: Boolean) { val left = expr.left val right = expr.right val endOffset = DeferredOffset() processExpression(left) val nextOffset = DeferredOffset() addInstruction(ConditionalGotoInstruction(nextOffset, DfTypes.booleanValue(and), left)) val anchor = KotlinExpressionAnchor(expr) addInstruction(PushValueInstruction(DfTypes.booleanValue(!and), anchor)) addInstruction(GotoInstruction(endOffset)) setOffset(nextOffset) addInstruction(FinishElementInstruction(null)) processExpression(right) setOffset(endOffset) addInstruction(ResultOfInstruction(anchor)) } private fun processMathExpression(expr: KtBinaryExpression, mathOp: LongRangeBinOp) { val left = expr.left val right = expr.right val resultType = expr.getKotlinType() processExpression(left) addImplicitConversion(left, resultType) processExpression(right) if (!mathOp.isShift) { addImplicitConversion(right, resultType) } if ((mathOp == LongRangeBinOp.DIV || mathOp == LongRangeBinOp.MOD) && resultType != null && (resultType.isLong() || resultType.isInt())) { val transfer: DfaControlTransferValue? = trapTracker.maybeTransferValue("kotlin.ArithmeticException") val zero = if (resultType.isLong()) DfTypes.longValue(0) else DfTypes.intValue(0) addInstruction(EnsureInstruction(null, RelationType.NE, zero, transfer, true)) } addInstruction(NumericBinaryInstruction(mathOp, KotlinExpressionAnchor(expr))) } private fun addImplicitConversion(expression: KtExpression?, expectedType: KotlinType?) { addImplicitConversion(expression, expression?.getKotlinType(), expectedType) } private fun addImplicitConversion(expression: KtExpression?, actualType: KotlinType?, expectedType: KotlinType?) { expression ?: return actualType ?: return expectedType ?: return if (actualType == expectedType) return val actualDfType = actualType.toDfType() val expectedDfType = expectedType.toDfType() if (actualDfType !is DfPrimitiveType && expectedDfType is DfPrimitiveType) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } else if (expectedDfType !is DfPrimitiveType && actualDfType is DfPrimitiveType) { val dfType = actualType.makeNullable().toDfType().meet(DfTypes.NOT_NULL_OBJECT) addInstruction(WrapDerivedVariableInstruction(expectedType.toDfType().meet(dfType), SpecialField.UNBOX)) } if (actualDfType is DfPrimitiveType && expectedDfType is DfPrimitiveType) { addInstruction(PrimitiveConversionInstruction(expectedType.toPsiPrimitiveType(), null)) } } private fun processBinaryRelationExpression( expr: KtBinaryExpression, relation: RelationType, forceEqualityByContent: Boolean ) { val left = expr.left val right = expr.right val leftType = left?.getKotlinType() val rightType = right?.getKotlinType() processExpression(left) val leftDfType = leftType.toDfType() val rightDfType = rightType.toDfType() if ((relation == RelationType.EQ || relation == RelationType.NE) || (leftDfType is DfPrimitiveType && rightDfType is DfPrimitiveType)) { val balancedType: KotlinType? = balanceType(leftType, rightType, forceEqualityByContent) addImplicitConversion(left, balancedType) processExpression(right) addImplicitConversion(right, balancedType) if (forceEqualityByContent && !mayCompareByContent(leftDfType, rightDfType)) { val transfer = trapTracker.maybeTransferValue("kotlin.Throwable") addInstruction(KotlinEqualityInstruction(expr, relation != RelationType.EQ, transfer)) } else { addInstruction(BooleanBinaryInstruction(relation, forceEqualityByContent, KotlinExpressionAnchor(expr))) } } else { val leftConstraint = TypeConstraint.fromDfType(leftDfType) val rightConstraint = TypeConstraint.fromDfType(rightDfType) if (leftConstraint.isEnum && rightConstraint.isEnum && leftConstraint.meet(rightConstraint) != TypeConstraints.BOTTOM) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.ENUM_ORDINAL)) processExpression(right) addInstruction(UnwrapDerivedVariableInstruction(SpecialField.ENUM_ORDINAL)) addInstruction(BooleanBinaryInstruction(relation, forceEqualityByContent, KotlinExpressionAnchor(expr))) } else if (leftConstraint.isExact(CommonClassNames.JAVA_LANG_STRING) && rightConstraint.isExact(CommonClassNames.JAVA_LANG_STRING)) { processExpression(right) addInstruction(BooleanBinaryInstruction(relation, forceEqualityByContent, KotlinExpressionAnchor(expr))) } else { // Overloaded >/>=/</<=: do not evaluate processExpression(right) addCall(expr, 2) } } } private fun mayCompareByContent(leftDfType: DfType, rightDfType: DfType): Boolean { if (leftDfType == DfTypes.NULL || rightDfType == DfTypes.NULL) return true if (leftDfType is DfPrimitiveType || rightDfType is DfPrimitiveType) return true val constraint = TypeConstraint.fromDfType(leftDfType) if (constraint.isComparedByEquals || constraint.isArray || constraint.isEnum) return true if (!constraint.isExact) return false val cls = PsiUtil.resolveClassInClassTypeOnly(constraint.getPsiType(factory.project)) ?: return false val equalsSignature = MethodSignatureUtil.createMethodSignature("equals", arrayOf(TypeUtils.getObjectType(context)), arrayOf(), PsiSubstitutor.EMPTY) val method = MethodSignatureUtil.findMethodBySignature(cls, equalsSignature, true) return method?.containingClass?.qualifiedName == CommonClassNames.JAVA_LANG_OBJECT } private fun balanceType(leftType: KotlinType?, rightType: KotlinType?, forceEqualityByContent: Boolean): KotlinType? = when { leftType == null || rightType == null -> null leftType.isNullableNothing() -> rightType.makeNullable() rightType.isNullableNothing() -> leftType.makeNullable() !forceEqualityByContent -> balanceType(leftType, rightType) leftType.isSubtypeOf(rightType) -> rightType rightType.isSubtypeOf(leftType) -> leftType else -> null } private fun balanceType(left: KotlinType?, right: KotlinType?): KotlinType? { if (left == null || right == null) return null if (left == right) return left if (left.canBeNull() && !right.canBeNull()) { return balanceType(left.makeNotNullable(), right) } if (!left.canBeNull() && right.canBeNull()) { return balanceType(left, right.makeNotNullable()) } if (left.isDouble()) return left if (right.isDouble()) return right if (left.isFloat()) return left if (right.isFloat()) return right if (left.isLong()) return left if (right.isLong()) return right // The 'null' means no balancing is necessary return null } private fun addInstruction(inst: Instruction) { flow.addInstruction(inst) } private fun setOffset(offset: DeferredOffset) { offset.setOffset(flow.instructionCount) } private fun processWhenExpression(expr: KtWhenExpression) { val subjectExpression = expr.subjectExpression val dfVar: DfaVariableValue? val kotlinType: KotlinType? if (subjectExpression == null) { dfVar = null kotlinType = null } else { processExpression(subjectExpression) val subjectVariable = expr.subjectVariable if (subjectVariable != null) { kotlinType = subjectVariable.type() dfVar = factory.varFactory.createVariableValue(KtVariableDescriptor(subjectVariable)) } else { kotlinType = subjectExpression.getKotlinType() dfVar = flow.createTempVariable(kotlinType.toDfType()) addInstruction(JvmAssignmentInstruction(null, dfVar)) } addInstruction(PopInstruction()) } val endOffset = DeferredOffset() for (entry in expr.entries) { if (entry.isElse) { processExpression(entry.expression) addInstruction(GotoInstruction(endOffset)) } else { val branchStart = DeferredOffset() for (condition in entry.conditions) { processWhenCondition(dfVar, kotlinType, condition) addInstruction(ConditionalGotoInstruction(branchStart, DfTypes.TRUE)) } val skipBranch = DeferredOffset() addInstruction(GotoInstruction(skipBranch)) setOffset(branchStart) processExpression(entry.expression) addInstruction(GotoInstruction(endOffset)) setOffset(skipBranch) } } pushUnknown() setOffset(endOffset) addInstruction(FinishElementInstruction(expr)) } private fun processWhenCondition(dfVar: DfaVariableValue?, dfVarType: KotlinType?, condition: KtWhenCondition) { when (condition) { is KtWhenConditionWithExpression -> { val expr = condition.expression processExpression(expr) val exprType = expr?.getKotlinType() if (dfVar != null) { val balancedType = balanceType(exprType, dfVarType, true) addImplicitConversion(expr, exprType, balancedType) addInstruction(JvmPushInstruction(dfVar, null)) addImplicitConversion(null, dfVarType, balancedType) addInstruction(BooleanBinaryInstruction(RelationType.EQ, true, KotlinWhenConditionAnchor(condition))) } else if (exprType?.canBeNull() == true) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } } is KtWhenConditionIsPattern -> { if (dfVar != null) { addInstruction(JvmPushInstruction(dfVar, null)) val type = getTypeCheckDfType(condition.typeReference) if (type == DfType.TOP) { pushUnknown() } else { addInstruction(PushValueInstruction(type)) if (condition.isNegated) { addInstruction(InstanceofInstruction(null, false)) addInstruction(NotInstruction(KotlinWhenConditionAnchor(condition))) } else { addInstruction(InstanceofInstruction(KotlinWhenConditionAnchor(condition), false)) } } } else { pushUnknown() } } is KtWhenConditionInRange -> { if (dfVar != null) { addInstruction(JvmPushInstruction(dfVar, null)) } else { pushUnknown() } processInCheck(dfVarType, condition.rangeExpression, KotlinWhenConditionAnchor(condition), condition.isNegated) } else -> broken = true } } private fun getTypeCheckDfType(typeReference: KtTypeReference?): DfType { if (typeReference == null) return DfType.TOP val kotlinType = typeReference.getAbbreviatedTypeOrType(typeReference.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL)) if (kotlinType == null || kotlinType.constructor.declarationDescriptor is TypeParameterDescriptor) return DfType.TOP if (kotlinType.isMarkedNullable) return kotlinType.toDfType() // makeNullable to convert primitive to boxed val dfType = kotlinType.makeNullable().toDfType().meet(DfTypes.NOT_NULL_OBJECT) return if (dfType is DfReferenceType) dfType.dropSpecialField() else dfType } private fun processIfExpression(ifExpression: KtIfExpression) { val condition = ifExpression.condition processExpression(condition) if (condition?.getKotlinType()?.canBeNull() == true) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } val skipThenOffset = DeferredOffset() val thenStatement = ifExpression.then val elseStatement = ifExpression.`else` val exprType = ifExpression.getKotlinType() addInstruction(ConditionalGotoInstruction(skipThenOffset, DfTypes.FALSE, condition)) addInstruction(FinishElementInstruction(null)) processExpression(thenStatement) addImplicitConversion(thenStatement, exprType) val skipElseOffset = DeferredOffset() addInstruction(GotoInstruction(skipElseOffset)) setOffset(skipThenOffset) addInstruction(FinishElementInstruction(null)) processExpression(elseStatement) addImplicitConversion(elseStatement, exprType) setOffset(skipElseOffset) addInstruction(FinishElementInstruction(ifExpression)) } companion object { private val LOG = logger<KtControlFlowBuilder>() private val ASSIGNMENT_TOKENS = TokenSet.create(KtTokens.EQ, KtTokens.PLUSEQ, KtTokens.MINUSEQ, KtTokens.MULTEQ, KtTokens.DIVEQ, KtTokens.PERCEQ) private val unsupported = ConcurrentHashMap.newKeySet<String>() } }
apache-2.0
401233d5bb6b0a5d4123785af4bbfa42
47.632246
165
0.620806
6.203035
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/actmain/ColumnStripLinearLayout.kt
1
2328
package jp.juggler.subwaytooter.actmain import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.util.AttributeSet import android.widget.LinearLayout // 画面下のカラムストリップのLinearLayout // 可視範囲を示すインジケーターを表示する class ColumnStripLinearLayout : LinearLayout { // 可視範囲 private var visibleFirst: Int = 0 private var visibleLast: Int = 0 private var visibleSlideRatio: Float = 0.toFloat() // インジケーターの高さ private val indicatorHeight: Int // インジケーターの色 var indicatorColor: Int = 0 set(value) { if (field != value) { field = value invalidate() } } init { indicatorHeight = (0.5f + 2f * resources.displayMetrics.density).toInt() } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) fun setVisibleRange(first: Int, last: Int, slideRatio: Float) { if (this.visibleFirst == first && this.visibleLast == last && this.visibleSlideRatio == slideRatio ) return this.visibleFirst = first this.visibleLast = last this.visibleSlideRatio = slideRatio invalidate() } private val paint = Paint() private val rect = Rect() override fun dispatchDraw(canvas: Canvas) { super.dispatchDraw(canvas) if (visibleFirst < 0 || visibleLast >= childCount) return val childFirst = getChildAt(visibleFirst) val childLast = getChildAt(visibleLast) val x = if (visibleSlideRatio != 0f) { (0.5f + visibleSlideRatio * childFirst.width).toInt() } else { 0 } rect.left = childFirst.left + x rect.right = childLast.right + x rect.top = 0 rect.bottom = indicatorHeight paint.color = indicatorColor canvas.drawRect(rect, paint) } }
apache-2.0
7d651ed79cf53f84449fdd055b167b59
25.725
83
0.603697
4.224762
false
false
false
false
paplorinc/intellij-community
plugins/changeReminder/src/com/jetbrains/changeReminder/repository/FilesHistoryProvider.kt
1
2019
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.changeReminder.repository import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.data.index.IndexDataGetter import com.intellij.vcs.log.visible.filters.VcsLogFilterObject import com.jetbrains.changeReminder.changedFilePaths import com.jetbrains.changeReminder.processCommitsFromHashes data class Commit(val id: Int, val time: Long, val files: Set<FilePath>) class FilesHistoryProvider(private val project: Project, private val root: VirtualFile, private val dataGetter: IndexDataGetter) { private fun getCommitHashesWithFile(file: FilePath): Collection<Int> { val structureFilter = VcsLogFilterObject.fromPaths(setOf(file)) return dataGetter.filter(listOf(structureFilter)) } private fun getCommitsData(commits: Collection<Int>): Map<Int, Commit> { val hashes = mutableMapOf<String, Int>() for (commit in commits) { val hash = dataGetter.logStorage.getCommitId(commit)?.hash?.asString() ?: continue hashes[hash] = commit } val commitsData = mutableMapOf<Int, Commit>() processCommitsFromHashes(project, root, hashes.keys.toList()) consume@{ commit -> if (commit.changes.isNotEmpty()) { val id = hashes[commit.id.asString()] ?: return@consume val time = commit.commitTime val files = commit.changedFilePaths().toSet() commitsData[id] = Commit(id, time, files) } } return commitsData } fun getFilesHistory(files: Collection<FilePath>): Map<FilePath, Set<Commit>> { val filesData = files.associateWith { getCommitHashesWithFile(it) } val commits = filesData.values.flatten().toSet() val commitsData = getCommitsData(commits) return filesData.mapValues { entry -> entry.value.mapNotNull { commitsData[it] }.toSet() } } }
apache-2.0
9ccd3cfad2299e7af663f8a4ca326636
40.22449
140
0.739475
4.259494
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2017/Day19.kt
1
1578
package com.nibado.projects.advent.y2017 import com.nibado.projects.advent.Day import com.nibado.projects.advent.Direction import com.nibado.projects.advent.Point import com.nibado.projects.advent.resourceLines object Day19 : Day { private val maze = resourceLines(2017, 19).map { it.toCharArray().toList() } private val solution: Pair<String, Int> by lazy { solve() } override fun part1() = solution.first override fun part2() = solution.second.toString() private fun solve(): Pair<String, Int> { var count = 0 var current = findStart() var dir = Direction.SOUTH var chars = mutableListOf<Char>() var visited = mutableSetOf<Point>() while (get(current) != ' ') { count++ visited.add(current) if (get(current) in 'A'..'Z') { chars.add(get(current)) } if (get(current) == '+') { val next = current.neighborsHv() .filterNot { get(it) == ' ' } .filterNot { visited.contains(it) } .first() dir = current.directionTo(next) current = next } else { current = current.plus(dir) } } return Pair(chars.joinToString(""), count) } private fun get(p: Point) = if (p.x >= 0 && p.y >= 0 && maze.size > p.y && maze[p.y].size > p.x) maze[p.y][p.x] else ' ' private fun findStart() = (0 until maze[0].size).map { Point(it, 0) }.find { get(it) == '|' }!! }
mit
b151ce3731d0a24d9a27cf5864141534
32.595745
124
0.537389
3.935162
false
false
false
false
StephaneBg/ScoreIt
app/src/main/kotlin/com/sbgapps/scoreit/app/ui/edition/EditionActivity.kt
1
2296
/* * Copyright 2020 Stéphane Baiget * * 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.sbgapps.scoreit.app.ui.edition import android.annotation.SuppressLint import android.os.Bundle import android.view.Menu import android.view.View import android.view.Window import androidx.appcompat.app.AppCompatDelegate import com.google.android.material.transition.platform.MaterialContainerTransform import com.google.android.material.transition.platform.MaterialContainerTransformSharedElementCallback import com.sbgapps.scoreit.app.R import com.sbgapps.scoreit.app.ui.prefs.PreferencesViewModel import com.sbgapps.scoreit.core.ui.BaseActivity import org.koin.androidx.viewmodel.ext.android.viewModel @SuppressLint("Registered") open class EditionActivity : BaseActivity() { private val prefsViewModel by viewModel<PreferencesViewModel>() override fun onCreate(savedInstanceState: Bundle?) { window.requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS) findViewById<View>(android.R.id.content).transitionName = "shared_element_container" setEnterSharedElementCallback(MaterialContainerTransformSharedElementCallback()) window.sharedElementEnterTransition = MaterialContainerTransform().apply { addTarget(android.R.id.content) duration = 300L } window.sharedElementReturnTransition = MaterialContainerTransform().apply { addTarget(android.R.id.content) duration = 250L } super.onCreate(savedInstanceState) AppCompatDelegate.setDefaultNightMode(prefsViewModel.getThemeMode()) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_edition, menu) return super.onCreateOptionsMenu(menu) } }
apache-2.0
64d302b4d21f5e8751d26bcf53fe2881
38.568966
102
0.763834
4.693252
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2019/Day10.kt
1
1283
package com.nibado.projects.advent.y2019 import com.nibado.projects.advent.Day import com.nibado.projects.advent.Point import com.nibado.projects.advent.resourceLines import kotlin.math.PI object Day10 : Day { private val map = resourceLines(2019, 10).map { line -> line.toCharArray().toList() } private val points: List<Point> by lazy { map.indices.flatMap { y -> map[y].indices.map { x -> Point(x, y) } }.filter { (x, y) -> map[y][x] == '#' } } private val laser: Pair<Point, Int> by lazy { points.map { it to visible(it) }.maxByOrNull { it.second }!! } private fun visible(p: Point): Int = points.filterNot { it == p }.map { it.angle(p) }.distinct().size override fun part1() = laser.second override fun part2(): Int { val rads = points.filterNot { it == laser.first } .groupBy { laser.first.angle(it) + PI } .map { e -> e.key to e.value.sortedBy { ast -> laser.first.distance(ast) }.toMutableList() } .sortedByDescending { it.first } var p = Point(0, 0) for (i in 0..199) { val list = rads[i % rads.size].second if (list.isNotEmpty()) { p = list.removeAt(0) } } return p.x * 100 + p.y } }
mit
eb7d4cff80b46bf1d3d5d2f408a532c9
30.317073
114
0.578332
3.476965
false
false
false
false
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/utils/PropertiesUtil.kt
1
2087
package no.skatteetaten.aurora.boober.utils import org.springframework.core.io.ByteArrayResource import org.springframework.core.io.support.PropertiesLoaderUtils import java.io.ByteArrayOutputStream import java.io.IOException import java.util.Properties fun filterProperties(properties: ByteArray, keys: List<String>, keyMappings: Map<String, String>?): Properties = try { PropertiesLoaderUtils .loadProperties(ByteArrayResource(properties)) .filter(keys) .replaceKeyMappings(keyMappings) } catch (ioe: IOException) { throw PropertiesException("Encountered a problem while reading properties.", ioe) } fun Properties.filter(keys: List<String>): Properties { if (keys.isEmpty()) { return this } val propertyNames = this.stringPropertyNames() val missingKeys = keys - propertyNames if (missingKeys.isNotEmpty()) { throw IllegalArgumentException("The keys $missingKeys were not found in the secret vault") } val newProps = Properties() keys.filter { propertyNames.contains(it) } .map { it to this.getProperty(it) } .forEach { (key, value) -> newProps[key] = value } return newProps } fun Properties.replaceKeyMappings(keyMappings: Map<String, String>?): Properties { if (keyMappings == null || keyMappings.isEmpty()) { return this } val newProps = Properties() this.stringPropertyNames().forEach { val key = keyMappings[it] ?: it newProps[key] = this.getProperty(it) } return newProps } fun Properties.toByteArray(): ByteArray = ByteArrayOutputStream() .let { baos -> this.store(baos, "Properties filtered.") baos.toByteArray() } class PropertiesException(override val message: String, override val cause: Throwable) : RuntimeException(message, cause) internal fun String.toProperties() = Properties().also { it.load(this.reader()) } internal fun Properties.asString(): String { val bos = ByteArrayOutputStream() store(bos, "") return bos.toString("UTF-8") }
apache-2.0
df26a7b45f7f6ad7c0493ed12bf624ca
31.107692
112
0.691423
4.412262
false
false
false
false
codebrothers/PhraseTool
src/main/kotlin/phraseTool/model/Fragment.kt
1
1538
package phraseTool.model import java.util.* data class RawFragment( val key: String, val replacements: Set<String> ) interface ByteSizeable { fun byteSize() : Int } class Fragment private constructor ( val key : String, var replacements : Set<Replacement>? = null ) : ByteSizeable { companion object { var fragmentCache = HashMap<String,Fragment>() fun getCached( key: String, createNew: (key:String)-> Fragment) : Fragment { var fragment = fragmentCache[key] if( fragment == null ) { fragment = createNew( key ) fragmentCache[key] = fragment } return fragment } fun forRawFragment( rawFragment: RawFragment) : Fragment { val fragment = getCached( rawFragment.key ) { key -> Fragment( key ) } val replacements = rawFragment.replacements.map( ::Replacement ) fragment.replacements = HashSet( replacements ) return fragment } fun forKey( key: String ) : Fragment { return getCached( key ) { key -> Fragment( key ) } } } override fun byteSize() : Int { // Start with 2 = Leading Uint16 count return ( this.replacements?.fold( 2, { length, replacement -> length + replacement.byteSize() } ) ?: throw Exception("Cannot compute byte size: Replacement definition incomplete") ) } }
mit
f11d5023d51fd63ebd20b7d24f831beb
27.481481
189
0.561769
4.96129
false
false
false
false
MGaetan89/Kolumbus
kolumbus/src/main/kotlin/io/kolumbus/activity/TableInfoActivity.kt
1
2324
/* * Copyright (C) 2016 MGaetan89 * * 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 io.kolumbus.activity import android.app.Activity import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.MenuItem import io.kolumbus.Analyzer import io.kolumbus.BuildConfig import io.kolumbus.R import io.kolumbus.adapter.TableInfoAdapter import io.kolumbus.extension.prettify import io.realm.RealmModel class TableInfoActivity : Activity() { companion object { private val EXTRA_TABLE_CLASS = BuildConfig.APPLICATION_ID + ".extra.TABLE_CLASS" fun start(context: Context, table: Class<out RealmModel>?) { val intent = Intent(context, TableInfoActivity::class.java) intent.putExtra(EXTRA_TABLE_CLASS, table) context.startActivity(intent) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.setContentView(R.layout.kolumbus_activity_table_info) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { this.actionBar?.setDisplayHomeAsUpEnabled(true) } val tableClass = this.intent.getSerializableExtra(EXTRA_TABLE_CLASS) as Class<out RealmModel> val fields = Analyzer.getRealmFields(tableClass) this.title = tableClass.simpleName.prettify() val recyclerView = this.findViewById(android.R.id.list) as RecyclerView recyclerView.adapter = TableInfoAdapter(fields, tableClass.newInstance()) recyclerView.layoutManager = LinearLayoutManager(this) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == android.R.id.home) { this.onBackPressed() return true } return super.onOptionsItemSelected(item) } }
apache-2.0
95e43caccc9bc89f785988f24811e4ff
30.405405
95
0.772806
3.873333
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/properties/privatePropertyCallIsAccessibleOnAccessors.kt
1
1331
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.* import kotlin.reflect.full.* import kotlin.reflect.jvm.* import kotlin.test.* class A(private var foo: String) fun box(): String { val a = A("") val foo = A::class.memberProperties.single() as KMutableProperty1<A, String> assertTrue(!foo.isAccessible) assertTrue(!foo.getter.isAccessible) assertTrue(!foo.setter.isAccessible) val setter = foo.setter setter.isAccessible = true assertTrue(setter.isAccessible) assertTrue(foo.setter.isAccessible) // After we invoked isAccessible on a setter, the underlying field and thus the getter are also accessible assertTrue(foo.isAccessible) assertTrue(foo.getter.isAccessible) setter.call(a, "A") assertEquals("A", foo.getter.call(a)) setter.isAccessible = false assertFalse(setter.isAccessible) assertFalse(foo.setter.isAccessible) assertFalse(foo.getter.isAccessible) assertFalse(foo.isAccessible) val getter = foo.getter getter.isAccessible = true assertTrue(setter.isAccessible) assertTrue(foo.setter.isAccessible) assertTrue(foo.isAccessible) assertTrue(foo.getter.isAccessible) assertTrue(getter.isAccessible) return "OK" }
apache-2.0
0a4ab5ba8bb5bd565ec506b6221af6a8
27.319149
110
0.728775
4.238854
false
false
false
false
tomaszpolanski/AndroidSandbox
app/src/main/java/com/tomaszpolanski/androidsandbox/core/BaseApplication.kt
1
725
package com.tomaszpolanski.androidsandbox.core import android.app.Application import android.support.annotation.CallSuper import com.tomaszpolanski.androidsandbox.inject.Injector abstract class BaseApplication<T> : Application(), Injector<T> { private var component: T? = null @CallSuper override fun onCreate() { super.onCreate() inject() } override fun component(): T { val oldComponent = component if (oldComponent == null) { val newComponent = createComponent() component = newComponent return newComponent } else { return oldComponent } } protected abstract fun createComponent(): T }
apache-2.0
cdffdf6de8f3e38d8c813f7ef0f8f6bc
20.323529
64
0.646897
4.865772
false
false
false
false
Code-Tome/hexameter
mixite.core/src/commonMain/kotlin/org/hexworks/mixite/core/api/defaults/DefaultHexagonDataStorage.kt
2
1573
package org.hexworks.mixite.core.api.defaults import org.hexworks.cobalt.datatypes.Maybe import org.hexworks.mixite.core.api.CubeCoordinate import org.hexworks.mixite.core.api.contract.HexagonDataStorage import org.hexworks.mixite.core.api.contract.SatelliteData class DefaultHexagonDataStorage<T : SatelliteData> : HexagonDataStorage<T> { private val storage = LinkedHashMap<CubeCoordinate, Maybe<T>>() override val coordinates: Iterable<CubeCoordinate> get() = storage.keys override fun addCoordinate(cubeCoordinate: CubeCoordinate) { storage[cubeCoordinate] = Maybe.empty() } override fun addCoordinate(cubeCoordinate: CubeCoordinate, satelliteData: T): Boolean { val previous = storage.put(cubeCoordinate, Maybe.of(satelliteData)) return previous != null } override fun getSatelliteDataBy(cubeCoordinate: CubeCoordinate): Maybe<T> { return if (storage.containsKey(cubeCoordinate)) storage[cubeCoordinate]!! else Maybe.empty() } override fun containsCoordinate(cubeCoordinate: CubeCoordinate): Boolean { return storage.containsKey(cubeCoordinate) } override fun hasDataFor(cubeCoordinate: CubeCoordinate): Boolean { return storage.containsKey(cubeCoordinate) && storage[cubeCoordinate]!!.isPresent } override fun clearDataFor(cubeCoordinate: CubeCoordinate): Boolean { var result = false if (hasDataFor(cubeCoordinate)) { result = true } storage[cubeCoordinate] = Maybe.empty() return result } }
mit
2bb7d1f9fa93bf906821e414b5b508cf
34.75
100
0.726001
4.695522
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/extractFunction/controlFlow/outputValues/pairWithNameClash.kt
9
501
// WITH_STDLIB // SUGGESTED_NAMES: pair, intIntPair, intPair // PARAM_TYPES: kotlin.Int // PARAM_TYPES: kotlin.Int // PARAM_TYPES: kotlin.Int // PARAM_DESCRIPTOR: var b: kotlin.Int defined in foo // PARAM_DESCRIPTOR: value-parameter a: kotlin.Int defined in foo // PARAM_DESCRIPTOR: var c: kotlin.Int defined in foo // SIBLING: fun foo(a: Int): Int { var b: Int = 1 var c: Int = 1 val pair = 2 <selection>b += a c -= a println(b) println(c)</selection> return b + c }
apache-2.0
60b5bd01796805ec2e18d9368b1e87d8
22.904762
65
0.644711
3.253247
false
false
false
false
smmribeiro/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/visible/filters/VcsLogTextFilters.kt
12
2176
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.visible.filters import com.intellij.openapi.util.Comparing import com.intellij.vcs.log.VcsLogDetailsFilter import com.intellij.vcs.log.VcsLogTextFilter import org.jetbrains.annotations.NonNls import java.util.* import java.util.regex.Pattern internal data class VcsLogRegexTextFilter(private val pattern: Pattern) : VcsLogDetailsFilter, VcsLogTextFilter { override fun matches(message: String): Boolean = pattern.matcher(message).find() override fun getText(): String = pattern.pattern() override fun isRegex(): Boolean = true override fun matchesCase(): Boolean = (pattern.flags() and Pattern.CASE_INSENSITIVE) == 0 @NonNls override fun toString(): String { return "matching '$text' ${caseSensitiveText()}" } } internal class VcsLogMultiplePatternsTextFilter(val patterns: List<String>, private val isMatchCase: Boolean) : VcsLogDetailsFilter, VcsLogTextFilter { override fun getText(): String = if (patterns.size == 1) patterns.single() else patterns.joinToString("|") { Pattern.quote(it) } override fun isRegex(): Boolean = patterns.size > 1 override fun matchesCase(): Boolean = isMatchCase override fun matches(message: String): Boolean = patterns.any { message.contains(it, !isMatchCase) } @NonNls override fun toString(): String { return "containing at least one of the ${patterns.joinToString(", ") { s -> "'$s'" }} ${caseSensitiveText()}" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as VcsLogMultiplePatternsTextFilter return Comparing.haveEqualElements(patterns, other.patterns) && isMatchCase == other.isMatchCase } override fun hashCode(): Int { return Objects.hash(Comparing.unorderedHashcode(patterns), isMatchCase) } } @NonNls internal fun VcsLogTextFilter.caseSensitiveText() = "(case ${if (matchesCase()) "sensitive" else "insensitive"})"
apache-2.0
08806fcf4bedc9dd29bdcfcb4d848f60
36.534483
140
0.715993
4.495868
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt
1
23959
package info.nightscout.androidaps.utils.wizard import android.content.Context import android.content.Intent import android.text.Spanned import com.google.common.base.Joiner import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.general.automation.AutomationEvent import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.automation.actions.ActionAlarm import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.general.automation.elements.InputDelta import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerBg import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerDelta import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerTime import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.formatColor import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONException import org.json.JSONObject import java.text.DecimalFormat import java.util.* import javax.inject.Inject import kotlin.math.abs class BolusWizard @Inject constructor( val injector: HasAndroidInjector ) { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var sp: SP @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin @Inject lateinit var automationPlugin: AutomationPlugin @Inject lateinit var dateUtil: DateUtil @Inject lateinit var config: Config init { injector.androidInjector().inject(this) } // Intermediate var sens = 0.0 private set var ic = 0.0 private set var glucoseStatus: GlucoseStatus? = null private set private var targetBGLow = 0.0 private var targetBGHigh = 0.0 private var bgDiff = 0.0 var insulinFromBG = 0.0 private set var insulinFromCarbs = 0.0 private set var insulinFromBolusIOB = 0.0 private set var insulinFromBasalIOB = 0.0 private set var insulinFromCorrection = 0.0 private set var insulinFromSuperBolus = 0.0 private set var insulinFromCOB = 0.0 private set var insulinFromTrend = 0.0 private set var trend = 0.0 private set private var accepted = false // Result var calculatedTotalInsulin: Double = 0.0 private set var totalBeforePercentageAdjustment: Double = 0.0 private set var carbsEquivalent: Double = 0.0 private set var insulinAfterConstraints: Double = 0.0 private set // Input lateinit var profile: Profile lateinit var profileName: String var tempTarget: TempTarget? = null var carbs: Int = 0 var cob: Double = 0.0 var bg: Double = 0.0 private var correction: Double = 0.0 private var percentageCorrection: Double = 0.0 private var useBg: Boolean = false private var useCob: Boolean = false private var includeBolusIOB: Boolean = false private var includeBasalIOB: Boolean = false private var useSuperBolus: Boolean = false private var useTT: Boolean = false private var useTrend: Boolean = false private var useAlarm = false var notes: String = "" private var carbTime: Int = 0 @JvmOverloads fun doCalc(profile: Profile, profileName: String, tempTarget: TempTarget?, carbs: Int, cob: Double, bg: Double, correction: Double, percentageCorrection: Double = 100.0, useBg: Boolean, useCob: Boolean, includeBolusIOB: Boolean, includeBasalIOB: Boolean, useSuperBolus: Boolean, useTT: Boolean, useTrend: Boolean, useAlarm: Boolean, notes: String = "", carbTime: Int = 0 ): BolusWizard { this.profile = profile this.profileName = profileName this.tempTarget = tempTarget this.carbs = carbs this.cob = cob this.bg = bg this.correction = correction this.percentageCorrection = percentageCorrection this.useBg = useBg this.useCob = useCob this.includeBolusIOB = includeBolusIOB this.includeBasalIOB = includeBasalIOB this.useSuperBolus = useSuperBolus this.useTT = useTT this.useTrend = useTrend this.useAlarm = useAlarm this.notes = notes this.carbTime = carbTime // Insulin from BG sens = Profile.fromMgdlToUnits(profile.isfMgdl, profileFunction.getUnits()) targetBGLow = Profile.fromMgdlToUnits(profile.targetLowMgdl, profileFunction.getUnits()) targetBGHigh = Profile.fromMgdlToUnits(profile.targetHighMgdl, profileFunction.getUnits()) if (useTT && tempTarget != null) { targetBGLow = Profile.fromMgdlToUnits(tempTarget.low, profileFunction.getUnits()) targetBGHigh = Profile.fromMgdlToUnits(tempTarget.high, profileFunction.getUnits()) } if (useBg && bg > 0) { bgDiff = when { bg in targetBGLow..targetBGHigh -> 0.0 bg <= targetBGLow -> bg - targetBGLow else -> bg - targetBGHigh } insulinFromBG = bgDiff / sens } // Insulin from 15 min trend glucoseStatus = GlucoseStatus(injector).glucoseStatusData glucoseStatus?.let { if (useTrend) { trend = it.short_avgdelta insulinFromTrend = Profile.fromMgdlToUnits(trend, profileFunction.getUnits()) * 3 / sens } } // Insulin from carbs ic = profile.ic insulinFromCarbs = carbs / ic insulinFromCOB = if (useCob) (cob / ic) else 0.0 // Insulin from IOB // IOB calculation activePlugin.activeTreatments.updateTotalIOBTreatments() val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() activePlugin.activeTreatments.updateTotalIOBTempBasals() val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() insulinFromBolusIOB = if (includeBolusIOB) -bolusIob.iob else 0.0 insulinFromBasalIOB = if (includeBasalIOB) -basalIob.basaliob else 0.0 // Insulin from correction insulinFromCorrection = correction // Insulin from superbolus for 2h. Get basal rate now and after 1h if (useSuperBolus) { insulinFromSuperBolus = profile.basal var timeAfter1h = System.currentTimeMillis() timeAfter1h += T.hours(1).msecs() insulinFromSuperBolus += profile.getBasal(timeAfter1h) } // Total calculatedTotalInsulin = insulinFromBG + insulinFromTrend + insulinFromCarbs + insulinFromBolusIOB + insulinFromBasalIOB + insulinFromCorrection + insulinFromSuperBolus + insulinFromCOB // Percentage adjustment totalBeforePercentageAdjustment = calculatedTotalInsulin if (calculatedTotalInsulin > 0) { calculatedTotalInsulin = calculatedTotalInsulin * percentageCorrection / 100.0 } if (calculatedTotalInsulin < 0) { carbsEquivalent = (-calculatedTotalInsulin) * ic calculatedTotalInsulin = 0.0 } val bolusStep = activePlugin.activePump.pumpDescription.bolusStep calculatedTotalInsulin = Round.roundTo(calculatedTotalInsulin, bolusStep) insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(calculatedTotalInsulin)).value() aapsLogger.debug(this.toString()) return this } @Suppress("SpellCheckingInspection") private fun nsJSON(): JSONObject { val bolusCalcJSON = JSONObject() try { bolusCalcJSON.put("profile", profileName) bolusCalcJSON.put("notes", notes) bolusCalcJSON.put("eventTime", DateUtil.toISOString(Date())) bolusCalcJSON.put("targetBGLow", targetBGLow) bolusCalcJSON.put("targetBGHigh", targetBGHigh) bolusCalcJSON.put("isf", sens) bolusCalcJSON.put("ic", ic) bolusCalcJSON.put("iob", -(insulinFromBolusIOB + insulinFromBasalIOB)) bolusCalcJSON.put("bolusiob", insulinFromBolusIOB) bolusCalcJSON.put("basaliob", insulinFromBasalIOB) bolusCalcJSON.put("bolusiobused", includeBolusIOB) bolusCalcJSON.put("basaliobused", includeBasalIOB) bolusCalcJSON.put("bg", bg) bolusCalcJSON.put("insulinbg", insulinFromBG) bolusCalcJSON.put("insulinbgused", useBg) bolusCalcJSON.put("bgdiff", bgDiff) bolusCalcJSON.put("insulincarbs", insulinFromCarbs) bolusCalcJSON.put("carbs", carbs) bolusCalcJSON.put("cob", cob) bolusCalcJSON.put("cobused", useCob) bolusCalcJSON.put("insulincob", insulinFromCOB) bolusCalcJSON.put("othercorrection", correction) bolusCalcJSON.put("insulinsuperbolus", insulinFromSuperBolus) bolusCalcJSON.put("insulintrend", insulinFromTrend) bolusCalcJSON.put("insulin", calculatedTotalInsulin) bolusCalcJSON.put("superbolusused", useSuperBolus) bolusCalcJSON.put("insulinsuperbolus", insulinFromSuperBolus) bolusCalcJSON.put("trendused", useTrend) bolusCalcJSON.put("insulintrend", insulinFromTrend) bolusCalcJSON.put("trend", trend) bolusCalcJSON.put("ttused", useTT) bolusCalcJSON.put("percentageCorrection", percentageCorrection) } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) } return bolusCalcJSON } private fun confirmMessageAfterConstraints(advisor: Boolean): Spanned { val actions: LinkedList<String> = LinkedList() if (insulinAfterConstraints > 0) { val pct = if (percentageCorrection != 100.0) " (" + percentageCorrection.toInt() + "%)" else "" actions.add(resourceHelper.gs(R.string.bolus) + ": " + resourceHelper.gs(R.string.formatinsulinunits, insulinAfterConstraints).formatColor(resourceHelper, R.color.bolus) + pct) } if (carbs > 0 && !advisor) { var timeShift = "" if (carbTime > 0) { timeShift += " (+" + resourceHelper.gs(R.string.mins, carbTime) + ")" } else if (carbTime < 0) { timeShift += " (" + resourceHelper.gs(R.string.mins, carbTime) + ")" } actions.add(resourceHelper.gs(R.string.carbs) + ": " + resourceHelper.gs(R.string.format_carbs, carbs).formatColor(resourceHelper, R.color.carbs) + timeShift) } if (insulinFromCOB > 0) { actions.add(resourceHelper.gs(R.string.cobvsiob) + ": " + resourceHelper.gs(R.string.formatsignedinsulinunits, insulinFromBolusIOB + insulinFromBasalIOB + insulinFromCOB + insulinFromBG).formatColor(resourceHelper, R.color.cobAlert)) val absorptionRate = iobCobCalculatorPlugin.slowAbsorptionPercentage(60) if (absorptionRate > .25) actions.add(resourceHelper.gs(R.string.slowabsorptiondetected, resourceHelper.gc(R.color.cobAlert), (absorptionRate * 100).toInt())) } if (abs(insulinAfterConstraints - calculatedTotalInsulin) > activePlugin.activePump.pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarn, calculatedTotalInsulin, insulinAfterConstraints).formatColor(resourceHelper, R.color.warning)) if (config.NSCLIENT && insulinAfterConstraints > 0) actions.add(resourceHelper.gs(R.string.bolusrecordedonly).formatColor(resourceHelper, R.color.warning)) if (useAlarm && !advisor && carbs > 0 && carbTime > 0) actions.add(resourceHelper.gs(R.string.alarminxmin, carbTime).formatColor(resourceHelper, R.color.info)) if (advisor) actions.add(resourceHelper.gs(R.string.advisoralarm).formatColor(resourceHelper, R.color.info)) return HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)) } fun confirmAndExecute(ctx: Context) { if (calculatedTotalInsulin > 0.0 || carbs > 0.0) { if (accepted) { aapsLogger.debug(LTag.UI, "guarding: already accepted") return } accepted = true if (sp.getBoolean(R.string.key_usebolusadvisor, false) && Profile.toMgdl(bg, profile.units) > 180 && carbs > 0 && carbTime >= 0) OKDialog.showYesNoCancel(ctx, resourceHelper.gs(R.string.bolusadvisor), resourceHelper.gs(R.string.bolusadvisormessage), { bolusAdvisorProcessing(ctx) }, { commonProcessing(ctx) } ) else commonProcessing(ctx) } } private fun bolusAdvisorProcessing(ctx: Context) { val confirmMessage = confirmMessageAfterConstraints(advisor = true) OKDialog.showConfirmation(ctx, resourceHelper.gs(R.string.boluswizard), confirmMessage, { DetailedBolusInfo().apply { eventType = CareportalEvent.CORRECTIONBOLUS insulin = insulinAfterConstraints carbs = 0.0 context = ctx glucose = bg glucoseType = "Manual" carbTime = 0 boluscalc = nsJSON() source = Source.USER notes = [email protected] aapsLogger.debug("USER ENTRY: BOLUS ADVISOR insulin $insulinAfterConstraints") if (insulin > 0) { commandQueue.bolus(this, object : Callback() { override fun run() { if (!result.success) { val i = Intent(ctx, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ctx.startActivity(i) } else scheduleEatReminder() } }) } } }) } private fun commonProcessing(ctx: Context) { val profile = profileFunction.getProfile() ?: return val pump = activePlugin.activePump val confirmMessage = confirmMessageAfterConstraints(advisor = false) OKDialog.showConfirmation(ctx, resourceHelper.gs(R.string.boluswizard), confirmMessage, { if (insulinAfterConstraints > 0 || carbs > 0) { if (useSuperBolus) { aapsLogger.debug("USER ENTRY: SUPERBOLUS TBR") if (loopPlugin.isEnabled(PluginType.LOOP)) { loopPlugin.superBolusTo(System.currentTimeMillis() + 2 * 60L * 60 * 1000) rxBus.send(EventRefreshOverview("WizardDialog")) } if (pump.pumpDescription.tempBasalStyle == PumpDescription.ABSOLUTE) { commandQueue.tempBasalAbsolute(0.0, 120, true, profile, object : Callback() { override fun run() { if (!result.success) { val i = Intent(ctx, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ctx.startActivity(i) } } }) } else { commandQueue.tempBasalPercent(0, 120, true, profile, object : Callback() { override fun run() { if (!result.success) { val i = Intent(ctx, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ctx.startActivity(i) } } }) } } DetailedBolusInfo().apply { eventType = CareportalEvent.BOLUSWIZARD insulin = insulinAfterConstraints carbs = [email protected]() context = ctx glucose = bg glucoseType = "Manual" carbTime = [email protected] boluscalc = nsJSON() source = Source.USER notes = [email protected] aapsLogger.debug("USER ENTRY: BOLUS WIZARD insulin $insulinAfterConstraints carbs: $carbs") if (insulin > 0 || pump.pumpDescription.storesCarbInfo) { commandQueue.bolus(this, object : Callback() { override fun run() { if (!result.success) { val i = Intent(ctx, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ctx.startActivity(i) } } }) } else { activePlugin.activeTreatments.addToHistoryTreatment(this, false) } } if (useAlarm && carbs > 0 && carbTime > 0) { scheduleReminder(dateUtil._now() + T.mins(carbTime.toLong()).msecs()) } } }) } private fun scheduleEatReminder() { val event = AutomationEvent(injector).apply { title = resourceHelper.gs(R.string.bolusadvisor) readOnly = true systemAction = true autoRemove = true trigger = TriggerConnector(injector, TriggerConnector.Type.OR).apply { // Bg under 180 mgdl and dropping by 15 mgdl list.add(TriggerConnector(injector, TriggerConnector.Type.AND).apply { list.add(TriggerBg(injector, 180.0, Constants.MGDL, Comparator.Compare.IS_LESSER)) list.add(TriggerDelta(injector, InputDelta(injector, -15.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.DELTA), Constants.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) list.add(TriggerDelta(injector, InputDelta(injector, -8.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.SHORT_AVERAGE), Constants.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) }) // Bg under 160 mgdl and dropping by 9 mgdl list.add(TriggerConnector(injector, TriggerConnector.Type.AND).apply { list.add(TriggerBg(injector, 160.0, Constants.MGDL, Comparator.Compare.IS_LESSER)) list.add(TriggerDelta(injector, InputDelta(injector, -9.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.DELTA), Constants.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) list.add(TriggerDelta(injector, InputDelta(injector, -5.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.SHORT_AVERAGE), Constants.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) }) // Bg under 145 mgdl and dropping list.add(TriggerConnector(injector, TriggerConnector.Type.AND).apply { list.add(TriggerBg(injector, 145.0, Constants.MGDL, Comparator.Compare.IS_LESSER)) list.add(TriggerDelta(injector, InputDelta(injector, 0.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.DELTA), Constants.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) list.add(TriggerDelta(injector, InputDelta(injector, 0.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.SHORT_AVERAGE), Constants.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) }) } actions.add(ActionAlarm(injector, resourceHelper.gs(R.string.time_to_eat))) } automationPlugin.addIfNotExists(event) } private fun scheduleReminder(time: Long) { val event = AutomationEvent(injector).apply { title = resourceHelper.gs(R.string.timetoeat) readOnly = true systemAction = true autoRemove = true trigger = TriggerConnector(injector, TriggerConnector.Type.AND).apply { list.add(TriggerTime(injector, time)) } actions.add(ActionAlarm(injector, resourceHelper.gs(R.string.timetoeat))) } automationPlugin.addIfNotExists(event) } }
agpl-3.0
d8137177e3a8770f0725ec8216ea3bfa
46.632207
245
0.618974
4.792759
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/core/project/ProjectManager.kt
1
3845
package com.cout970.modeler.core.project import com.cout970.modeler.api.animation.IAnimation import com.cout970.modeler.api.animation.IAnimationRef import com.cout970.modeler.api.model.IModel import com.cout970.modeler.api.model.`object`.IGroupRef import com.cout970.modeler.api.model.`object`.RootGroupRef import com.cout970.modeler.api.model.material.IMaterial import com.cout970.modeler.api.model.material.IMaterialRef import com.cout970.modeler.api.model.selection.ISelection import com.cout970.modeler.core.animation.AnimationNone import com.cout970.modeler.core.animation.AnimationRefNone import com.cout970.modeler.core.config.Config import com.cout970.modeler.core.export.ExportManager import com.cout970.modeler.core.export.ProgramSave import com.cout970.modeler.core.model.Model import com.cout970.modeler.core.model.material.MaterialNone import com.cout970.modeler.core.model.material.MaterialRefNone import com.cout970.modeler.core.model.material.TexturedMaterial import com.cout970.modeler.core.model.ref import com.cout970.modeler.core.model.selection.ClipboardNone import com.cout970.modeler.core.model.selection.IClipboard import com.cout970.modeler.core.model.selection.SelectionHandler import com.cout970.modeler.util.Nullable /** * Created by cout970 on 2017/07/08. */ class ProjectManager( override val modelSelectionHandler: SelectionHandler, override val textureSelectionHandler: SelectionHandler ) : IProgramState { override val modelSelection: Nullable<ISelection> get() = modelSelectionHandler.getSelection() override val textureSelection: Nullable<ISelection> get() = textureSelectionHandler.getSelection() var projectProperties: ProjectProperties = ProjectProperties(Config.user, "unnamed") override var model: IModel = Model.empty() override var selectedGroup: IGroupRef = RootGroupRef override var selectedMaterial: IMaterialRef = MaterialRefNone override val material: IMaterial get() = model.materialMap[selectedMaterial] ?: MaterialNone override var selectedAnimation: IAnimationRef = AnimationRefNone override val animation: IAnimation get() = model.animationMap[selectedAnimation] ?: AnimationNone val modelChangeListeners: MutableList<(old: IModel, new: IModel) -> Unit> = mutableListOf() val materialChangeListeners: MutableList<(old: IMaterial?, new: IMaterial?) -> Unit> = mutableListOf() val materialPaths get() = loadedMaterials.values.filterIsInstance<TexturedMaterial>() val loadedMaterials: Map<IMaterialRef, IMaterial> get() = model.materialMap var clipboard: IClipboard = ClipboardNone fun loadMaterial(material: IMaterial) { if (material.ref !in loadedMaterials) { model = model.addMaterial(material) materialChangeListeners.forEach { it.invoke(null, material) } } } fun updateMaterial(new: IMaterial) { if (new.ref in loadedMaterials) { materialChangeListeners.forEach { it.invoke(model.getMaterial(new.ref), new) } model = model.modifyMaterial(new) } } fun removeMaterial(ref: IMaterialRef) { if (ref in loadedMaterials) { val oldMaterial = model.getMaterial(ref) model = model.removeMaterial(ref) materialChangeListeners.forEach { it.invoke(oldMaterial, null) } } } fun updateModel(model: IModel) { val old = this.model this.model = model modelChangeListeners.forEach { it.invoke(old, model) } } fun loadProjectProperties(aNew: ProjectProperties) { projectProperties = aNew } fun toProgramSave(saveImages: Boolean) = ProgramSave( ExportManager.CURRENT_SAVE_VERSION, projectProperties, model, if (saveImages) materialPaths else emptyList() ) }
gpl-3.0
e44d63312268bfba6dce8f6f75af220b
38.244898
106
0.745904
4.258029
false
false
false
false
MarcinMoskala/ActivityStarter
activitystarter-compiler/src/main/java/activitystarter/compiler/model/classbinding/KnownClassType.kt
1
975
package activitystarter.compiler.model.classbinding import activitystarter.compiler.utils.isSubtypeOfType import javax.lang.model.type.TypeMirror enum class KnownClassType(vararg val typeString: String) { Activity(ACTIVITY_TYPE), Fragment(FRAGMENT_TYPE, FRAGMENTv4_TYPE), Service(SERVICE_TYPE), BroadcastReceiver(BROADCAST_RECEIVER_TYPE); companion object { fun getByType(elementType: TypeMirror): KnownClassType? = values() .first { elementType.isSubtypeOfType(*it.typeString) } } } private const val ACTIVITY_TYPE = "android.app.Activity" private const val FRAGMENT_TYPE = "android.app.Fragment" private const val FRAGMENTv4_TYPE = "android.support.v4.app.Fragment" private const val SERVICE_TYPE = "android.app.Service" private const val BROADCAST_RECEIVER_TYPE = "android.content.BroadcastReceiver" private const val SERIALIZABLE_TYPE = "java.io.Serializable" private const val PARCELABLE_TYPE = "android.os.Parcelable"
apache-2.0
70010506eea7bd3e459959c410b35542
39.666667
79
0.771282
4.096639
false
false
false
false
Pattonville-App-Development-Team/Android-App
app/src/androidTest/java/org/pattonvillecs/pattonvilleapp/service/repository/calendar/CalendarRepositoryTest.kt
1
12266
/* * Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District * * 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 org.pattonvillecs.pattonvilleapp.service.repository.calendar import android.arch.persistence.room.Room import android.support.test.InstrumentationRegistry import android.support.test.filters.MediumTest import android.support.test.runner.AndroidJUnit4 import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.* import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.pattonvillecs.pattonvilleapp.service.model.DataSource import org.pattonvillecs.pattonvilleapp.service.model.calendar.DataSourceMarker import org.pattonvillecs.pattonvilleapp.service.model.calendar.event.CalendarEvent import org.pattonvillecs.pattonvilleapp.service.model.calendar.event.PinnableCalendarEvent import org.pattonvillecs.pattonvilleapp.service.repository.AppDatabase import org.pattonvillecs.pattonvilleapp.service.repository.awaitValue import org.threeten.bp.Instant /** * Tests adding and removing calendar events from an in-memory database. * * @author Mitchell Skaggs * @since 1.2.0 */ @Suppress("TestFunctionName") @RunWith(AndroidJUnit4::class) @MediumTest class CalendarRepositoryTest { private lateinit var appDatabase: AppDatabase private lateinit var calendarRepository: CalendarRepository /** * Gets a test event * * @param startEpochMilli the start date * @param uid the uid * @return A test event occurring at the given date and ending 10,000ms later, with the given UID */ private fun testEvent(startEpochMilli: Long = 10000, endEpochMilli: Long = startEpochMilli + 10000, uid: String = "test_uid", pinned: Boolean = false, vararg dataSources: DataSource = arrayOf(DataSource.DISTRICT)): PinnableCalendarEvent { return PinnableCalendarEvent( CalendarEvent(uid, "summary", "location", Instant.ofEpochMilli(startEpochMilli), Instant.ofEpochMilli(endEpochMilli)), pinned, dataSources.map { DataSourceMarker(uid, it) }.toSet()) } @Before fun createDb() { val context = InstrumentationRegistry.getTargetContext() appDatabase = AppDatabase.init(Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)).build() calendarRepository = CalendarRepository(appDatabase) } @After fun closeDb() { appDatabase.close() } @Test fun Given_UnpinnedCalendarEvent_When_GetEventsByDataSourceCalled_Then_ReturnSameUnpinnedEvent() { val calendarEvent = testEvent(dataSources = *arrayOf(DataSource.DISTRICT)) calendarRepository.insertEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsByDataSource(DataSource.DISTRICT).awaitValue() assertThat(calendarEvents, contains(calendarEvent)) } @Test fun Given_PinnedCalendarEvent_When_GetEventsByDataSourceCalled_Then_ReturnSamePinnedEvent() { val calendarEvent = testEvent(pinned = true, dataSources = *arrayOf(DataSource.DISTRICT)) calendarRepository.insertEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsByDataSource(DataSource.DISTRICT).awaitValue() assertThat(calendarEvents, contains(calendarEvent)) } @Test fun Given_UnpinnedCalendarEvent_When_GetEventsByUidCalled_Then_ReturnSameUnpinnedEvent() { val calendarEvent = testEvent() calendarRepository.insertEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsByUid(DataSource.DISTRICT, calendarEvent.uid).awaitValue() assertThat(calendarEvents, contains(calendarEvent)) } @Test fun Given_UnpinnedDuplicateCalendarEvent_When_GetEventsByUidCalled_Then_ReturnSameUnpinnedEvent() { val calendarEvent = testEvent() calendarRepository.insertEvent(calendarEvent) calendarRepository.insertEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsByUid(DataSource.DISTRICT, calendarEvent.uid).awaitValue() assertThat(calendarEvents, contains(calendarEvent)) } @Test fun Given_PinnedCalendarEvent_When_GetEventsByUidCalled_Then_ReturnSamePinnedEvent() { val calendarEvent = testEvent(pinned = true) calendarRepository.insertEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsByUid(DataSource.DISTRICT, calendarEvent.uid).awaitValue() assertThat(calendarEvents, contains(calendarEvent)) } @Test fun Given_PinnedDuplicateCalendarEvent_When_GetEventsByUidCalled_Then_ReturnSamePinnedEvent() { val calendarEvent = testEvent(pinned = true) calendarRepository.insertEvent(calendarEvent) calendarRepository.insertEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsByUid(DataSource.DISTRICT, calendarEvent.uid).awaitValue() assertThat(calendarEvents, contains(calendarEvent)) } @Test fun Given_UnpinnedCalendarEvent_When_GetDataSourcesCalled_Then_ReturnSameDataSource() { val calendarEvent = testEvent() calendarRepository.insertEvent(calendarEvent) val dataSources = calendarRepository.getDataSources(calendarEvent.uid).awaitValue() assertThat(dataSources, containsInAnyOrder(DataSource.DISTRICT)) } @Test fun Given_UnpinnedCalendarEventMultipleDataSources_When_GetDataSourcesCalled_Then_ReturnSameDataSources() { val calendarEvent = testEvent(dataSources = *arrayOf(DataSource.DISTRICT, DataSource.HIGH_SCHOOL)) calendarRepository.insertEvent(calendarEvent) val dataSources = calendarRepository.getDataSources(calendarEvent.uid).awaitValue() assertThat(dataSources, containsInAnyOrder(DataSource.DISTRICT, DataSource.HIGH_SCHOOL)) } @Test fun Given_UnpinnedDuplicateCalendarEventMultipleDataSources_When_GetDataSourcesCalled_Then_ReturnSameDataSources() { val calendarEvent1 = testEvent() val calendarEvent2 = testEvent(dataSources = *arrayOf(DataSource.HIGH_SCHOOL)) calendarRepository.insertEvent(calendarEvent1) calendarRepository.insertEvent(calendarEvent2) val dataSources = calendarRepository.getDataSources(calendarEvent1.uid).awaitValue() assertThat(dataSources, containsInAnyOrder(DataSource.DISTRICT, DataSource.HIGH_SCHOOL)) } @Test fun Given_UnpinnedCalendarEventDuplicateDataSource_When_GetDataSourcesCalled_Then_ReturnSameDataSource() { val calendarEvent = testEvent() calendarRepository.insertEvent(calendarEvent) calendarRepository.insertEvent(calendarEvent) val dataSources = calendarRepository.getDataSources(calendarEvent.uid).awaitValue() assertThat(dataSources, containsInAnyOrder(DataSource.DISTRICT)) } @Test fun Given_UnpinnedCalendarEvent_When_PinEventCalled_And_GetEventsByDataSourceCalled_Then_ReturnPinnedEvent() { val calendarEvent = testEvent() calendarRepository.insertEvent(calendarEvent) calendarRepository.pinEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsByDataSource(DataSource.DISTRICT).awaitValue() val expectedCalendarEvent = testEvent(pinned = true) assertThat(calendarEvents, contains(expectedCalendarEvent)) } @Test fun Given_PinnedCalendarEvent_When_UnpinEventCalled_And_GetEventsByDataSourceCalled_Then_ReturnUnpinnedEvent() { val calendarEvent = testEvent(pinned = true) calendarRepository.insertEvent(calendarEvent) calendarRepository.unpinEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsByDataSource(DataSource.DISTRICT).awaitValue() val expectedCalendarEvent = testEvent(pinned = false) assertThat(calendarEvents, contains(expectedCalendarEvent)) } @Test fun Given_UnpinnedCalendarEvent_When_GetEventsBeforeDateCalled_And_EventIsBeforeDate_Then_ReturnSameEvent() { val calendarEvent = testEvent() calendarRepository.insertEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsBeforeDate(DataSource.DISTRICT, Instant.ofEpochMilli(25000)).awaitValue() assertThat(calendarEvents, contains(calendarEvent)) } @Test fun Given_UnpinnedCalendarEvent_When_GetEventsBeforeDateCalled_And_EventIsNotBeforeDate_Then_ReturnNothing() { val calendarEvent = testEvent() calendarRepository.insertEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsBeforeDate(DataSource.DISTRICT, Instant.ofEpochMilli(5000)).awaitValue() assertThat(calendarEvents, `is`(empty())) } @Test fun Given_UnpinnedCalendarEvent_When_GetEventsAfterDateCalled_And_EventIsAfterDate_Then_ReturnSameEvent() { val calendarEvent = testEvent() calendarRepository.insertEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsAfterDate(DataSource.DISTRICT, Instant.ofEpochMilli(5000)).awaitValue() assertThat(calendarEvents, contains(calendarEvent)) } @Test fun Given_UnpinnedCalendarEvent_When_GetEventsAfterDateCalled_And_EventIsNotAfterDate_Then_ReturnNothing() { val calendarEvent = testEvent() calendarRepository.insertEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsAfterDate(DataSource.DISTRICT, Instant.ofEpochMilli(25000)).awaitValue() assertThat(calendarEvents, `is`(empty())) } @Test fun Given_UnpinnedCalendarEvent_When_GetEventsBetweenDatesCalled_And_EventIsBetweenDates_Then_ReturnSameEvent() { val calendarEvent = testEvent() calendarRepository.insertEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsBetweenDates(DataSource.DISTRICT, Instant.ofEpochMilli(5000), Instant.ofEpochMilli(25000)).awaitValue() assertThat(calendarEvents, contains(calendarEvent)) } @Test fun Given_UnpinnedCalendarEvent_When_GetEventsBetweenDatesCalled_And_EventIsNotBetweenDates_Then_ReturnNothing() { val calendarEvent = testEvent() calendarRepository.insertEvent(calendarEvent) val calendarEvents = calendarRepository.getEventsBetweenDates(DataSource.DISTRICT, Instant.ofEpochMilli(25000), Instant.ofEpochMilli(45000)).awaitValue() assertThat(calendarEvents, `is`(empty())) } @Test fun Given_TwoUnpinnedCalendarEvents_When_GetEventsBetweenDatesCalled_And_EventsAreBetweenDates_Then_ReturnBothSorted() { val calendarEventFirst = testEvent(uid = "test_uid_1") val calendarEventSecond = testEvent(startEpochMilli = 30000, uid = "test_uid_2") calendarRepository.insertEvent(calendarEventSecond) calendarRepository.insertEvent(calendarEventFirst) val calendarEvents = calendarRepository.getEventsBetweenDates(DataSource.DISTRICT, Instant.ofEpochMilli(10000), Instant.ofEpochMilli(40000)).awaitValue() assertThat(calendarEvents, hasSize(2)) assertThat(calendarEvents, contains(calendarEventFirst, calendarEventSecond)) } @Test fun Given_CalendarEvent_When_GetCountOnDaysCalled_Then_OneEntry() { val calendarEvent = testEvent() calendarRepository.insertEvent(calendarEvent) val dates = calendarRepository.getCountOnDays(DataSource.DISTRICT).awaitValue() assertThat(dates.entrySet(), hasSize(1)) // One unique item added assertThat(dates, hasSize(1)) // One item added total } }
gpl-3.0
e03c3467288ee43b5d49a544770d9595
38.44373
242
0.756481
4.930064
false
true
false
false
SkyTreasure/Kotlin-Firebase-Group-Chat
app/src/main/java/io/skytreasure/kotlingroupchat/chat/ui/ChatMessagesActivity.kt
1
22818
package io.skytreasure.kotlingroupchat.chat.ui import android.Manifest import android.app.ProgressDialog import android.content.DialogInterface import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.os.Environment import android.os.Handler import android.provider.MediaStore import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.text.format.DateFormat import android.util.Log import android.view.Gravity import android.view.View import android.widget.Toast import com.google.android.gms.common.GooglePlayServicesNotAvailableException import com.google.android.gms.common.GooglePlayServicesRepairableException import com.google.android.gms.location.places.ui.PlacePicker import com.google.android.gms.tasks.OnFailureListener import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.Query import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageReference import com.google.firebase.storage.UploadTask import io.skytreasure.kotlingroupchat.R import io.skytreasure.kotlingroupchat.chat.MyChatManager import io.skytreasure.kotlingroupchat.chat.model.FileModel import io.skytreasure.kotlingroupchat.chat.model.LocationModel import io.skytreasure.kotlingroupchat.chat.model.MessageModel import io.skytreasure.kotlingroupchat.chat.model.UserModel import io.skytreasure.kotlingroupchat.chat.ui.ViewHolders.ViewHolder import io.skytreasure.kotlingroupchat.chat.ui.adapter.ChatMessagesRecyclerAdapter import io.skytreasure.kotlingroupchat.chat.ui.widget.EndlessRecyclerViewScrollListener import io.skytreasure.kotlingroupchat.chat.ui.widget.InfiniteFirebaseRecyclerAdapter import io.skytreasure.kotlingroupchat.common.constants.AppConstants import io.skytreasure.kotlingroupchat.common.constants.DataConstants import io.skytreasure.kotlingroupchat.common.constants.DataConstants.Companion.groupMembersMap import io.skytreasure.kotlingroupchat.common.constants.DataConstants.Companion.sMyGroups import io.skytreasure.kotlingroupchat.common.constants.DataConstants.Companion.sCurrentUser import io.skytreasure.kotlingroupchat.common.constants.FirebaseConstants import io.skytreasure.kotlingroupchat.common.constants.NetworkConstants import io.skytreasure.kotlingroupchat.common.controller.NotifyMeInterface import io.skytreasure.kotlingroupchat.common.util.MyTextUtil import io.skytreasure.kotlingroupchat.common.util.MyViewUtils import kotlinx.android.synthetic.main.activity_chat_messages.* import java.io.File import java.util.* import kotlin.concurrent.schedule class ChatMessagesActivity : AppCompatActivity(), View.OnClickListener { var adapter: ChatMessagesRecyclerAdapter? = null var groupId: String? = "" var position: Int? = 0 var progressDialog: ProgressDialog? = null var mFirebaseDatabaseReference: DatabaseReference? = null var mLinearLayoutManager: LinearLayoutManager? = null var storage = FirebaseStorage.getInstance() var type: String? = "" val IMAGE_GALLERY_REQUEST = 1 val IMAGE_CAMERA_REQUEST = 2 val PLACE_PICKER_REQUEST = 3 var user2: UserModel = UserModel() var user2Id: String = "" var groupIsPresent: Boolean = false //File var filePathImageCamera: File? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_chat_messages) progressDialog?.show() groupId = intent.getStringExtra(AppConstants.GROUP_ID) position = intent.getIntExtra(AppConstants.POSITION, 1) type = intent.getStringExtra(AppConstants.CHAT_TYPE) tv_loadmore.setOnClickListener(this) MyChatManager.setmContext(this@ChatMessagesActivity) when (type) { AppConstants.GROUP_CHAT -> { if (groupId != null) { chat_room_title.text = sMyGroups?.get(position!!)?.name mLinearLayoutManager = LinearLayoutManager(this) mLinearLayoutManager!!.setStackFromEnd(true) // chat_messages_recycler.layoutManager = mLinearLayoutManager progressDialog?.show() btnSend.setOnClickListener(this) iv_back.setOnClickListener(this) chat_room_title.setOnClickListener(this) iv_attach.setOnClickListener(this) MyChatManager.fetchGroupMembersDetails(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { readMessagesFromFirebase(groupId!!) getLastMessageAndUpdateUnreadCount() } }, NetworkConstants.FETCH_GROUP_MEMBERS_DETAILS, groupId) } } AppConstants.ONE_ON_ONE_CHAT -> { mLinearLayoutManager = LinearLayoutManager(this) mLinearLayoutManager!!.setStackFromEnd(true) btnSend.setOnClickListener(this) iv_back.setOnClickListener(this) chat_room_title.setOnClickListener(this) iv_attach.setOnClickListener(this) btnSend.visibility = View.GONE user2Id = intent.getStringExtra(AppConstants.USER_ID) var userModel = DataConstants.userMap?.get(user2Id) chat_room_title.text = userModel?.name checkIfGroupExistsOrNot(); } } } /** * Check if group exists, if exists then download the chat data. * If group doesn't exists, then wait till the first message is sent. * * * When first message is sent. * * Check if user2 node is present or not, if not create user2 node. Then, * * Create a groupID of these two by calling getHash(uid1,uid2) * * Create a group with 2 members, group flag set to false. Then add group id in user1, user2 to be true * * Then add the message under the MESSAGE->GROUPID. */ private fun checkIfGroupExistsOrNot() { groupId = MyTextUtil().getHash(sCurrentUser?.uid!!, user2Id) MyChatManager.checkIfGroupExists(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { if (`object` as Boolean) { //Exists so fetch the data readMessagesFromFirebase(groupId!!) tv_last_seen.visibility = View.VISIBLE user2 = DataConstants.userMap?.get(user2Id)!! if (user2.online!!) { tv_last_seen.setText("Online") } else if (user2.last_seen_online != null) { tv_last_seen.setText(MyTextUtil().getTimestamp(user2.last_seen_online!!.toLong())) } else { tv_last_seen.visibility = View.GONE } groupIsPresent = true } else { //Doesn't exists wait till first message is sent (Do nothing) user2 = DataConstants.userMap?.get(user2Id)!! MyChatManager.createOrUpdateUserNode(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { user2 = `object` as UserModel //createGroupOfTwo(user2, null) } }, user2, NetworkConstants.CREATE_USER_NODE) } } }, groupId!!, NetworkConstants.CHECK_GROUP_EXISTS) } fun getLastMessageAndUpdateUnreadCount() { MyChatManager.fetchLastMessageFromGroup(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { var lastMessage: MessageModel? = `object` as MessageModel if (lastMessage != null) { MyChatManager.updateUnReadCountLastSeenMessageTimestamp(groupId, lastMessage!!) } } }, NetworkConstants.FETCH_MESSAGES, groupId) } override fun onClick(v: View?) { when (v?.id) { R.id.btnSend -> { var message: String = et_chat.text.toString() if (!message.isEmpty()) { sendMessage(message!!) } } R.id.tv_loadmore -> { /* newAdapter?.more() tv_loadmore.visibility = View.GONE*/ } R.id.iv_back -> { finish() } R.id.chat_room_title -> { val intent = Intent(this@ChatMessagesActivity, GroupDetailsActivity::class.java) intent.putExtra(AppConstants.GROUP_ID, groupId) startActivity(intent) } R.id.iv_attach -> { val builder = AlertDialog.Builder(this) builder.setTitle("Select the Type of attachment") .setItems(R.array.attachment_type, DialogInterface.OnClickListener { dialog, which -> when (which) { 0 -> //Camera photoCameraIntent() 1 -> //Gallery photoGalleryIntent() 2 -> //Location locationPlacesIntent() 3 -> //Delete Chat messages of this group deleteChatMessagesOfThisGroup() } }) val resultFL = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) if (resultFL == PackageManager.PERMISSION_DENIED) { ActivityCompat.requestPermissions(this@ChatMessagesActivity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 100) } else { builder.create().show() } } } } private fun deleteChatMessagesOfThisGroup() { MyChatManager.setmContext(this@ChatMessagesActivity) MyChatManager.deleteGroupChat(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { if (`object` as Boolean) { Handler().postDelayed({ readMessagesFromFirebase(groupId!!) }, 2000) } } }, groupId) } private fun locationPlacesIntent() { try { val builder = PlacePicker.IntentBuilder() startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST) } catch (e: GooglePlayServicesRepairableException) { e.printStackTrace() } catch (e: GooglePlayServicesNotAvailableException) { e.printStackTrace() } } private fun photoCameraIntent() { val nomeFoto = DateFormat.format("yyyy-MM-dd_hhmmss", Date()).toString() filePathImageCamera = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), nomeFoto + "camera.jpg") val it = Intent(MediaStore.ACTION_IMAGE_CAPTURE) it.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(filePathImageCamera)) startActivityForResult(it, IMAGE_CAMERA_REQUEST) } private fun photoGalleryIntent() { val intent = Intent() intent.type = "image/*" intent.action = Intent.ACTION_GET_CONTENT startActivityForResult(Intent.createChooser(intent, "Get Photo From"), IMAGE_GALLERY_REQUEST) } /** * Check if group exists, if exists then download the chat data. * If group doesn't exists, then wait till the first message is sent. * * * When first message is sent. * * Check if user2 node is present or not, if not create user2 node. Then, * * Create a groupID of these two by calling getHash(uid1,uid2) * * Create a group with 2 members, group flag set to false. Then add group id in user1, user2 to be true * * Then add the message under the MESSAGE->GROUPID. */ fun sendMessage(message: String) { when (type) { AppConstants.ONE_ON_ONE_CHAT -> { if (groupIsPresent) { sendMessageToGroup(message) } else { /* if (DataConstants.userMap?.containsKey(user2Id)!!) { user2 = DataConstants.userMap?.get(user2Id)!! //createGroupOfTwo(sCurrentUser, user2) } else { //User2 node is not there so create one. user2.email = "[email protected]" user2.name = "Sky Wall Treasure" user2.image_url = "https://lh6.googleusercontent.com/-x8DMU8TwQWU/AAAAAAAAAAI/AAAAAAAALQA/waA51g0k3GA/s96-c/photo.jpg" user2.uid = user2Id user2.group = hashMapOf()*/ } } AppConstants.GROUP_CHAT -> { sendMessageToGroup(message) } } } private fun createGroupOfTwo(user2: UserModel, message: String?) { MyChatManager.createOneOnOneChatGroup(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { groupIsPresent = true readMessagesFromFirebase(groupId!!) btnSend.visibility = View.VISIBLE if (message != null) { sendMessageToGroup(message) } } }, user2Id, user2, NetworkConstants.CREATE_ONE_ON_ONE_GROUP) } private fun sendMessageToGroup(message: String) { var cal: Calendar = Calendar.getInstance() var read_status_temp: HashMap<String, Boolean> = hashMapOf() /* for (member in groupMembersMap?.get(groupId!!)!!) { if (member.uid == sCurrentUser?.uid) { read_status_temp.put(member.uid!!, true) } else { read_status_temp.put(member.uid!!, false) } }*/ var messageModel: MessageModel? = MessageModel(message, sCurrentUser?.uid, cal.timeInMillis.toString(), read_status = read_status_temp) MyChatManager.sendMessageToAGroup(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { et_chat.setText("") Handler().postDelayed({ chat_messages_recycler.scrollToPosition(newAdapter?.mSnapshots?.mSnapshots?.count()!!) }, 1000) } }, NetworkConstants.SEND_MESSAGE_REQUEST, groupId, messageModel) } override fun onStop() { super.onStop() getLastMessageAndUpdateUnreadCount() } var newAdapter: InfiniteFirebaseRecyclerAdapter<MessageModel, ViewHolder>? = null private fun readMessagesFromFirebase(groupId: String) { var currentGroup = DataConstants.sGroupMap?.get(groupId) var time = Calendar.getInstance().timeInMillis var deleteTill: String = currentGroup?.members?.get(sCurrentUser?.uid)?.delete_till!! mFirebaseDatabaseReference = FirebaseDatabase.getInstance().reference var itemCount: Int = 10 var ref: Query = mFirebaseDatabaseReference?.child(FirebaseConstants.MESSAGES) ?.child(groupId)!! newAdapter = object : InfiniteFirebaseRecyclerAdapter<MessageModel, ViewHolder>(MessageModel::class.java, R.layout.item_chat_row, ViewHolder::class.java, ref, itemCount, deleteTill, chat_messages_recycler) { override fun populateViewHolder(viewHolder: ViewHolder?, model: MessageModel?, position: Int) { val viewHolder = viewHolder as ViewHolder val chatMessage = model!! if (chatMessage.sender_id.toString() == sCurrentUser?.uid) { viewHolder.llParent.gravity = Gravity.END viewHolder.llChild.background = ContextCompat.getDrawable(this@ChatMessagesActivity, R.drawable.chat_bubble_grey_sender) viewHolder.name.text = "You" } else { viewHolder.llParent.gravity = Gravity.START viewHolder.name.text = DataConstants.userMap?.get(chatMessage.sender_id!!)?.name viewHolder.llChild.background = ContextCompat.getDrawable(viewHolder.llParent.context, R.drawable.chat_bubble_grey) } viewHolder.message.text = chatMessage.message try { viewHolder.timestamp.text = MyTextUtil().getTimestamp(chatMessage.timestamp?.toLong()!!) } catch (e: Exception) { e.printStackTrace() } viewHolder.rlName.layoutParams.width = viewHolder.message.layoutParams.width } override fun getItemCount(): Int { return super.getItemCount() } } chat_messages_recycler.setLayoutManager(mLinearLayoutManager) //chat_messages_recycler.setAdapter(firebaseAdapter) chat_messages_recycler.setAdapter(newAdapter) chat_messages_recycler.scrollToPosition(itemCount) btnSend.visibility = View.VISIBLE progressDialog?.hide() chat_messages_recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (IsRecyclerViewAtTop() && newState == RecyclerView.SCROLL_STATE_IDLE) { newAdapter?.more() } } override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { } }) } private fun IsRecyclerViewAtTop(): Boolean { return if (chat_messages_recycler.getChildCount() == 0) true else chat_messages_recycler.getChildAt(0).getTop() == 0 } protected override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { val storageRef = storage.getReferenceFromUrl(NetworkConstants.URL_STORAGE_REFERENCE).child(NetworkConstants.FOLDER_STORAGE_IMG) if (requestCode == IMAGE_GALLERY_REQUEST) { if (resultCode == RESULT_OK) { val selectedImageUri = data.data if (selectedImageUri != null) { sendFileFirebase(storageRef, selectedImageUri) } else { //URI IS NULL } } } else if (requestCode == IMAGE_CAMERA_REQUEST) { if (resultCode == RESULT_OK) { if (filePathImageCamera != null && filePathImageCamera!!.exists()) { val imageCameraRef = storageRef.child(filePathImageCamera!!.getName() + "_camera") sendFileFirebase(imageCameraRef, filePathImageCamera!!) } else { //IS NULL } } } else if (requestCode == PLACE_PICKER_REQUEST) { if (resultCode == RESULT_OK) { val place = PlacePicker.getPlace(this, data) if (place != null) { val latLng = place.latLng val mapModel = LocationModel(latLng.latitude.toString() + "", latLng.longitude.toString() + "") //val chatModel = MessageModel(tfUserModel.getUserId(), ffUserModel.getUserId(), ffUserModel, Calendar.getInstance().time.time.toString() + "", mapModel) // mFirebaseDatabaseReference.child(deedId).child(CHAT_REFERENCE).child(seekerProviderKey).push().setValue(chatModel) } else { //PLACE IS NULL } } } } private fun sendFileFirebase(storageReference: StorageReference?, file: File) { if (storageReference != null) { val uploadTask = storageReference.putFile(Uri.fromFile(file)) uploadTask.addOnFailureListener { e -> Log.e("", "onFailure sendFileFirebase " + e.message) }.addOnSuccessListener { taskSnapshot -> Log.i("", "onSuccess sendFileFirebase") val downloadUrl = taskSnapshot.downloadUrl val fileModel = FileModel("img", downloadUrl!!.toString(), file.name, file.length().toString() + "") // val chatModel = MessageModel(tfUserModel.getUserId(), ffUserModel.getUserId(), ffUserModel, Calendar.getInstance().time.time.toString() + "", fileModel) // mFirebaseDatabaseReference.child(deedId).child(CHAT_REFERENCE).child(seekerProviderKey).push().setValue(chatModel) } } else { //IS NULL } } private fun sendFileFirebase(storageReference: StorageReference?, file: Uri) { if (storageReference != null) { val name = DateFormat.format("yyyy-MM-dd_hhmmss", Date()).toString() val imageGalleryRef = storageReference.child(name + "_gallery") val uploadTask = imageGalleryRef.putFile(file) uploadTask.addOnFailureListener { e -> Log.e("", "onFailure sendFileFirebase " + e.message) }.addOnSuccessListener { taskSnapshot -> Log.i("", "onSuccess sendFileFirebase") val downloadUrl = taskSnapshot.downloadUrl val fileModel = FileModel("img", downloadUrl!!.toString(), name, "") // val chatModel = MessageModel(tfUserModel.getUserId(), ffUserModel.getUserId(), ffUserModel, Calendar.getInstance().time.time.toString() + "", fileModel) // mFirebaseDatabaseReference.child(deedId).child(CHAT_REFERENCE).child(seekerProviderKey).push().setValue(chatModel) } } else { //IS NULL } } }
mit
8da3579867a0963586c5431dfefc40d4
39.673797
215
0.60759
5.041538
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/substring/ReplaceSubstringWithIndexingOperationInspection.kt
1
2392
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.substring import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.psi.KtConstantExpression import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator class ReplaceSubstringWithIndexingOperationInspection : ReplaceSubstringInspection() { override fun inspectionText(element: KtDotQualifiedExpression): String = KotlinBundle.message("inspection.replace.substring.with.indexing.operation.display.name") override val defaultFixText: String get() = KotlinBundle.message("replace.substring.call.with.indexing.operation.call") override val isAlwaysStable: Boolean = true override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) { val expression = element.callExpression?.valueArguments?.firstOrNull()?.getArgumentExpression() ?: return element.replaceWith("$0[$1]", expression) } override fun isApplicableInner(element: KtDotQualifiedExpression): Boolean { val arguments = element.callExpression?.valueArguments ?: return false if (arguments.size != 2) return false val arg1 = element.getValueArgument(0) ?: return false val arg2 = element.getValueArgument(1) ?: return false return arg1 + 1 == arg2 } private fun KtDotQualifiedExpression.getValueArgument(index: Int): Int? { val bindingContext = analyze() val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return null val expression = resolvedCall.call.valueArguments[index].getArgumentExpression() as? KtConstantExpression ?: return null val constant = ConstantExpressionEvaluator.getConstant(expression, bindingContext) ?: return null val constantType = bindingContext.getType(expression) ?: return null return constant.getValue(constantType) as? Int } }
apache-2.0
5bac692bb025098779bf54db4d6c0f53
53.386364
158
0.773829
5.067797
false
false
false
false
siosio/intellij-community
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModifiableRootModelBridgeImpl.kt
1
26224
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots import com.intellij.configurationStore.serializeStateInto import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.ModuleOrderEnumerator import com.intellij.openapi.roots.impl.RootConfigurationAccessor import com.intellij.openapi.roots.impl.RootModelBase.CollectDependentModules import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtilRt import com.intellij.util.SmartList import com.intellij.util.isEmpty import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.getInstance import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeModifiableBase import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity import com.intellij.workspaceModel.ide.legacyBridge.ModifiableRootModelBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleExtensionBridge import com.intellij.workspaceModel.storage.CachedValue import com.intellij.workspaceModel.storage.WorkspaceEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Element import org.jetbrains.jps.model.module.JpsModuleSourceRoot import org.jetbrains.jps.model.module.JpsModuleSourceRootType import java.util.concurrent.ConcurrentHashMap class ModifiableRootModelBridgeImpl( diff: WorkspaceEntityStorageBuilder, override val moduleBridge: ModuleBridge, override val accessor: RootConfigurationAccessor, cacheStorageResult: Boolean = true ) : LegacyBridgeModifiableBase(diff, cacheStorageResult), ModifiableRootModelBridge, ModuleRootModelBridge { /* We save the module entity for the following case: - Modifiable model created - module disposed - modifiable model used This case can appear, for example, during maven import moduleEntity would be removed from this diff after module disposing */ private var savedModuleEntity: ModuleEntity init { savedModuleEntity = entityStorageOnDiff.current.findModuleEntity(module) ?: error("Cannot find module entity for '$moduleBridge'") } override fun getModificationCount(): Long = diff.modificationCount private val extensionsDisposable = Disposer.newDisposable() private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project) private val extensionsDelegate = lazy { RootModelBridgeImpl.loadExtensions(storage = entityStorageOnDiff, module = module, diff = diff, writable = true, parentDisposable = extensionsDisposable) } private val extensions by extensionsDelegate private val sourceRootPropertiesMap = ConcurrentHashMap<VirtualFileUrl, JpsModuleSourceRoot>() internal val moduleEntity: ModuleEntity get() { val actualModuleEntity = entityStorageOnDiff.current.findModuleEntity(module) ?: return savedModuleEntity savedModuleEntity = actualModuleEntity return actualModuleEntity } private val moduleLibraryTable = ModifiableModuleLibraryTableBridge(this) /** * Contains instances of OrderEntries edited via [ModifiableRootModel] interfaces; we need to keep references to them to update their indices; * it should be used for modifications only, in order to read actual state one need to use [orderEntriesArray]. */ private val mutableOrderEntries: ArrayList<OrderEntryBridge> by lazy { ArrayList<OrderEntryBridge>().also { addOrderEntries(moduleEntity.dependencies, it) } } /** * Provides cached value for [mutableOrderEntries] converted to an array to avoid creating array each time [getOrderEntries] is called; * also it updates instances in [mutableOrderEntries] when underlying entities are changed via [WorkspaceModel] interface (e.g. when a * library referenced from [LibraryOrderEntry] is renamed). */ private val orderEntriesArrayValue: CachedValue<Array<OrderEntry>> = CachedValue { storage -> val dependencies = storage.findModuleEntity(module)?.dependencies ?: return@CachedValue emptyArray() if (mutableOrderEntries.size == dependencies.size) { //keep old instances of OrderEntries if possible (i.e. if only some properties of order entries were changes via WorkspaceModel) for (i in mutableOrderEntries.indices) { if (dependencies[i] != mutableOrderEntries[i].item && dependencies[i].javaClass == mutableOrderEntries[i].item.javaClass) { mutableOrderEntries[i].item = dependencies[i] } } } else { mutableOrderEntries.clear() addOrderEntries(dependencies, mutableOrderEntries) } mutableOrderEntries.toTypedArray() } private val orderEntriesArray get() = entityStorageOnDiff.cachedValue(orderEntriesArrayValue) private fun addOrderEntries(dependencies: List<ModuleDependencyItem>, target: MutableList<OrderEntryBridge>) = dependencies.mapIndexedTo(target) { index, item -> RootModelBridgeImpl.toOrderEntry(item, index, this, this::updateDependencyItem) } private val contentEntriesImplValue: CachedValue<List<ModifiableContentEntryBridge>> = CachedValue { storage -> val moduleEntity = storage.findModuleEntity(module) ?: return@CachedValue emptyList<ModifiableContentEntryBridge>() val contentEntries = moduleEntity.contentRoots.sortedBy { it.url.url }.toList() contentEntries.map { ModifiableContentEntryBridge( diff = diff, contentEntryUrl = it.url, modifiableRootModel = this ) } } private fun updateDependencyItem(index: Int, transformer: (ModuleDependencyItem) -> ModuleDependencyItem) { val oldItem = moduleEntity.dependencies[index] val newItem = transformer(oldItem) if (oldItem == newItem) return diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { val copy = dependencies.toMutableList() copy[index] = newItem dependencies = copy } } override val storage: WorkspaceEntityStorage get() = entityStorageOnDiff.current override fun getOrCreateJpsRootProperties(sourceRootUrl: VirtualFileUrl, creator: () -> JpsModuleSourceRoot): JpsModuleSourceRoot { return sourceRootPropertiesMap.computeIfAbsent(sourceRootUrl) { creator() } } override fun removeCachedJpsRootProperties(sourceRootUrl: VirtualFileUrl) { sourceRootPropertiesMap.remove(sourceRootUrl) } private val contentEntries get() = entityStorageOnDiff.cachedValue(contentEntriesImplValue) override fun getProject(): Project = moduleBridge.project override fun addContentEntry(root: VirtualFile): ContentEntry = addContentEntry(root.url) override fun addContentEntry(url: String): ContentEntry { assertModelIsLive() val virtualFileUrl = virtualFileManager.fromUrl(url) val existingEntry = contentEntries.firstOrNull { it.contentEntryUrl == virtualFileUrl } if (existingEntry != null) { return existingEntry } diff.addContentRootEntity( module = moduleEntity, excludedUrls = emptyList(), excludedPatterns = emptyList(), url = virtualFileUrl ) // TODO It's N^2 operations since we need to recreate contentEntries every time return contentEntries.firstOrNull { it.contentEntryUrl == virtualFileUrl } ?: error("addContentEntry: unable to find content entry after adding: $url to module ${moduleEntity.name}") } override fun removeContentEntry(entry: ContentEntry) { assertModelIsLive() val entryImpl = entry as ModifiableContentEntryBridge val contentEntryUrl = entryImpl.contentEntryUrl val entity = currentModel.contentEntities.firstOrNull { it.url == contentEntryUrl } ?: error("ContentEntry $entry does not belong to modifiableRootModel of module ${moduleBridge.name}") entry.clearSourceFolders() diff.removeEntity(entity) if (assertChangesApplied && contentEntries.any { it.url == contentEntryUrl.url }) { error("removeContentEntry: removed content entry url '$contentEntryUrl' still exists after removing") } } override fun addOrderEntry(orderEntry: OrderEntry) { assertModelIsLive() when (orderEntry) { is LibraryOrderEntryBridge -> { if (orderEntry.isModuleLevel) { moduleLibraryTable.addLibraryCopy(orderEntry.library as LibraryBridgeImpl, orderEntry.isExported, orderEntry.libraryDependencyItem.scope) } else { appendDependency(orderEntry.libraryDependencyItem) } } is ModuleOrderEntry -> orderEntry.module?.let { addModuleOrderEntry(it) } ?: error("Module is empty: $orderEntry") is ModuleSourceOrderEntry -> appendDependency(ModuleDependencyItem.ModuleSourceDependency) is InheritedJdkOrderEntry -> appendDependency(ModuleDependencyItem.InheritedSdkDependency) is ModuleJdkOrderEntry -> appendDependency((orderEntry as SdkOrderEntryBridge).sdkDependencyItem) else -> error("OrderEntry should not be extended by external systems") } } override fun addLibraryEntry(library: Library): LibraryOrderEntry { val libraryId = if (library is LibraryBridge) library.libraryId else { val libraryName = library.name if (libraryName.isNullOrEmpty()) { error("Library name is null or empty: $library") } LibraryId(libraryName, LibraryNameGenerator.getLibraryTableId(library.table.tableLevel)) } val libraryDependency = ModuleDependencyItem.Exportable.LibraryDependency( library = libraryId, exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE ) appendDependency(libraryDependency) return (mutableOrderEntries.lastOrNull() as? LibraryOrderEntry ?: error("Unable to find library orderEntry after adding")) } override fun addInvalidLibrary(name: String, level: String): LibraryOrderEntry { val libraryDependency = ModuleDependencyItem.Exportable.LibraryDependency( library = LibraryId(name, LibraryNameGenerator.getLibraryTableId(level)), exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE ) appendDependency(libraryDependency) return (mutableOrderEntries.lastOrNull() as? LibraryOrderEntry ?: error("Unable to find library orderEntry after adding")) } override fun addModuleOrderEntry(module: Module): ModuleOrderEntry { val moduleDependency = ModuleDependencyItem.Exportable.ModuleDependency( module = (module as ModuleBridge).moduleEntityId, productionOnTest = false, exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE ) appendDependency(moduleDependency) return mutableOrderEntries.lastOrNull() as? ModuleOrderEntry ?: error("Unable to find module orderEntry after adding") } override fun addInvalidModuleEntry(name: String): ModuleOrderEntry { val moduleDependency = ModuleDependencyItem.Exportable.ModuleDependency( module = ModuleId(name), productionOnTest = false, exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE ) appendDependency(moduleDependency) return mutableOrderEntries.lastOrNull() as? ModuleOrderEntry ?: error("Unable to find module orderEntry after adding") } internal fun appendDependency(dependency: ModuleDependencyItem) { mutableOrderEntries.add(RootModelBridgeImpl.toOrderEntry(dependency, mutableOrderEntries.size, this, this::updateDependencyItem)) entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = dependencies + dependency } } internal fun insertDependency(dependency: ModuleDependencyItem, position: Int): OrderEntryBridge { val last = position == mutableOrderEntries.size val newEntry = RootModelBridgeImpl.toOrderEntry(dependency, position, this, this::updateDependencyItem) if (last) { mutableOrderEntries.add(newEntry) } else { mutableOrderEntries.add(position, newEntry) for (i in position + 1 until mutableOrderEntries.size) { mutableOrderEntries[i].updateIndex(i) } } entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = if (last) dependencies + dependency else dependencies.subList(0, position) + dependency + dependencies.subList(position, dependencies.size) } return newEntry } internal fun removeDependencies(filter: (Int, ModuleDependencyItem) -> Boolean) { val newDependencies = ArrayList<ModuleDependencyItem>() val newOrderEntries = ArrayList<OrderEntryBridge>() val oldDependencies = moduleEntity.dependencies for (i in oldDependencies.indices) { if (!filter(i, oldDependencies[i])) { newDependencies.add(oldDependencies[i]) val entryBridge = mutableOrderEntries[i] entryBridge.updateIndex(newOrderEntries.size) newOrderEntries.add(entryBridge) } } mutableOrderEntries.clear() mutableOrderEntries.addAll(newOrderEntries) entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = newDependencies } } override fun findModuleOrderEntry(module: Module): ModuleOrderEntry? { return orderEntries.filterIsInstance<ModuleOrderEntry>().firstOrNull { module == it.module } } override fun findLibraryOrderEntry(library: Library): LibraryOrderEntry? { if (library is LibraryBridge) { val libraryIdToFind = library.libraryId return orderEntries .filterIsInstance<LibraryOrderEntry>() .firstOrNull { libraryIdToFind == (it.library as? LibraryBridge)?.libraryId } } else { return orderEntries.filterIsInstance<LibraryOrderEntry>().firstOrNull { it.library == library } } } override fun removeOrderEntry(orderEntry: OrderEntry) { assertModelIsLive() val entryImpl = orderEntry as OrderEntryBridge val item = entryImpl.item if (mutableOrderEntries.none { it.item == item }) { LOG.error("OrderEntry $item does not belong to modifiableRootModel of module ${moduleBridge.name}") return } if (orderEntry is LibraryOrderEntryBridge && orderEntry.isModuleLevel) { moduleLibraryTable.removeLibrary(orderEntry.library as LibraryBridge) } else { val itemIndex = entryImpl.currentIndex removeDependencies { index, _ -> index == itemIndex } } } override fun rearrangeOrderEntries(newOrder: Array<out OrderEntry>) { val newOrderEntries = newOrder.mapTo(ArrayList()) { it as OrderEntryBridge } val newEntities = newOrderEntries.map { it.item } if (newEntities.toSet() != moduleEntity.dependencies.toSet()) { error("Expected the same entities as existing order entries, but in a different order") } mutableOrderEntries.clear() mutableOrderEntries.addAll(newOrderEntries) for (i in mutableOrderEntries.indices) { mutableOrderEntries[i].updateIndex(i) } entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = newEntities } } override fun clear() { for (library in moduleLibraryTable.libraries) { moduleLibraryTable.removeLibrary(library) } val currentSdk = sdk val jdkItem = currentSdk?.let { ModuleDependencyItem.SdkDependency(it.name, it.sdkType.name) } if (moduleEntity.dependencies != listOfNotNull(jdkItem, ModuleDependencyItem.ModuleSourceDependency)) { removeDependencies { _, _ -> true } if (jdkItem != null) { appendDependency(jdkItem) } appendDependency(ModuleDependencyItem.ModuleSourceDependency) } for (contentRoot in moduleEntity.contentRoots) { diff.removeEntity(contentRoot) } } fun collectChangesAndDispose(): WorkspaceEntityStorageBuilder? { assertModelIsLive() Disposer.dispose(moduleLibraryTable) if (!isChanged) { moduleLibraryTable.restoreLibraryMappingsAndDisposeCopies() disposeWithoutLibraries() return null } if (extensionsDelegate.isInitialized() && extensions.any { it.isChanged }) { val element = Element("component") for (extension in extensions) { if (extension is ModuleExtensionBridge) continue extension.commit() if (extension is PersistentStateComponent<*>) { serializeStateInto(extension, element) } else { @Suppress("DEPRECATION") extension.writeExternal(element) } } val elementAsString = JDOMUtil.writeElement(element) val customImlDataEntity = moduleEntity.customImlData if (customImlDataEntity?.rootManagerTagCustomData != elementAsString) { when { customImlDataEntity == null && !element.isEmpty() -> diff.addModuleCustomImlDataEntity( module = moduleEntity, rootManagerTagCustomData = elementAsString, customModuleOptions = emptyMap(), source = moduleEntity.entitySource ) customImlDataEntity == null && element.isEmpty() -> Unit customImlDataEntity != null && customImlDataEntity.customModuleOptions.isEmpty() && element.isEmpty() -> diff.removeEntity(customImlDataEntity) customImlDataEntity != null && customImlDataEntity.customModuleOptions.isNotEmpty() && element.isEmpty() -> diff.modifyEntity(ModifiableModuleCustomImlDataEntity::class.java, customImlDataEntity) { rootManagerTagCustomData = null } customImlDataEntity != null && !element.isEmpty() -> diff.modifyEntity(ModifiableModuleCustomImlDataEntity::class.java, customImlDataEntity) { rootManagerTagCustomData = elementAsString } else -> error("Should not be reached") } } } if (!sourceRootPropertiesMap.isEmpty()) { for (sourceRoot in moduleEntity.sourceRoots) { val actualSourceRootData = sourceRootPropertiesMap[sourceRoot.url] ?: continue SourceRootPropertiesHelper.applyChanges(diff, sourceRoot, actualSourceRootData) } } disposeWithoutLibraries() return diff } private fun areSourceRootPropertiesChanged(): Boolean { if (sourceRootPropertiesMap.isEmpty()) return false return moduleEntity.sourceRoots.any { sourceRoot -> val actualSourceRootData = sourceRootPropertiesMap[sourceRoot.url] actualSourceRootData != null && !SourceRootPropertiesHelper.hasEqualProperties(sourceRoot, actualSourceRootData) } } override fun commit() { val diff = collectChangesAndDispose() ?: return val moduleDiff = module.diff if (moduleDiff != null) { moduleDiff.addDiff(diff) } else { WorkspaceModel.getInstance(project).updateProjectModel { it.addDiff(diff) } } postCommit() } override fun prepareForCommit() { collectChangesAndDispose() } override fun postCommit() { moduleLibraryTable.disposeOriginalLibrariesAndUpdateCopies() } override fun dispose() { disposeWithoutLibraries() moduleLibraryTable.restoreLibraryMappingsAndDisposeCopies() Disposer.dispose(moduleLibraryTable) } private fun disposeWithoutLibraries() { if (!modelIsCommittedOrDisposed) { Disposer.dispose(extensionsDisposable) } // No assertions here since it is ok to call dispose twice or more modelIsCommittedOrDisposed = true } override fun getModuleLibraryTable(): LibraryTable = moduleLibraryTable override fun setSdk(jdk: Sdk?) { if (jdk == null) { setSdkItem(null) if (assertChangesApplied && sdkName != null) { error("setSdk: expected sdkName is null, but got: $sdkName") } } else { if (SdkOrderEntryBridge.findSdk(jdk.name, jdk.sdkType.name) == null) { error("setSdk: sdk '${jdk.name}' type '${jdk.sdkType.name}' is not registered in ProjectJdkTable") } setInvalidSdk(jdk.name, jdk.sdkType.name) } } override fun setInvalidSdk(sdkName: String, sdkType: String) { setSdkItem(ModuleDependencyItem.SdkDependency(sdkName, sdkType)) if (assertChangesApplied && getSdkName() != sdkName) { error("setInvalidSdk: expected sdkName '$sdkName' but got '${getSdkName()}' after doing a change") } } override fun inheritSdk() { if (isSdkInherited) return setSdkItem(ModuleDependencyItem.InheritedSdkDependency) if (assertChangesApplied && !isSdkInherited) { error("inheritSdk: Sdk is still not inherited after inheritSdk()") } } // TODO compare by actual values override fun isChanged(): Boolean { if (!diff.isEmpty()) return true if (extensionsDelegate.isInitialized() && extensions.any { it.isChanged }) return true if (areSourceRootPropertiesChanged()) return true return false } override fun isWritable(): Boolean = true override fun <T : OrderEntry?> replaceEntryOfType(entryClass: Class<T>, entry: T) = throw NotImplementedError("Not implemented since it was used only by project model implementation") override fun getSdkName(): String? = orderEntries.filterIsInstance<JdkOrderEntry>().firstOrNull()?.jdkName // TODO override fun isDisposed(): Boolean = modelIsCommittedOrDisposed private fun setSdkItem(item: ModuleDependencyItem?) { removeDependencies { _, it -> it is ModuleDependencyItem.InheritedSdkDependency || it is ModuleDependencyItem.SdkDependency } if (item != null) { insertDependency(item, 0) } } private val modelValue = CachedValue { storage -> RootModelBridgeImpl( moduleEntity = storage.findModuleEntity(moduleBridge), storage = entityStorageOnDiff, itemUpdater = null, rootModel = this, updater = { transformer -> transformer(diff) } ) } internal val currentModel get() = entityStorageOnDiff.cachedValue(modelValue) override fun getExcludeRoots(): Array<VirtualFile> = currentModel.excludeRoots override fun orderEntries(): OrderEnumerator = ModuleOrderEnumerator(this, null) override fun <T : Any?> getModuleExtension(klass: Class<T>): T? { return extensions.filterIsInstance(klass).firstOrNull() } override fun getDependencyModuleNames(): Array<String> { val result = orderEntries().withoutSdk().withoutLibraries().withoutModuleSourceEntries().process(CollectDependentModules(), ArrayList()) return ArrayUtilRt.toStringArray(result) } override fun getModule(): ModuleBridge = moduleBridge override fun isSdkInherited(): Boolean = orderEntriesArray.any { it is InheritedJdkOrderEntry } override fun getOrderEntries(): Array<OrderEntry> = orderEntriesArray override fun getSourceRootUrls(): Array<String> = currentModel.sourceRootUrls override fun getSourceRootUrls(includingTests: Boolean): Array<String> = currentModel.getSourceRootUrls(includingTests) override fun getContentEntries(): Array<ContentEntry> = contentEntries.toTypedArray() override fun getExcludeRootUrls(): Array<String> = currentModel.excludeRootUrls override fun <R : Any?> processOrder(policy: RootPolicy<R>, initialValue: R): R { var result = initialValue for (orderEntry in orderEntries) { result = orderEntry.accept(policy, result) } return result } override fun getSdk(): Sdk? = (orderEntriesArray.find { it is JdkOrderEntry } as JdkOrderEntry?)?.jdk override fun getSourceRoots(): Array<VirtualFile> = currentModel.sourceRoots override fun getSourceRoots(includingTests: Boolean): Array<VirtualFile> = currentModel.getSourceRoots(includingTests) override fun getSourceRoots(rootType: JpsModuleSourceRootType<*>): MutableList<VirtualFile> = currentModel.getSourceRoots(rootType) override fun getSourceRoots(rootTypes: MutableSet<out JpsModuleSourceRootType<*>>): MutableList<VirtualFile> = currentModel.getSourceRoots(rootTypes) override fun getContentRoots(): Array<VirtualFile> = currentModel.contentRoots override fun getContentRootUrls(): Array<String> = currentModel.contentRootUrls override fun getModuleDependencies(): Array<Module> = getModuleDependencies(true) override fun getModuleDependencies(includeTests: Boolean): Array<Module> { var result: MutableList<Module>? = null for (entry in orderEntriesArray) { if (entry is ModuleOrderEntry) { val scope = entry.scope if (includeTests || scope.isForProductionCompile || scope.isForProductionRuntime) { val module = entry.module if (module != null) { if (result == null) { result = SmartList() } result.add(module) } } } } return if (result.isNullOrEmpty()) Module.EMPTY_ARRAY else result.toTypedArray() } companion object { private val LOG = logger<ModifiableRootModelBridgeImpl>() } }
apache-2.0
683a7db611fe749255fa244bda366b03
38.316342
151
0.739513
5.583138
false
false
false
false
JetBrains/kotlin-native
shared/src/main/kotlin/org/jetbrains/kotlin/konan/Exceptions.kt
4
2004
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.konan /** * This is a common ancestor of all Kotlin/Native exceptions. */ open class KonanException(message: String = "", cause: Throwable? = null) : Exception(message, cause) /** * An error occurred during external tool invocation. Such as non-zero exit code. */ class KonanExternalToolFailure(message: String, val toolName: String, cause: Throwable? = null) : KonanException(message, cause) /** * An exception indicating a failed attempt to access some parts of Xcode (e.g. get SDK paths or version). */ class MissingXcodeException(message: String, cause: Throwable? = null) : KonanException(message, cause) /** * Native exception handling in Kotlin: terminate, wrap, etc. * Foreign exceptionMode mode is per library option: controlled by cinterop command-line option or def file property * than stored in klib manifest and used by compiler to generate appropriate handler. */ class ForeignExceptionMode { companion object { val manifestKey = "foreignExceptionMode" val default = Mode.TERMINATE fun byValue(value: String?): Mode = value?.let { Mode.values().find { it.value == value } ?: throw IllegalArgumentException("Illegal ForeignExceptionMode $value") } ?: default } enum class Mode(val value: String) { TERMINATE("terminate"), OBJC_WRAP("objc-wrap") } }
apache-2.0
9016921d4299dfe41bba87d119b1067b
37.538462
128
0.711577
4.26383
false
false
false
false
androidx/androidx
compose/material3/material3/src/androidMain/kotlin/androidx/compose/material3/ExposedDropdownMenu.kt
3
28217
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.material3 import android.graphics.Rect import android.view.View import android.view.ViewTreeObserver import androidx.compose.animation.core.MutableTransitionState import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.waitForUpOrCancellation import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.width import androidx.compose.foundation.text.selection.LocalTextSelectionColors import androidx.compose.foundation.text.selection.TextSelectionColors import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowDropDown import androidx.compose.material3.internal.ExposedDropdownMenuPopup import androidx.compose.material3.tokens.FilledAutocompleteTokens import androidx.compose.material3.tokens.OutlinedAutocompleteTokens import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.draw.rotate import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.boundsInWindow import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.node.Ref import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.onClick import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp import kotlin.math.max /** * <a href="https://m3.material.io/components/menus/overview" class="external" target="_blank">Material Design Exposed Dropdown Menu</a>. * * Menus display a list of choices on a temporary surface. They appear when users interact with a * button, action, or other control. * * Exposed dropdown menus display the currently selected item in a text field to which the menu is * anchored. In some cases, it can accept and display user input (whether or not it’s listed as a * menu choice). If the text field input is used to filter results in the menu, the component is * also known as "autocomplete" or a "combobox". * * ![Exposed dropdown menu image](https://developer.android.com/images/reference/androidx/compose/material3/exposed-dropdown-menu.png) * * The [ExposedDropdownMenuBox] is expected to contain a [TextField] (or [OutlinedTextField]) and * [ExposedDropdownMenuBoxScope.ExposedDropdownMenu] as content. * * An example of read-only Exposed Dropdown Menu: * @sample androidx.compose.material3.samples.ExposedDropdownMenuSample * * An example of editable Exposed Dropdown Menu: * @sample androidx.compose.material3.samples.EditableExposedDropdownMenuSample * * @param expanded whether the menu is expanded or not * @param onExpandedChange called when the exposed dropdown menu is clicked and the expansion state * changes. * @param modifier the [Modifier] to be applied to this exposed dropdown menu * @param content the content of this exposed dropdown menu, typically a [TextField] and an * [ExposedDropdownMenuBoxScope.ExposedDropdownMenu]. The [TextField] within [content] should be * passed the [ExposedDropdownMenuBoxScope.menuAnchor] modifier for proper menu behavior. */ @ExperimentalMaterial3Api @Composable fun ExposedDropdownMenuBox( expanded: Boolean, onExpandedChange: (Boolean) -> Unit, modifier: Modifier = Modifier, content: @Composable ExposedDropdownMenuBoxScope.() -> Unit ) { val density = LocalDensity.current val view = LocalView.current var width by remember { mutableStateOf(0) } var menuHeight by remember { mutableStateOf(0) } val verticalMarginInPx = with(density) { MenuVerticalMargin.roundToPx() } val coordinates = remember { Ref<LayoutCoordinates>() } val focusRequester = remember { FocusRequester() } val scope = remember(expanded, onExpandedChange, density, menuHeight, width) { object : ExposedDropdownMenuBoxScope { override fun Modifier.menuAnchor(): Modifier { return composed(inspectorInfo = debugInspectorInfo { name = "menuAnchor" }) { onGloballyPositioned { width = it.size.width coordinates.value = it updateHeight( view.rootView, coordinates.value, verticalMarginInPx ) { newHeight -> menuHeight = newHeight } }.expandable( expanded = expanded, onExpandedChange = { onExpandedChange(!expanded) }, ).focusRequester(focusRequester) } } override fun Modifier.exposedDropdownSize(matchTextFieldWidth: Boolean): Modifier { return with(density) { heightIn(max = menuHeight.toDp()).let { if (matchTextFieldWidth) { it.width(width.toDp()) } else { it } } } } } } Box(modifier) { scope.content() } SideEffect { if (expanded) focusRequester.requestFocus() } DisposableEffect(view) { val listener = OnGlobalLayoutListener(view) { // We want to recalculate the menu height on relayout - e.g. when keyboard shows up. updateHeight(view.rootView, coordinates.value, verticalMarginInPx) { newHeight -> menuHeight = newHeight } } onDispose { listener.dispose() } } } /** * Subscribes to onGlobalLayout and correctly removes the callback when the View is detached. * Logic copied from AndroidPopup.android.kt. */ private class OnGlobalLayoutListener( private val view: View, private val onGlobalLayoutCallback: () -> Unit ) : View.OnAttachStateChangeListener, ViewTreeObserver.OnGlobalLayoutListener { private var isListeningToGlobalLayout = false init { view.addOnAttachStateChangeListener(this) registerOnGlobalLayoutListener() } override fun onViewAttachedToWindow(p0: View) = registerOnGlobalLayoutListener() override fun onViewDetachedFromWindow(p0: View) = unregisterOnGlobalLayoutListener() override fun onGlobalLayout() = onGlobalLayoutCallback() private fun registerOnGlobalLayoutListener() { if (isListeningToGlobalLayout || !view.isAttachedToWindow) return view.viewTreeObserver.addOnGlobalLayoutListener(this) isListeningToGlobalLayout = true } private fun unregisterOnGlobalLayoutListener() { if (!isListeningToGlobalLayout) return view.viewTreeObserver.removeOnGlobalLayoutListener(this) isListeningToGlobalLayout = false } fun dispose() { unregisterOnGlobalLayoutListener() view.removeOnAttachStateChangeListener(this) } } /** * Scope for [ExposedDropdownMenuBox]. */ @ExperimentalMaterial3Api interface ExposedDropdownMenuBoxScope { /** * Modifier which should be applied to a [TextField] (or [OutlinedTextField]) placed inside the * scope. It's responsible for properly anchoring the [ExposedDropdownMenu], handling semantics * of the component, and requesting focus. */ fun Modifier.menuAnchor(): Modifier /** * Modifier which should be applied to an [ExposedDropdownMenu] placed inside the scope. It's * responsible for setting the width of the [ExposedDropdownMenu], which will match the width of * the [TextField] (if [matchTextFieldWidth] is set to true). It will also change the height of * [ExposedDropdownMenu], so it'll take the largest possible height to not overlap the * [TextField] and the software keyboard. * * @param matchTextFieldWidth whether the menu should match the width of the text field to which * it's attached. If set to `true`, the width will match the width of the text field. */ fun Modifier.exposedDropdownSize( matchTextFieldWidth: Boolean = true ): Modifier /** * Popup which contains content for Exposed Dropdown Menu. Should be used inside the content of * [ExposedDropdownMenuBox]. * * @param expanded whether the menu is expanded * @param onDismissRequest called when the user requests to dismiss the menu, such as by * tapping outside the menu's bounds * @param modifier the [Modifier] to be applied to this menu * @param content the content of the menu */ @Composable fun ExposedDropdownMenu( expanded: Boolean, onDismissRequest: () -> Unit, modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit ) { // TODO(b/202810604): use DropdownMenu when PopupProperties constructor is stable // return DropdownMenu( // expanded = expanded, // onDismissRequest = onDismissRequest, // modifier = modifier.exposedDropdownSize(), // properties = ExposedDropdownMenuDefaults.PopupProperties, // content = content // ) val expandedStates = remember { MutableTransitionState(false) } expandedStates.targetState = expanded if (expandedStates.currentState || expandedStates.targetState) { val transformOriginState = remember { mutableStateOf(TransformOrigin.Center) } val density = LocalDensity.current val popupPositionProvider = DropdownMenuPositionProvider( DpOffset.Zero, density ) { anchorBounds, menuBounds -> transformOriginState.value = calculateTransformOrigin(anchorBounds, menuBounds) } ExposedDropdownMenuPopup( onDismissRequest = onDismissRequest, popupPositionProvider = popupPositionProvider ) { DropdownMenuContent( expandedStates = expandedStates, transformOriginState = transformOriginState, modifier = modifier.exposedDropdownSize(), content = content ) } } } } /** * Contains default values used by Exposed Dropdown Menu. */ @ExperimentalMaterial3Api object ExposedDropdownMenuDefaults { /** * Default trailing icon for Exposed Dropdown Menu. * * @param expanded whether [ExposedDropdownMenuBoxScope.ExposedDropdownMenu] is expanded or not. * Affects the appearance of the icon. */ @ExperimentalMaterial3Api @Composable fun TrailingIcon(expanded: Boolean) { Icon( Icons.Filled.ArrowDropDown, null, Modifier.rotate(if (expanded) 180f else 0f) ) } /** * Creates a [TextFieldColors] that represents the default input text, container, and content * (including label, placeholder, leading and trailing icons) colors used in a [TextField] * within an [ExposedDropdownMenuBox]. * * @param textColor the color used for the input text of this text field * @param disabledTextColor the color used for the input text of this text field when disabled * @param containerColor the container color for this text field * @param cursorColor the cursor color for this text field * @param errorCursorColor the cursor color for this text field when in error state * @param selectionColors the colors used when the input text of this text field is selected * @param focusedIndicatorColor the indicator color for this text field when focused * @param unfocusedIndicatorColor the indicator color for this text field when not focused * @param disabledIndicatorColor the indicator color for this text field when disabled * @param errorIndicatorColor the indicator color for this text field when in error state * @param focusedLeadingIconColor the leading icon color for this text field when focused * @param unfocusedLeadingIconColor the leading icon color for this text field when not focused * @param disabledLeadingIconColor the leading icon color for this text field when disabled * @param errorLeadingIconColor the leading icon color for this text field when in error state * @param focusedTrailingIconColor the trailing icon color for this text field when focused * @param unfocusedTrailingIconColor the trailing icon color for this text field when not * focused * @param disabledTrailingIconColor the trailing icon color for this text field when disabled * @param errorTrailingIconColor the trailing icon color for this text field when in error state * @param focusedLabelColor the label color for this text field when focused * @param unfocusedLabelColor the label color for this text field when not focused * @param disabledLabelColor the label color for this text field when disabled * @param errorLabelColor the label color for this text field when in error state * @param placeholderColor the placeholder color for this text field * @param disabledPlaceholderColor the placeholder color for this text field when disabled */ @Composable fun textFieldColors( textColor: Color = FilledAutocompleteTokens.FieldInputTextColor.toColor(), disabledTextColor: Color = FilledAutocompleteTokens.FieldDisabledInputTextColor.toColor() .copy(alpha = FilledAutocompleteTokens.FieldDisabledInputTextOpacity), containerColor: Color = FilledAutocompleteTokens.TextFieldContainerColor.toColor(), cursorColor: Color = FilledAutocompleteTokens.TextFieldCaretColor.toColor(), errorCursorColor: Color = FilledAutocompleteTokens.TextFieldErrorFocusCaretColor.toColor(), selectionColors: TextSelectionColors = LocalTextSelectionColors.current, focusedIndicatorColor: Color = FilledAutocompleteTokens.TextFieldFocusActiveIndicatorColor.toColor(), unfocusedIndicatorColor: Color = FilledAutocompleteTokens.TextFieldActiveIndicatorColor.toColor(), disabledIndicatorColor: Color = FilledAutocompleteTokens.TextFieldDisabledActiveIndicatorColor.toColor() .copy(alpha = FilledAutocompleteTokens.TextFieldDisabledActiveIndicatorOpacity), errorIndicatorColor: Color = FilledAutocompleteTokens.TextFieldErrorActiveIndicatorColor.toColor(), focusedLeadingIconColor: Color = FilledAutocompleteTokens.TextFieldFocusLeadingIconColor.toColor(), unfocusedLeadingIconColor: Color = FilledAutocompleteTokens.TextFieldLeadingIconColor.toColor(), disabledLeadingIconColor: Color = FilledAutocompleteTokens.TextFieldDisabledLeadingIconColor.toColor() .copy(alpha = FilledAutocompleteTokens.TextFieldDisabledLeadingIconOpacity), errorLeadingIconColor: Color = FilledAutocompleteTokens.TextFieldErrorLeadingIconColor.toColor(), focusedTrailingIconColor: Color = FilledAutocompleteTokens.TextFieldFocusTrailingIconColor.toColor(), unfocusedTrailingIconColor: Color = FilledAutocompleteTokens.TextFieldTrailingIconColor.toColor(), disabledTrailingIconColor: Color = FilledAutocompleteTokens.TextFieldDisabledTrailingIconColor.toColor() .copy(alpha = FilledAutocompleteTokens.TextFieldDisabledTrailingIconOpacity), errorTrailingIconColor: Color = FilledAutocompleteTokens.TextFieldErrorTrailingIconColor.toColor(), focusedLabelColor: Color = FilledAutocompleteTokens.FieldFocusLabelTextColor.toColor(), unfocusedLabelColor: Color = FilledAutocompleteTokens.FieldLabelTextColor.toColor(), disabledLabelColor: Color = FilledAutocompleteTokens.FieldDisabledLabelTextColor.toColor(), errorLabelColor: Color = FilledAutocompleteTokens.FieldErrorLabelTextColor.toColor(), placeholderColor: Color = FilledAutocompleteTokens.FieldSupportingTextColor.toColor(), disabledPlaceholderColor: Color = FilledAutocompleteTokens.FieldDisabledInputTextColor.toColor() .copy(alpha = FilledAutocompleteTokens.FieldDisabledInputTextOpacity) ): TextFieldColors = TextFieldDefaults.textFieldColors( textColor = textColor, disabledTextColor = disabledTextColor, cursorColor = cursorColor, errorCursorColor = errorCursorColor, selectionColors = selectionColors, focusedIndicatorColor = focusedIndicatorColor, unfocusedIndicatorColor = unfocusedIndicatorColor, errorIndicatorColor = errorIndicatorColor, disabledIndicatorColor = disabledIndicatorColor, focusedLeadingIconColor = focusedLeadingIconColor, unfocusedLeadingIconColor = unfocusedLeadingIconColor, disabledLeadingIconColor = disabledLeadingIconColor, errorLeadingIconColor = errorLeadingIconColor, focusedTrailingIconColor = focusedTrailingIconColor, unfocusedTrailingIconColor = unfocusedTrailingIconColor, disabledTrailingIconColor = disabledTrailingIconColor, errorTrailingIconColor = errorTrailingIconColor, containerColor = containerColor, focusedLabelColor = focusedLabelColor, unfocusedLabelColor = unfocusedLabelColor, disabledLabelColor = disabledLabelColor, errorLabelColor = errorLabelColor, placeholderColor = placeholderColor, disabledPlaceholderColor = disabledPlaceholderColor ) /** * Creates a [TextFieldColors] that represents the default input text, container, and content * (including label, placeholder, leading and trailing icons) colors used in an * [OutlinedTextField] within an [ExposedDropdownMenuBox]. * * @param textColor the color used for the input text of this text field * @param disabledTextColor the color used for the input text of this text field when disabled * @param containerColor the container color for this text field * @param cursorColor the cursor color for this text field * @param errorCursorColor the cursor color for this text field when in error state * @param selectionColors the colors used when the input text of this text field is selected * @param focusedBorderColor the border color for this text field when focused * @param unfocusedBorderColor the border color for this text field when not focused * @param disabledBorderColor the border color for this text field when disabled * @param errorBorderColor the border color for this text field when in error state * @param focusedLeadingIconColor the leading icon color for this text field when focused * @param unfocusedLeadingIconColor the leading icon color for this text field when not focused * @param disabledLeadingIconColor the leading icon color for this text field when disabled * @param errorLeadingIconColor the leading icon color for this text field when in error state * @param focusedTrailingIconColor the trailing icon color for this text field when focused * @param unfocusedTrailingIconColor the trailing icon color for this text field when not focused * @param disabledTrailingIconColor the trailing icon color for this text field when disabled * @param errorTrailingIconColor the trailing icon color for this text field when in error state * @param focusedLabelColor the label color for this text field when focused * @param unfocusedLabelColor the label color for this text field when not focused * @param disabledLabelColor the label color for this text field when disabled * @param errorLabelColor the label color for this text field when in error state * @param placeholderColor the placeholder color for this text field * @param disabledPlaceholderColor the placeholder color for this text field when disabled */ @Composable fun outlinedTextFieldColors( textColor: Color = OutlinedAutocompleteTokens.FieldInputTextColor.toColor(), disabledTextColor: Color = OutlinedAutocompleteTokens.FieldDisabledInputTextColor.toColor() .copy(alpha = OutlinedAutocompleteTokens.FieldDisabledInputTextOpacity), containerColor: Color = Color.Transparent, cursorColor: Color = OutlinedAutocompleteTokens.TextFieldCaretColor.toColor(), errorCursorColor: Color = OutlinedAutocompleteTokens.TextFieldErrorFocusCaretColor.toColor(), selectionColors: TextSelectionColors = LocalTextSelectionColors.current, focusedBorderColor: Color = OutlinedAutocompleteTokens.TextFieldFocusOutlineColor.toColor(), unfocusedBorderColor: Color = OutlinedAutocompleteTokens.TextFieldOutlineColor.toColor(), disabledBorderColor: Color = OutlinedAutocompleteTokens.TextFieldDisabledOutlineColor.toColor() .copy(alpha = OutlinedAutocompleteTokens.TextFieldDisabledOutlineOpacity), errorBorderColor: Color = OutlinedAutocompleteTokens.TextFieldErrorOutlineColor.toColor(), focusedLeadingIconColor: Color = OutlinedAutocompleteTokens.TextFieldFocusLeadingIconColor.toColor(), unfocusedLeadingIconColor: Color = OutlinedAutocompleteTokens.TextFieldLeadingIconColor.toColor(), disabledLeadingIconColor: Color = OutlinedAutocompleteTokens.TextFieldDisabledLeadingIconColor.toColor() .copy(alpha = OutlinedAutocompleteTokens.TextFieldDisabledLeadingIconOpacity), errorLeadingIconColor: Color = OutlinedAutocompleteTokens.TextFieldErrorLeadingIconColor.toColor(), focusedTrailingIconColor: Color = OutlinedAutocompleteTokens.TextFieldFocusTrailingIconColor.toColor(), unfocusedTrailingIconColor: Color = OutlinedAutocompleteTokens.TextFieldTrailingIconColor.toColor(), disabledTrailingIconColor: Color = OutlinedAutocompleteTokens.TextFieldDisabledTrailingIconColor.toColor() .copy(alpha = OutlinedAutocompleteTokens.TextFieldDisabledTrailingIconOpacity), errorTrailingIconColor: Color = OutlinedAutocompleteTokens.TextFieldErrorTrailingIconColor.toColor(), focusedLabelColor: Color = OutlinedAutocompleteTokens.FieldFocusLabelTextColor.toColor(), unfocusedLabelColor: Color = OutlinedAutocompleteTokens.FieldLabelTextColor.toColor(), disabledLabelColor: Color = OutlinedAutocompleteTokens.FieldDisabledLabelTextColor.toColor() .copy(alpha = OutlinedAutocompleteTokens.FieldDisabledLabelTextOpacity), errorLabelColor: Color = OutlinedAutocompleteTokens.FieldErrorLabelTextColor.toColor(), placeholderColor: Color = OutlinedAutocompleteTokens.FieldSupportingTextColor.toColor(), disabledPlaceholderColor: Color = OutlinedAutocompleteTokens.FieldDisabledInputTextColor.toColor() .copy(alpha = OutlinedAutocompleteTokens.FieldDisabledInputTextOpacity) ): TextFieldColors = TextFieldDefaults.outlinedTextFieldColors( textColor = textColor, disabledTextColor = disabledTextColor, cursorColor = cursorColor, errorCursorColor = errorCursorColor, selectionColors = selectionColors, focusedBorderColor = focusedBorderColor, unfocusedBorderColor = unfocusedBorderColor, errorBorderColor = errorBorderColor, disabledBorderColor = disabledBorderColor, focusedLeadingIconColor = focusedLeadingIconColor, unfocusedLeadingIconColor = unfocusedLeadingIconColor, disabledLeadingIconColor = disabledLeadingIconColor, errorLeadingIconColor = errorLeadingIconColor, focusedTrailingIconColor = focusedTrailingIconColor, unfocusedTrailingIconColor = unfocusedTrailingIconColor, disabledTrailingIconColor = disabledTrailingIconColor, errorTrailingIconColor = errorTrailingIconColor, containerColor = containerColor, focusedLabelColor = focusedLabelColor, unfocusedLabelColor = unfocusedLabelColor, disabledLabelColor = disabledLabelColor, errorLabelColor = errorLabelColor, placeholderColor = placeholderColor, disabledPlaceholderColor = disabledPlaceholderColor ) /** * Padding for [DropdownMenuItem]s within [ExposedDropdownMenuBoxScope.ExposedDropdownMenu] to * align them properly with [TextField] components. */ val ItemContentPadding: PaddingValues = PaddingValues( horizontal = ExposedDropdownMenuItemHorizontalPadding, vertical = 0.dp ) } @Suppress("ComposableModifierFactory") @Composable private fun Modifier.expandable( expanded: Boolean, onExpandedChange: () -> Unit, menuDescription: String = getString(Strings.ExposedDropdownMenu), expandedDescription: String = getString(Strings.MenuExpanded), collapsedDescription: String = getString(Strings.MenuCollapsed), ) = pointerInput(Unit) { awaitEachGesture { // Must be PointerEventPass.Initial to observe events before the text field consumes them // in the Main pass awaitFirstDown(pass = PointerEventPass.Initial) val upEvent = waitForUpOrCancellation(pass = PointerEventPass.Initial) if (upEvent != null) { onExpandedChange() } } }.semantics { stateDescription = if (expanded) expandedDescription else collapsedDescription contentDescription = menuDescription onClick { onExpandedChange() true } } private fun updateHeight( view: View, coordinates: LayoutCoordinates?, verticalMarginInPx: Int, onHeightUpdate: (Int) -> Unit ) { coordinates ?: return val visibleWindowBounds = Rect().let { view.getWindowVisibleDisplayFrame(it) it } val heightAbove = coordinates.boundsInWindow().top - visibleWindowBounds.top val heightBelow = visibleWindowBounds.bottom - visibleWindowBounds.top - coordinates.boundsInWindow().bottom onHeightUpdate(max(heightAbove, heightBelow).toInt() - verticalMarginInPx) } private val ExposedDropdownMenuItemHorizontalPadding = 16.dp
apache-2.0
e84ae41df3e0cbf12c92965db2c56414
48.761905
137
0.724331
5.515051
false
false
false
false
androidx/androidx
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/text/TextMeasurerHelperTest.kt
3
4140
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalTextApi::class) package androidx.compose.ui.text import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalFontFamilyResolver import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.text.font.createFontFamilyResolver import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @SmallTest @RunWith(AndroidJUnit4::class) class TextMeasurerHelperTest { @get:Rule val rule = createComposeRule() val context = InstrumentationRegistry.getInstrumentation().targetContext @Test fun whenFontFamilyResolverChanges_TextMeasurerShouldChange() { val fontFamilyResolver = mutableStateOf(createFontFamilyResolver(context)) val measurers = mutableSetOf<TextMeasurer>() rule.setContent { CompositionLocalProvider( LocalFontFamilyResolver provides fontFamilyResolver.value ) { val textMeasurer = rememberTextMeasurer() measurers.add(textMeasurer) } } rule.waitForIdle() // FontFamily.Resolver implementation has only instance check for equality // new instance should always be unequal to any other instance fontFamilyResolver.value = createFontFamilyResolver(context) rule.waitForIdle() assertThat(measurers.size).isEqualTo(2) } @Test fun whenDensityChanges_TextMeasurerShouldChange() { val density = mutableStateOf(Density(1f)) val measurers = mutableSetOf<TextMeasurer>() rule.setContent { CompositionLocalProvider( LocalDensity provides density.value ) { val textMeasurer = rememberTextMeasurer() measurers.add(textMeasurer) } } rule.waitForIdle() density.value = Density(2f) rule.waitForIdle() assertThat(measurers.size).isEqualTo(2) } @Test fun whenLayoutDirectionChanges_TextMeasurerShouldChange() { val layoutDirection = mutableStateOf(LayoutDirection.Ltr) val measurers = mutableSetOf<TextMeasurer>() rule.setContent { CompositionLocalProvider( LocalLayoutDirection provides layoutDirection.value ) { val textMeasurer = rememberTextMeasurer() measurers.add(textMeasurer) } } rule.waitForIdle() layoutDirection.value = LayoutDirection.Rtl rule.waitForIdle() assertThat(measurers.size).isEqualTo(2) } @Test fun whenCacheSizeChanges_TextMeasurerShouldChange() { val cacheSize = mutableStateOf(4) val measurers = mutableSetOf<TextMeasurer>() rule.setContent { val textMeasurer = rememberTextMeasurer(cacheSize = cacheSize.value) measurers.add(textMeasurer) } rule.waitForIdle() cacheSize.value = 8 rule.waitForIdle() assertThat(measurers.size).isEqualTo(2) } }
apache-2.0
a9696b6e23e802c9e645b3e42d9aaf53
31.351563
82
0.696377
5.117429
false
true
false
false
GunoH/intellij-community
uast/uast-common/src/org/jetbrains/uast/expressions/UStringConcatenationsFacade.kt
8
6422
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.expressions import com.intellij.openapi.util.TextRange import com.intellij.psi.ElementManipulators import com.intellij.psi.PsiElement import com.intellij.psi.PsiLanguageInjectionHost import com.intellij.psi.util.PartiallyKnownString import com.intellij.psi.util.StringEntry import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* /** * A helper class to work with string concatenations with variables and interpolated strings in a language-abstract way (UAST-based). * It is mostly useful for working with reference/language injections in cases when it is injected into multiple [PsiLanguageInjectionHost] joined together. * * @see PartiallyKnownString */ class UStringConcatenationsFacade private constructor(private val uContext: UExpression, val uastOperands: Sequence<UExpression>) { @Deprecated("use factory method `UStringConcatenationsFacade.createFromUExpression`", ReplaceWith("UStringConcatenationsFacade.createFromUExpression(uContext)")) @ApiStatus.Experimental constructor(uContext: UExpression) : this(uContext, buildLazyUastOperands(uContext, false) ?: emptySequence()) @get:ApiStatus.Experimental val rootUExpression: UExpression get() = uContext val psiLanguageInjectionHosts: Sequence<PsiLanguageInjectionHost> = uastOperands.mapNotNull { (it as? ULiteralExpression)?.psiLanguageInjectionHost }.distinct() /** * external (non string-literal) expressions in string interpolations and/or concatenations */ val placeholders: List<Pair<TextRange, String>> get() = segments.mapNotNull { segment -> when (segment) { is Segment.Placeholder -> segment.range to (segment.value ?: "missingValue") else -> null } } private sealed class Segment { abstract val value: String? abstract val range: TextRange abstract val uExpression: UExpression class StringLiteral(override val value: String, override val range: TextRange, override val uExpression: ULiteralExpression) : Segment() class Placeholder(override val value: String?, override val range: TextRange, override val uExpression: UExpression) : Segment() } private val segments: List<Segment> by lazy(LazyThreadSafetyMode.NONE) { val bounds = uContext.sourcePsi?.textRange ?: return@lazy emptyList<Segment>() val operandsList = uastOperands.toList() ArrayList<Segment>(operandsList.size).apply { for (i in operandsList.indices) { val operand = operandsList[i] val sourcePsi = operand.sourcePsi ?: continue val selfRange = sourcePsi.textRange if (operand is ULiteralExpression) add(Segment.StringLiteral(operand.evaluateString() ?: "", selfRange, operand)) else { val prev = operandsList.getOrNull(i - 1) val next = operandsList.getOrNull(i + 1) val start = when (prev) { null -> bounds.startOffset is ULiteralExpression -> prev.sourcePsi?.textRange?.endOffset ?: selfRange.startOffset else -> selfRange.startOffset } val end = when (next) { null -> bounds.endOffset is ULiteralExpression -> next.sourcePsi?.textRange?.startOffset ?: selfRange.endOffset else -> selfRange.endOffset } val range = TextRange.create(start, end) val evaluate = operand.evaluateString() add(Segment.Placeholder(evaluate, range, operand)) } } } } @ApiStatus.Experimental fun asPartiallyKnownString() : PartiallyKnownString = PartiallyKnownString(segments.map { segment -> segment.value?.let { value -> StringEntry.Known(value, segment.uExpression.sourcePsi, getSegmentInnerTextRange(segment)) } ?: StringEntry.Unknown(segment.uExpression.sourcePsi, getSegmentInnerTextRange(segment)) }) private fun getSegmentInnerTextRange(segment: Segment): TextRange { val sourcePsi = segment.uExpression.sourcePsi ?: throw IllegalStateException("no sourcePsi for $segment") val sourcePsiTextRange = sourcePsi.textRange val range = segment.range if (range.startOffset > sourcePsiTextRange.startOffset) return range.shiftLeft(sourcePsiTextRange.startOffset) return ElementManipulators.getValueTextRange(sourcePsi) } companion object { private fun buildLazyUastOperands(uContext: UExpression?, flatten: Boolean): Sequence<UExpression>? = when { uContext is UPolyadicExpression && isConcatenation(uContext) -> { val concatenationOperands = uContext.operands.asSequence() if (flatten) concatenationOperands.flatMap { operand -> buildLazyUastOperands(operand, true) ?: sequenceOf(operand) } else concatenationOperands } uContext is ULiteralExpression && !isConcatenation(uContext.uastParent) -> { val host = uContext.sourceInjectionHost if (host == null || !host.isValidHost) emptySequence() else sequenceOf(uContext) } else -> null } @JvmStatic @JvmOverloads fun createFromUExpression(uContext: UExpression?, flatten: Boolean = false): UStringConcatenationsFacade? { val operands = buildLazyUastOperands(uContext, flatten) ?: return null return UStringConcatenationsFacade(uContext!!, operands) } @JvmStatic fun createFromTopConcatenation(member: UExpression?): UStringConcatenationsFacade? { val topConcatenation = generateSequence(member?.uastParent, UElement::uastParent).takeWhile { isConcatenation(it) } .lastOrNull() as? UExpression ?: member ?: return null val operands = buildLazyUastOperands(topConcatenation, true) ?: return null return UStringConcatenationsFacade(topConcatenation, operands) } @JvmStatic @ApiStatus.ScheduledForRemoval @Deprecated("doesn't support concatenation for Kotlin", ReplaceWith("createFromUExpression")) fun create(context: PsiElement?): UStringConcatenationsFacade? { if (context == null || context !is PsiLanguageInjectionHost && context.firstChild !is PsiLanguageInjectionHost) { return null } val uElement = context.toUElementOfType<UExpression>() ?: return null return createFromUExpression(uElement) } } }
apache-2.0
c6001120a3c8443da4e271ef09dcea9d
42.993151
156
0.721582
5.129393
false
false
false
false
GunoH/intellij-community
uast/uast-common/src/org/jetbrains/uast/UastUtils.kt
7
9568
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmMultifileClass @file:JvmName("UastUtils") package org.jetbrains.uast import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.ArrayUtil import org.jetbrains.annotations.ApiStatus import java.io.File inline fun <reified T : UElement> UElement.getParentOfType(strict: Boolean = true): T? = getParentOfType(T::class.java, strict) @JvmOverloads fun <T : UElement> UElement.getParentOfType(parentClass: Class<out T>, strict: Boolean = true): T? { var element = (if (strict) uastParent else this) ?: return null while (true) { if (parentClass.isInstance(element)) { @Suppress("UNCHECKED_CAST") return element as T } element = element.uastParent ?: return null } } fun UElement.skipParentOfType(strict: Boolean, vararg parentClasses: Class<out UElement>): UElement? { var element = (if (strict) uastParent else this) ?: return null while (true) { if (!parentClasses.any { it.isInstance(element) }) { return element } element = element.uastParent ?: return null } } @SafeVarargs fun <T : UElement> UElement.getParentOfType( parentClass: Class<out T>, strict: Boolean = true, vararg terminators: Class<out UElement> ): T? { var element = (if (strict) uastParent else this) ?: return null while (true) { if (parentClass.isInstance(element)) { @Suppress("UNCHECKED_CAST") return element as T } if (terminators.any { it.isInstance(element) }) { return null } element = element.uastParent ?: return null } } fun <T : UElement> UElement.getParentOfType( strict: Boolean = true, firstParentClass: Class<out T>, vararg parentClasses: Class<out T> ): T? { var element = (if (strict) uastParent else this) ?: return null while (true) { if (firstParentClass.isInstance(element)) { @Suppress("UNCHECKED_CAST") return element as T } if (parentClasses.any { it.isInstance(element) }) { @Suppress("UNCHECKED_CAST") return element as T } element = element.uastParent ?: return null } } @JvmOverloads fun UElement?.getUCallExpression(searchLimit: Int = Int.MAX_VALUE): UCallExpression? { if (this == null) return null var u: UElement? = this; for (i in 1..searchLimit) { if (u == null) break if (u is UCallExpression) return u if (u is UQualifiedReferenceExpression) { val selector = u.selector if (selector is UCallExpression) return selector } u = u.uastParent } return null } fun UElement.getContainingUFile(): UFile? = getParentOfType(UFile::class.java, false) fun UElement.getContainingUClass(): UClass? = getParentOfType(UClass::class.java) fun UElement.getContainingUMethod(): UMethod? = getParentOfType(UMethod::class.java) fun UElement.getContainingUVariable(): UVariable? = getParentOfType(UVariable::class.java) fun <T : UElement> PsiElement?.findContaining(clazz: Class<T>): T? { var element = this while (element != null && element !is PsiFileSystemItem) { element.toUElement(clazz)?.let { return it } element = element.parent } return null } fun <T : UElement> PsiElement?.findAnyContaining(vararg types: Class<out T>): T? = findAnyContaining(Int.Companion.MAX_VALUE, *types) fun <T : UElement> PsiElement?.findAnyContaining(depthLimit: Int, vararg types: Class<out T>): T? { var element = this var i = 0 while (i < depthLimit && element != null && element !is PsiFileSystemItem) { element.toUElementOfExpectedTypes(*types)?.let { return it } element = element.parent i++ } return null } fun isPsiAncestor(ancestor: UElement, child: UElement): Boolean { val ancestorPsi = ancestor.sourcePsi ?: return false val childPsi = child.sourcePsi ?: return false return PsiTreeUtil.isAncestor(ancestorPsi, childPsi, false) } fun UElement.isUastChildOf(probablyParent: UElement?, strict: Boolean = false): Boolean { tailrec fun isChildOf(current: UElement?, probablyParent: UElement): Boolean { return when (current) { null -> false probablyParent -> true else -> isChildOf(current.uastParent, probablyParent) } } if (probablyParent == null) return false return isChildOf(if (strict) uastParent else this, probablyParent) } /** * Resolves the receiver element if it implements [UResolvable]. * * @return the resolved element, or null if the element was not resolved, or if the receiver element is not an [UResolvable]. */ fun UElement.tryResolve(): PsiElement? = (this as? UResolvable)?.resolve() fun UElement.tryResolveNamed(): PsiNamedElement? = (this as? UResolvable)?.resolve() as? PsiNamedElement fun UReferenceExpression?.getQualifiedName(): String? = (this?.resolve() as? PsiClass)?.qualifiedName /** * Returns the String expression value, or null if the value can't be calculated, or if the calculated value is not a String or an integral literal. */ fun UExpression.evaluateString(): String? = evaluate().takeIf { it is String || isIntegralLiteral() }?.toString() fun UExpression.skipParenthesizedExprDown(): UExpression { var expression = this while (expression is UParenthesizedExpression) { expression = expression.expression } return expression } fun skipParenthesizedExprUp(elem: UElement?): UElement? { var parent = elem while (parent is UParenthesizedExpression) { parent = parent.uastParent } return parent } /** * Get a physical [File] for this file, or null if there is no such file on disk. */ fun UFile.getIoFile(): File? = sourcePsi.virtualFile?.let { VfsUtilCore.virtualToIoFile(it) } @Deprecated("use UastFacade", ReplaceWith("UastFacade")) @ApiStatus.ScheduledForRemoval @Suppress("DEPRECATION") tailrec fun UElement.getUastContext(): UastContext { val psi = this.sourcePsi if (psi != null) { return psi.project.getService(UastContext::class.java) ?: error("UastContext not found") } return (uastParent ?: error("PsiElement should exist at least for UFile")).getUastContext() } @Deprecated("could unexpectedly throw exception", ReplaceWith("UastFacade.findPlugin")) @ApiStatus.ScheduledForRemoval tailrec fun UElement.getLanguagePlugin(): UastLanguagePlugin { val psi = this.sourcePsi if (psi != null) { return UastFacade.findPlugin(psi) ?: error("Language plugin was not found for $this (${this.javaClass.name})") } return (uastParent ?: error("PsiElement should exist at least for UFile")).getLanguagePlugin() } fun Collection<UElement?>.toPsiElements(): List<PsiElement> = mapNotNull { it?.sourcePsi } /** * A helper function for getting parents for given [PsiElement] that could be considered as identifier. * Useful for working with gutter according to recommendations in [com.intellij.codeInsight.daemon.LineMarkerProvider]. * * @see [getUParentForAnnotationIdentifier] for working with annotations */ fun getUParentForIdentifier(identifier: PsiElement): UElement? { val uIdentifier = identifier.toUElementOfType<UIdentifier>() ?: return null return uIdentifier.uastParent } /** * @param arg expression in call arguments list of [this] * @return parameter that corresponds to the [arg] in declaration to which [this] resolves */ fun UCallExpression.getParameterForArgument(arg: UExpression): PsiParameter? { val psiMethod = resolve() ?: return null val parameters = psiMethod.parameterList.parameters return parameters.withIndex().find { (i, p) -> val argumentForParameter = getArgumentForParameter(i) ?: return@find false if (wrapULiteral(argumentForParameter) == wrapULiteral(arg)) return@find true if (p.isVarArgs && argumentForParameter is UExpressionList) return@find argumentForParameter.expressions.contains(arg) return@find false }?.value } @ApiStatus.Experimental tailrec fun UElement.isLastElementInControlFlow(scopeElement: UElement? = null): Boolean = when (val parent = this.uastParent) { scopeElement -> if (scopeElement is UBlockExpression) scopeElement.expressions.lastOrNull() == this else true is UBlockExpression -> if (parent.expressions.lastOrNull() == this) parent.isLastElementInControlFlow(scopeElement) else false is UElement -> parent.isLastElementInControlFlow(scopeElement) else -> false } fun UNamedExpression.getAnnotationMethod(): PsiMethod? { val annotation: UAnnotation? = getParentOfType(UAnnotation::class.java, true) val fqn = annotation?.qualifiedName ?: return null val annotationSrc = annotation.sourcePsi if (annotationSrc == null) return null val psiClass = JavaPsiFacade.getInstance(annotationSrc.project).findClass(fqn, annotationSrc.resolveScope) if (psiClass != null && psiClass.isAnnotationType) { return ArrayUtil.getFirstElement(psiClass.findMethodsByName(this.name ?: "value", false)) } return null } val UElement.textRange: TextRange? get() = sourcePsi?.textRange /** * A helper function for getting [UMethod] for element for LineMarker. * It handles cases, when [getUParentForIdentifier] returns same `parent` for more than one `identifier`. * Such situations cause multiple LineMarkers for same declaration. */ inline fun <reified T : UDeclaration> getUParentForDeclarationLineMarkerElement(lineMarkerElement: PsiElement): T? { val parent = getUParentForIdentifier(lineMarkerElement) as? T ?: return null if (parent.uastAnchor.sourcePsiElement != lineMarkerElement) return null return parent }
apache-2.0
91dbd13a043c2ef89853ef3608adcbd8
35.246212
148
0.734218
4.294434
false
false
false
false
GunoH/intellij-community
platform/dependencies-toolwindow/src/com/intellij/dependencytoolwindow/CoroutineUtils.kt
2
3259
// 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.dependencytoolwindow import com.intellij.ide.ui.LafManager import com.intellij.ide.ui.LafManagerListener import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindowManager import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.messages.Topic import kotlinx.coroutines.* import kotlinx.coroutines.channels.ProducerScope import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.channels.trySendBlocking import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlin.coroutines.CoroutineContext val <T : Any> ExtensionPointName<T>.extensionsFlow: Flow<List<T>> get() = callbackFlow { val listener = object : ExtensionPointListener<T> { override fun extensionAdded(extension: T, pluginDescriptor: PluginDescriptor) { trySendBlocking(extensions.toList()) } override fun extensionRemoved(extension: T, pluginDescriptor: PluginDescriptor) { trySendBlocking(extensions.toList()) } } send(extensions.toList()) addExtensionPointListener(listener) awaitClose { removeExtensionPointListener(listener) } } @Service(Service.Level.PROJECT) internal class DependencyToolwindowLifecycleScope : CoroutineScope, Disposable { val dispatcher = AppExecutorUtil.getAppExecutorService().asCoroutineDispatcher() override val coroutineContext = SupervisorJob() + CoroutineName(this::class.qualifiedName!!) + dispatcher override fun dispose() { cancel("Disposing ${this::class.simpleName}") } } internal val Project.lifecycleScope: DependencyToolwindowLifecycleScope get() = service() internal val Project.contentIdMap get() = service<ContentIdMapService>().idMap.value fun <L : Any, K> Project.messageBusFlow( topic: Topic<L>, initialValue: (suspend () -> K)? = null, listener: suspend ProducerScope<K>.() -> L ): Flow<K> { return callbackFlow { initialValue?.let { send(it()) } val connection = messageBus.simpleConnect() connection.subscribe(topic, listener()) awaitClose { connection.disconnect() } } } internal val Project.lookAndFeelFlow: Flow<LafManager> get() = messageBusFlow(LafManagerListener.TOPIC, { LafManager.getInstance()!! }) { LafManagerListener { trySend(it) } } internal fun DependenciesToolWindowTabProvider.isAvailableFlow(project: Project): Flow<Boolean> { return callbackFlow { val sub = addIsAvailableChangesListener(project) { trySend(it) } awaitClose { sub.unsubscribe() } } } @Suppress("UnusedReceiverParameter") internal fun Dispatchers.toolWindowManager(project: Project): CoroutineDispatcher = object : CoroutineDispatcher() { override fun dispatch(context: CoroutineContext, block: java.lang.Runnable) = ToolWindowManager.getInstance(project).invokeLater(block) }
apache-2.0
18f048cd918fd6a3f7a7d53715d80c0a
36.471264
137
0.779687
4.682471
false
false
false
false
bjansen/pebble-intellij
src/main/kotlin/com/github/bjansen/intellij/pebble/editor/PebbleHighlighter.kt
1
5805
package com.github.bjansen.intellij.pebble.editor import com.github.bjansen.intellij.pebble.psi.PebbleParserDefinition.Companion.tokens import com.github.bjansen.intellij.pebble.psi.createLexer import com.github.bjansen.pebble.parser.PebbleLexer import com.intellij.lexer.Lexer import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.HighlighterColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighterBase import com.intellij.openapi.project.Project import com.intellij.psi.TokenType import com.intellij.psi.tree.IElementType import java.util.* class PebbleHighlighter(val project: Project? = null) : SyntaxHighlighterBase() { override fun getHighlightingLexer(): Lexer { return createLexer(null, project) } override fun getTokenHighlights(tokenType: IElementType): Array<TextAttributesKey> { val attributes: TextAttributesKey? if (delimiters.contains(tokenType)) { attributes = DELIMITER } else if (keywords.contains(tokenType)) { attributes = KEYWORDS } else if (braces.contains(tokenType)) { attributes = BRACES } else if (brackets.contains(tokenType)) { attributes = BRACKETS } else if (operators.contains(tokenType)) { attributes = OPERATORS } else if (parens.contains(tokenType)) { attributes = PARENTHESES } else if (strings.contains(tokenType)) { attributes = STRINGS } else if (tokenType == tokens[PebbleLexer.COMMENT]) { attributes = COMMENT } else if (tokenType == tokens[PebbleLexer.ID_NAME]) { attributes = IDENTIFIER } else if ( tokenType == tokens[PebbleLexer.NUMERIC] || tokenType == tokens[PebbleLexer.LONG] ) { attributes = NUMBER } else if (tokenType == TokenType.BAD_CHARACTER) { attributes = BAD_CHARACTER } else { attributes = null } return pack(BACKGROUND, attributes) } companion object Highlights { val BACKGROUND = createTextAttributesKey("PEBBLE_BACKGROUND", DefaultLanguageHighlighterColors.TEMPLATE_LANGUAGE_COLOR) val BAD_CHARACTER = createTextAttributesKey("PEBBLE_BAD_CHARACTER", HighlighterColors.BAD_CHARACTER) val BRACES = createTextAttributesKey("PEBBLE_BRACES", DefaultLanguageHighlighterColors.BRACES) val BRACKETS = createTextAttributesKey("PEBBLE_BRACKETS", DefaultLanguageHighlighterColors.BRACKETS) val COMMENT = createTextAttributesKey("PEBBLE_COMMENT", DefaultLanguageHighlighterColors.DOC_COMMENT) val DELIMITER = createTextAttributesKey("PEBBLE_DELIMITER", DefaultLanguageHighlighterColors.INSTANCE_FIELD) val IDENTIFIER = createTextAttributesKey("PEBBLE_IDENTIFIER", DefaultLanguageHighlighterColors.IDENTIFIER) val KEYWORDS = createTextAttributesKey("PEBBLE_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD) val NUMBER = createTextAttributesKey("PEBBLE_NUMBER", DefaultLanguageHighlighterColors.NUMBER) val OPERATORS = createTextAttributesKey("PEBBLE_OPERATOR", DefaultLanguageHighlighterColors.OPERATION_SIGN) val PARENTHESES = createTextAttributesKey("PEBBLE_PARENTHESIS", DefaultLanguageHighlighterColors.PARENTHESES) val STRINGS = createTextAttributesKey("PEBBLE_STRING", DefaultLanguageHighlighterColors.STRING) } // Built-in reserved words that can't be used as legal identifiers, and thus should // always be highlighted as keywords. private val keywords = Arrays.asList( // Unary operators listed in com.mitchellbosecke.pebble.extension.core.CoreExtension tokens[PebbleLexer.NOT], // Binary operators listed in com.mitchellbosecke.pebble.extension.core.CoreExtension tokens[PebbleLexer.OR], tokens[PebbleLexer.AND], tokens[PebbleLexer.IS], tokens[PebbleLexer.CONTAINS], tokens[PebbleLexer.EQUALS], // Reserved words listed in com.mitchellbosecke.pebble.parser.ExpressionParser // "none" can be a legal Java identifier so we do not list it here tokens[PebbleLexer.TRUE], tokens[PebbleLexer.FALSE], tokens[PebbleLexer.NULL] ) private val delimiters = Arrays.asList( tokens[PebbleLexer.TAG_OPEN], tokens[PebbleLexer.TAG_CLOSE], tokens[PebbleLexer.PRINT_OPEN], tokens[PebbleLexer.PRINT_CLOSE], tokens[PebbleLexer.INTERPOLATED_STRING_START], tokens[PebbleLexer.INTERPOLATED_STRING_STOP] ) private val braces = Arrays.asList( tokens[PebbleLexer.LBRACE], tokens[PebbleLexer.RBRACE] ) private val brackets = Arrays.asList( tokens[PebbleLexer.LBRACKET], tokens[PebbleLexer.RBRACKET] ) private val parens = Arrays.asList( tokens[PebbleLexer.LPAREN], tokens[PebbleLexer.RPAREN] ) private val operators = Arrays.asList( tokens[PebbleLexer.OP_PLUS], tokens[PebbleLexer.OP_MINUS], tokens[PebbleLexer.OP_MULT], tokens[PebbleLexer.OP_DIV], tokens[PebbleLexer.OP_MOD], tokens[PebbleLexer.OP_PIPE] ) private val strings = Arrays.asList( tokens[PebbleLexer.STRING_START], tokens[PebbleLexer.STRING_END], tokens[PebbleLexer.TEXT], tokens[PebbleLexer.SINGLE_QUOTED_STRING], tokens[PebbleLexer.DOUBLE_QUOTED_PLAIN_STRING] ) }
mit
6362914bf1ff43b7909fedce4ae72521
40.76259
103
0.687339
5.061029
false
false
false
false
Automattic/Automattic-Tracks-Android
AutomatticTracks/src/main/java/com/automattic/android/tracks/crashlogging/CrashLogging.kt
1
1348
package com.automattic.android.tracks.crashlogging interface CrashLogging { /** * Records a breadcrumb during the app lifecycle but doesn't report an event. This basically * adds more context for the next reports created and sent by [sendReport] or an unhandled * exception report. * * @param[message] The message to attach to a breadcrumb * @param[category] An optional category */ fun recordEvent( message: String, category: String? = null ) /** * Records a breadcrumb with exception during the app lifecycle but doesn't report an event. * This basically adds more context for the next reports created and sent by [sendReport] or an * unhandled exception report. * * @param[exception] The message to attach to a breadcrumb * @param[category] An optional category */ fun recordException( exception: Throwable, category: String? = null ) /** * Sends a new event to crash logging service * * @param[exception] An optional exception to report * @param[tags] Tags attached to event * @param[message] An optional message attached to event */ fun sendReport( exception: Throwable? = null, tags: Map<String, String> = emptyMap(), message: String? = null ) }
gpl-2.0
9b98f23f96f823257f204e44e446cea5
30.348837
99
0.64911
4.616438
false
false
false
false
jwren/intellij-community
plugins/git4idea/src/git4idea/log/GitShowExternalLogAction.kt
1
9541
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.log import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task.Backgroundable import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.WindowWrapper import com.intellij.openapi.ui.WindowWrapperBuilder import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsContexts.DialogTitle import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsRoot import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowManager.Companion.getInstance import com.intellij.ui.content.Content import com.intellij.ui.content.ContentFactory import com.intellij.ui.content.ContentManager import com.intellij.vcs.log.VcsLogBundle import com.intellij.vcs.log.VcsLogProvider import com.intellij.vcs.log.impl.VcsLogContentUtil import com.intellij.vcs.log.impl.VcsLogManager import com.intellij.vcs.log.impl.VcsLogTabLocation import com.intellij.vcs.log.impl.VcsProjectLog import com.intellij.vcs.log.ui.VcsLogPanel import com.intellij.vcs.log.visible.filters.VcsLogFilterObject.collection import com.intellij.vcs.log.visible.filters.VcsLogFilterObject.fromRoots import git4idea.GitUtil import git4idea.GitVcs import git4idea.config.GitExecutableManager import git4idea.i18n.GitBundle import git4idea.repo.GitRepositoryImpl import git4idea.repo.GitRepositoryManager import org.jetbrains.annotations.Nls import java.awt.BorderLayout import java.io.File import javax.swing.JComponent import javax.swing.JPanel class GitShowExternalLogAction : DumbAwareAction() { override fun update(e: AnActionEvent) { super.update(e) e.presentation.isEnabledAndVisible = e.project != null } override fun actionPerformed(e: AnActionEvent) { val project = e.getRequiredData(CommonDataKeys.PROJECT) val vcs = GitVcs.getInstance(project) val roots = getGitRootsFromUser(project) if (roots.isEmpty()) { return } val window = getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) if (project.isDefault || !ProjectLevelVcsManager.getInstance(project).hasActiveVcss() || window == null) { showExternalGitLogInDialog(project, vcs, roots, GitBundle.message("git.log.external.window.title")) } else { val description = GitBundle.message("git.log.external.tab.description", roots.joinToString("\n") { obj: VirtualFile -> obj.path }) showExternalGitLogInToolwindow(project, window, vcs, roots, calcTabName(window.contentManager, roots), description) } } } fun showExternalGitLogInDialog(project: Project, vcs: GitVcs, roots: List<VirtualFile>, dialogTitle: @DialogTitle String) { ProgressManager.getInstance().run(ShowLogInDialogTask(project, roots, vcs, dialogTitle)) } fun showExternalGitLogInToolwindow(project: Project, toolWindow: ToolWindow, vcs: GitVcs, roots: List<VirtualFile>, tabTitle: @NlsContexts.TabTitle String, tabDescription: @NlsContexts.Tooltip String) { val showContent = { val cm = toolWindow.contentManager if (!selectProjectLog(project, vcs, roots) && !selectAlreadyOpened(cm, roots)) { val isToolWindowTab = toolWindow.id == ChangesViewContentManager.TOOLWINDOW_ID val component = createManagerAndContent(project, vcs, roots, isToolWindowTab) val content = ContentFactory.SERVICE.getInstance().createContent(component, tabTitle, false) content.setDisposer(component.disposable) content.description = tabDescription content.isCloseable = true cm.addContent(content) cm.setSelectedContent(content) doOnProviderRemoval(project, component.disposable) { cm.removeContent(content, true) } } } if (!toolWindow.isVisible) { toolWindow.activate(showContent, true) } else { showContent() } } private class MyContentComponent(actualComponent: JComponent, val roots: Collection<VirtualFile>, val disposable: Disposable) : JPanel(BorderLayout()) { init { add(actualComponent) } } private class ShowLogInDialogTask(project: Project, val roots: List<VirtualFile>, val vcs: GitVcs, @DialogTitle val dialogTitle: String) : Backgroundable(project, @Suppress("DialogTitleCapitalization") GitBundle.message("git.log.external.loading.process"), true) { override fun run(indicator: ProgressIndicator) { if (!GitExecutableManager.getInstance().testGitExecutableVersionValid(project)) { throw ProcessCanceledException() } } override fun onSuccess() { if (!project.isDisposed) { val content = createManagerAndContent(project, vcs, roots, false) val window = WindowWrapperBuilder(WindowWrapper.Mode.FRAME, content) .setProject(project) .setTitle(dialogTitle) .setPreferredFocusedComponent(content) .setDimensionServiceKey(GitShowExternalLogAction::class.java.name) .build() Disposer.register(window, content.disposable) doOnProviderRemoval(project, content.disposable) { window.close() } window.show() } } } private const val EXTERNAL = "EXTERNAL" private fun createManagerAndContent(project: Project, vcs: GitVcs, roots: List<VirtualFile>, isToolWindowTab: Boolean): MyContentComponent { val disposable = Disposer.newDisposable() val repositoryManager = GitRepositoryManager.getInstance(project) for (root in roots) { repositoryManager.addExternalRepository(root, GitRepositoryImpl.createInstance(root, project, disposable)) } val manager = VcsLogManager(project, ApplicationManager.getApplication().getService(GitExternalLogTabsProperties::class.java), roots.map { VcsRoot(vcs, it) }) Disposer.register(disposable, Disposable { manager.dispose { roots.forEach { repositoryManager.removeExternalRepository(it) } } }) val ui = manager.createLogUi(calcLogId(roots), if (isToolWindowTab) VcsLogTabLocation.TOOL_WINDOW else VcsLogTabLocation.STANDALONE) Disposer.register(disposable, ui) return MyContentComponent(VcsLogPanel(manager, ui), roots, disposable) } private fun calcLogId(roots: List<VirtualFile>): String { return "$EXTERNAL " + roots.joinToString(File.pathSeparator) { obj: VirtualFile -> obj.path } } @Nls private fun calcTabName(cm: ContentManager, roots: List<VirtualFile>): String { val name = VcsLogBundle.message("vcs.log.tab.name") + " (" + roots.first().name + (if (roots.size > 1) "+" else "") + ")" var candidate = name var cnt = 1 while (cm.contents.any { content: Content -> content.displayName == candidate }) { candidate = "$name-$cnt" cnt++ } return candidate } private fun getGitRootsFromUser(project: Project): List<VirtualFile> { val descriptor = FileChooserDescriptor(false, true, false, true, false, true) val virtualFiles = FileChooser.chooseFiles(descriptor, project, null) return virtualFiles.filter { GitUtil.isGitRoot(File(it.path)) } } private fun selectProjectLog(project: Project, vcs: GitVcs, requestedRoots: List<VirtualFile>): Boolean { val projectRoots = listOf(*ProjectLevelVcsManager.getInstance(project).getRootsUnderVcs(vcs)) if (!projectRoots.containsAll(requestedRoots)) return false if (requestedRoots.containsAll(projectRoots)) return VcsLogContentUtil.selectMainLog(project) val filters = collection(fromRoots(requestedRoots)) return VcsProjectLog.getInstance(project).openLogTab(filters) != null } private fun selectAlreadyOpened(cm: ContentManager, roots: Collection<VirtualFile>): Boolean { val content = cm.contents.firstOrNull { content -> val component = content.component if (component is MyContentComponent) { Comparing.haveEqualElements(roots, component.roots) } else { false } } ?: return false cm.setSelectedContent(content) return true } private fun doOnProviderRemoval(project: Project, disposable: Disposable, closeTab: () -> Unit) { VcsLogProvider.LOG_PROVIDER_EP.getPoint(project).addExtensionPointListener(object : ExtensionPointListener<VcsLogProvider> { override fun extensionRemoved(extension: VcsLogProvider, pluginDescriptor: PluginDescriptor) { if (extension.supportedVcs == GitVcs.getKey()) { closeTab() } } }, false, disposable) }
apache-2.0
4eac1aa5b38966911574bf616cd24e99
42.770642
138
0.740593
4.598072
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/HighlightingProblem.kt
9
4582
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.analysis.problemsView.toolWindow import com.intellij.CommonBundle import com.intellij.analysis.problemsView.FileProblem import com.intellij.analysis.problemsView.ProblemsProvider import com.intellij.codeHighlighting.HighlightDisplayLevel import com.intellij.codeInsight.daemon.HighlightDisplayKey import com.intellij.codeInsight.daemon.impl.AsyncDescriptionSupplier import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.ex.RangeHighlighterEx import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.AnimatedIcon import com.intellij.xml.util.XmlStringUtil.escapeString import java.util.concurrent.atomic.AtomicBoolean import javax.swing.Icon internal class HighlightingProblem( override val provider: ProblemsProvider, override val file: VirtualFile, val highlighter: RangeHighlighterEx ) : FileProblem { private fun getIcon(level: HighlightDisplayLevel): Icon? = when { text.isEmpty() || asyncDescriptionRequested.get() -> AnimatedIcon.Default.INSTANCE severity >= level.severity.myVal -> level.icon else -> null } private var asyncDescriptionRequested = AtomicBoolean(false) private var loading = AtomicBoolean(false) val info: HighlightInfo? get() { val info = HighlightInfo.fromRangeHighlighter(highlighter) if (info is AsyncDescriptionSupplier) { requestAsyncDescription(info) } return info } private fun requestAsyncDescription(info: AsyncDescriptionSupplier) { if (!asyncDescriptionRequested.compareAndSet(false, true)) return loading.set(true) info.requestDescription().onSuccess { // we do that to avoid Concurrent modification exception ApplicationManager.getApplication().invokeLater { val panel = ProblemsViewToolWindowUtils.getTabById(provider.project, HighlightingPanel.ID) as? HighlightingPanel panel?.currentRoot?.problemUpdated(this) loading.set(false) } } } override val icon: Icon get() { val highlightInfo = info val severity = if (highlightInfo == null) HighlightSeverity.INFORMATION else highlightInfo.severity return HighlightDisplayLevel.find(severity)?.icon ?: getIcon(HighlightDisplayLevel.ERROR) ?: getIcon(HighlightDisplayLevel.WARNING) ?: HighlightDisplayLevel.WEAK_WARNING.icon } override val text: String get() { val text = info?.description ?: return CommonBundle.getLoadingTreeNodeText() val pos = text.indexOfFirst { StringUtil.isLineBreak(it) } return if (pos < 0 || text.startsWith("<html>", ignoreCase = true)) text else text.substring(0, pos) + StringUtil.ELLIPSIS } override val group: String? get() { val id = info?.inspectionToolId ?: return null return HighlightDisplayKey.getDisplayNameByKey(HighlightDisplayKey.findById(id)) } override val description: String? get() { val text = info?.description ?: return null if (text.isEmpty()) return null val pos = text.indexOfFirst { StringUtil.isLineBreak(it) } return if (pos < 0 || text.startsWith("<html>", ignoreCase = true)) null else "<html>" + StringUtil.join(StringUtil.splitByLines(escapeString(text)), "<br/>") } val severity: Int get() = info?.severity?.myVal ?: -1 override fun hashCode() = highlighter.hashCode() override fun equals(other: Any?) = other is HighlightingProblem && other.highlighter == highlighter override val line: Int get() = position?.line ?: -1 override val column: Int get() = position?.column ?: -1 private var position: CachedPosition? = null get() = info?.actualStartOffset?.let { if (it != field?.offset) field = computePosition(it) field } private fun computePosition(offset: Int): CachedPosition? { if (offset < 0) return null val document = ProblemsView.getDocument(provider.project, file) ?: return null if (offset > document.textLength) return null val line = document.getLineNumber(offset) return CachedPosition(offset, line, offset - document.getLineStartOffset(line)) } private class CachedPosition(val offset: Int, val line: Int, val column: Int) }
apache-2.0
618b7fd400ca6d9ec99e83650fcc2e6e
36.867769
140
0.733741
4.642351
false
false
false
false
ItsPriyesh/HexaTime
app/src/main/kotlin/com/priyesh/hexatime/ui/preferences/ClockPositionDialog.kt
1
2296
/* * Copyright 2015 Priyesh Patel * * 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.priyesh.hexatime.ui.preferences import android.app.AlertDialog import android.content.Context import android.preference.PreferenceManager import android.view.LayoutInflater import android.widget.SeekBar import com.priyesh.hexatime.KEY_CLOCK_POSITION_X import com.priyesh.hexatime.KEY_CLOCK_POSITION_Y import com.priyesh.hexatime.R import kotlin.properties.Delegates public class ClockPositionDialog(context: Context) : AlertDialog.Builder(context) { private val prefs = PreferenceManager.getDefaultSharedPreferences(context) private var sliderX: SeekBar by Delegates.notNull() private var sliderY: SeekBar by Delegates.notNull() init { val view = LayoutInflater.from(context).inflate(R.layout.clock_position_dialog, null) setView(view) sliderX = view.findViewById(R.id.horizontal_seekbar) as SeekBar sliderY = view.findViewById(R.id.vertical_seekbar) as SeekBar sliderX.progress = prefs.getInt(KEY_CLOCK_POSITION_X, 50) sliderY.progress = prefs.getInt(KEY_CLOCK_POSITION_Y, 50) view.findViewById(R.id.center_horizontal).setOnClickListener({ sliderX.center() }) view.findViewById(R.id.center_vertical).setOnClickListener({ sliderY.center() }) setTitle("Clock position") setNegativeButton("Cancel", { dialog, id -> dialog.dismiss() }) setPositiveButton("OK", { dialog, ide -> prefs.edit().putInt(KEY_CLOCK_POSITION_X, sliderX.progress).commit() prefs.edit().putInt(KEY_CLOCK_POSITION_Y, sliderY.progress).commit() }) } private fun SeekBar.center() { progress = max / 2 } public fun display(): Unit = create().show() }
apache-2.0
f680d4fa4f669da37c4654dde472efd6
36.048387
93
0.72169
4.056537
false
false
false
false
aosp-mirror/platform_frameworks_support
core/ktx/src/main/java/androidx/core/view/View.kt
1
7997
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE") // Aliases to other public API. package androidx.core.view import android.graphics.Bitmap import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver import android.view.accessibility.AccessibilityEvent import androidx.annotation.Px import androidx.annotation.RequiresApi import androidx.annotation.StringRes import androidx.core.graphics.applyCanvas /** * Performs the given action when this view is next laid out. * * @see doOnLayout */ inline fun View.doOnNextLayout(crossinline action: (view: View) -> Unit) { addOnLayoutChangeListener(object : View.OnLayoutChangeListener { override fun onLayoutChange( view: View, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int ) { view.removeOnLayoutChangeListener(this) action(view) } }) } /** * Performs the given action when this view is laid out. If the view has been laid out and it * has not requested a layout, the action will be performed straight away, otherwise the * action will be performed after the view is next laid out. * * @see doOnNextLayout */ inline fun View.doOnLayout(crossinline action: (view: View) -> Unit) { if (ViewCompat.isLaidOut(this) && !isLayoutRequested) { action(this) } else { doOnNextLayout { action(it) } } } /** * Performs the given action when the view tree is about to be drawn. */ inline fun View.doOnPreDraw(crossinline action: (view: View) -> Unit) { val vto = viewTreeObserver vto.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener { override fun onPreDraw(): Boolean { action(this@doOnPreDraw) when { vto.isAlive -> vto.removeOnPreDrawListener(this) else -> viewTreeObserver.removeOnPreDrawListener(this) } return true } }) } /** * Sends [AccessibilityEvent] of type [AccessibilityEvent.TYPE_ANNOUNCEMENT]. * * @see View.announceForAccessibility */ @RequiresApi(16) inline fun View.announceForAccessibility(@StringRes resource: Int) { val announcement = resources.getString(resource) announceForAccessibility(announcement) } /** * Updates this view's relative padding. This version of the method allows using named parameters * to just set one or more axes. * * @see View.setPaddingRelative */ @RequiresApi(17) inline fun View.updatePaddingRelative( @Px start: Int = paddingStart, @Px top: Int = paddingTop, @Px end: Int = paddingEnd, @Px bottom: Int = paddingBottom ) { setPaddingRelative(start, top, end, bottom) } /** * Updates this view's padding. This version of the method allows using named parameters * to just set one or more axes. * * @see View.setPadding */ inline fun View.updatePadding( @Px left: Int = paddingLeft, @Px top: Int = paddingTop, @Px right: Int = paddingRight, @Px bottom: Int = paddingBottom ) { setPadding(left, top, right, bottom) } /** * Sets the view's padding. This version of the method sets all axes to the provided size. * * @see View.setPadding */ inline fun View.setPadding(@Px size: Int) { setPadding(size, size, size, size) } /** * Version of [View.postDelayed] which re-orders the parameters, allowing the action to be placed * outside of parentheses. * * ``` * view.postDelayed(200) { * doSomething() * } * ``` * * @return the created Runnable */ inline fun View.postDelayed(delayInMillis: Long, crossinline action: () -> Unit): Runnable { val runnable = Runnable { action() } postDelayed(runnable, delayInMillis) return runnable } /** * Version of [View.postOnAnimationDelayed] which re-orders the parameters, allowing the action * to be placed outside of parentheses. * * ``` * view.postOnAnimationDelayed(16) { * doSomething() * } * ``` * * @return the created Runnable */ @RequiresApi(16) inline fun View.postOnAnimationDelayed( delayInMillis: Long, crossinline action: () -> Unit ): Runnable { val runnable = Runnable { action() } postOnAnimationDelayed(runnable, delayInMillis) return runnable } /** * Return a [Bitmap] representation of this [View]. * * The resulting bitmap will be the same width and height as this view's current layout * dimensions. This does not take into account any transformations such as scale or translation. * * Note, this will use the software rendering pipeline to draw the view to the bitmap. This may * result with different drawing to what is rendered on a hardware accelerated canvas (such as * the device screen). * * If this view has not been laid out this method will throw a [IllegalStateException]. * * @param config Bitmap config of the desired bitmap. Defaults to [Bitmap.Config.ARGB_8888]. */ fun View.toBitmap(config: Bitmap.Config = Bitmap.Config.ARGB_8888): Bitmap { if (!ViewCompat.isLaidOut(this)) { throw IllegalStateException("View needs to be laid out before calling toBitmap()") } return Bitmap.createBitmap(width, height, config).applyCanvas(::draw) } /** * Returns true when this view's visibility is [View.VISIBLE], false otherwise. * * ``` * if (view.isVisible) { * // Behavior... * } * ``` * * Setting this property to true sets the visibility to [View.VISIBLE], false to [View.GONE]. * * ``` * view.isVisible = true * ``` */ inline var View.isVisible: Boolean get() = visibility == View.VISIBLE set(value) { visibility = if (value) View.VISIBLE else View.GONE } /** * Returns true when this view's visibility is [View.INVISIBLE], false otherwise. * * ``` * if (view.isInvisible) { * // Behavior... * } * ``` * * Setting this property to true sets the visibility to [View.INVISIBLE], false to [View.VISIBLE]. * * ``` * view.isInvisible = true * ``` */ inline var View.isInvisible: Boolean get() = visibility == View.INVISIBLE set(value) { visibility = if (value) View.INVISIBLE else View.VISIBLE } /** * Returns true when this view's visibility is [View.GONE], false otherwise. * * ``` * if (view.isGone) { * // Behavior... * } * ``` * * Setting this property to true sets the visibility to [View.GONE], false to [View.VISIBLE]. * * ``` * view.isGone = true * ``` */ inline var View.isGone: Boolean get() = visibility == View.GONE set(value) { visibility = if (value) View.GONE else View.VISIBLE } /** * Executes [block] with the View's layoutParams and reassigns the layoutParams with the * updated version. * * @see View.getLayoutParams * @see View.setLayoutParams **/ inline fun View.updateLayoutParams(block: ViewGroup.LayoutParams.() -> Unit) { updateLayoutParams<ViewGroup.LayoutParams>(block) } /** * Executes [block] with a typed version of the View's layoutParams and reassigns the * layoutParams with the updated version. * * @see View.getLayoutParams * @see View.setLayoutParams **/ @JvmName("updateLayoutParamsTyped") inline fun <reified T : ViewGroup.LayoutParams> View.updateLayoutParams(block: T.() -> Unit) { val params = layoutParams as T block(params) layoutParams = params }
apache-2.0
4848262d2cab588ac8c80ff0f0e45250
26.864111
98
0.677879
4.098924
false
false
false
false
bixlabs/bkotlin
bkotlin/src/main/java/com/bixlabs/bkotlin/Alert.kt
1
2770
package com.bixlabs.bkotlin import android.app.ProgressDialog import android.content.Context import android.content.DialogInterface import androidx.appcompat.app.AlertDialog import android.text.TextUtils /** * Display an AlertDialog * * @param[title] optional, title * @param[message] to display * @param[positiveButton] optional, button text * @param[cancelable] able to cancel * @param[callback] callback of click ok button */ fun Context.displayAlertDialog(title: String? = "", message: String, positiveButton: String? = null, cancelable: Boolean = true, callback: DialogInterface.() -> Unit = {}) = AlertDialog.Builder(this).apply { if (!TextUtils.isEmpty(title)) setTitle(title) setMessage(message) setPositiveButton(positiveButton ?: getString(android.R.string.ok), { dialog, _ -> dialog.callback() }) setCancelable(cancelable) show() } /** * Display an AlertDialog with confirmation/cancellation options * * @param[title] optional, title * @param[message] to display * @param[positiveButton] optional, possitive button text. Defaults to true * @param[negativeButton] optional, negative button text. Defaults to false * @param[cancelable] optional, cancelable. Defaults to true * @param[callback] callback which includes the option selected by the user. True if the user pressed the possitive button, * false otherwise. */ fun Context.displayConfirmDialog(title: String? = "", message: String, positiveButton: String? = null, negativeButton: String? = null, cancelable: Boolean = true, callback: DialogInterface.(result: Boolean) -> Unit) = AlertDialog.Builder(this).apply { if (!TextUtils.isEmpty(title)) setTitle(title) setMessage(message) setPositiveButton(positiveButton ?: getString(android.R.string.ok), { dialog, _ -> dialog.callback(true) }) setNegativeButton(negativeButton ?: getString(android.R.string.no), { dialog, _ -> dialog.callback(false) }) setCancelable(cancelable) show() } /** * Display a ProgressDialog * * * @param[title] optional, title * @param[message] message * @return DialogInterface which allows the dismissal of the ProgressDialog */ @Deprecated("Use a progress indicator such as ProgressBar inline inside of an activity rather than using this modal dialog.") fun Context.displayProgressDialog(title: String? = null, message: String): DialogInterface { return ProgressDialog(this).apply { setProgressStyle(ProgressDialog.STYLE_SPINNER) setMessage(message) if (title != null) setTitle(title) show() } }
apache-2.0
42da6f241f5ee17a19f2b9d893572a37
39.15942
134
0.677978
4.593698
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/breadwallet/ui/showkey/ShowPaperKey.kt
1
2870
/** * BreadWallet * * Created by Pablo Budelli <[email protected]> on 10/10/19. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.ui.showkey import com.breadwallet.ui.navigation.NavigationEffect import com.breadwallet.ui.navigation.NavigationTarget import com.breadwallet.ui.navigation.OnCompleteAction import dev.zacsweers.redacted.annotations.Redacted object ShowPaperKey { data class M( @Redacted val phrase: List<String>, val onComplete: OnCompleteAction?, val currentWord: Int = 0, val phraseWroteDown: Boolean = false ) { companion object { fun createDefault( phrase: List<String>, onComplete: OnCompleteAction?, phraseWroteDown: Boolean ) = M(phrase, onComplete, phraseWroteDown = phraseWroteDown) } } sealed class E { object OnNextClicked : E() object OnPreviousClicked : E() object OnCloseClicked : E() data class OnPageChanged(val position: Int) : E() } sealed class F { object GoToHome : F(), NavigationEffect { override val navigationTarget = NavigationTarget.Home } object GoToBuy : F(), NavigationEffect { override val navigationTarget = NavigationTarget.Buy } object GoBack : F(), NavigationEffect { override val navigationTarget = NavigationTarget.Back } data class GoToPaperKeyProve( @Redacted val phrase: List<String>, val onComplete: OnCompleteAction ) : F(), NavigationEffect { override val navigationTarget = NavigationTarget.PaperKeyProve( phrase, onComplete ) } } }
mit
9253f9c48e8d5aea7523ffabe2652f93
35.794872
80
0.675958
4.897611
false
false
false
false
sandy-8925/Checklist
app/src/androidTest/java/org/sanpra/checklist/activity/MockItemsController.kt
1
2538
package org.sanpra.checklist.activity import androidx.collection.ArrayMap import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import org.sanpra.checklist.dbhelper.ChecklistItem import org.sanpra.checklist.dbhelper.ItemsControllerInterface import java.util.concurrent.atomic.AtomicLong class MockItemsController : ItemsControllerInterface { private val itemsMap : MutableMap<Long, ChecklistItem> = ArrayMap() private var nextId = AtomicLong(0) override fun flipStatus(itemId: Long) { val item = itemsMap[itemId] item ?: return item.isChecked = !item.isChecked } private val itemsLiveData = MutableLiveData(listItems().toList()) private fun updateLiveData() { itemsLiveData.postValue(listItems().toList()) } override fun deleteItem(itemId: Long) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun deleteCheckedItems() { val iterator = itemsMap.entries.iterator() while(iterator.hasNext()) { val entry = iterator.next() if(entry.value.isChecked) iterator.remove() } updateLiveData() } override fun checkAllItems() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun uncheckAllItems() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun reverseAllItemStatus() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun itemListLiveData(): LiveData<List<ChecklistItem>> = itemsLiveData override fun addItem(itemDesc: String) { val itemId = nextId.getAndIncrement() itemsMap[itemId] = ChecklistItem().apply { id = itemId description = itemDesc } } override fun fetchItem(itemId: Long): LiveData<ChecklistItem> { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun updateItem(item: ChecklistItem) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } fun listItems(): Collection<ChecklistItem> = itemsMap.values fun addItems(items : Collection<ChecklistItem>) { for(item in items) { itemsMap.put(item.id, item) } } }
gpl-3.0
a6df66d9d1dcc53658b7334eb434a6c0
31.974026
107
0.678881
4.806818
false
false
false
false
paoloach/zdomus
cs5463/app/src/main/java/it/achdjian/paolo/cs5463/domusEngine/DomusEngine.kt
1
4335
package it.achdjian.paolo.cs5463.domusEngine import android.os.Handler import android.os.HandlerThread import android.os.Message import android.util.Log import it.achdjian.paolo.cs5463.Constants import it.achdjian.paolo.cs5463.domusEngine.DomusEngine.handler import it.achdjian.paolo.cs5463.domusEngine.rest.* import it.achdjian.paolo.cs5463.zigbee.PowerNode import it.achdjian.paolo.cs5463.zigbee.ZDevices import it.achdjian.paolo.cs5463.zigbee.ZEndpoint import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit /** * Created by Paolo Achdjian on 7/9/17. */ object DomusEngine : HandlerThread("DomusEngtine"), Handler.Callback { val handler: Handler val whoAreYou = WhoAreYou() val getDevices = GetDevices() private val listeners: MutableList<NewSmartPlugDeviceListener> = ArrayList() private val attributeListener: MutableList<AttributesListener> = ArrayList() private val powerListener: MutableSet<PowerListener> = HashSet() private val mDecodeWorkQueue = LinkedBlockingQueue<Runnable>(); private val threadPool = ThreadPoolExecutor(3, Int.MAX_VALUE, 60, TimeUnit.SECONDS, mDecodeWorkQueue) val TAG = "ZIGBEE COM" init { start() handler = Handler(looper, this) } fun startEngine() { handler.post(whoAreYou) } fun getDevices() = handler.post(getDevices) fun getDevice(device: Int) = handler.post(GetDevice(device)) fun getAttribute(networkId: Int, endpointId: Int, clusterId: Int, attributeId: Int) = threadPool.execute(RequestAttributes(AttributeCoord(networkId, endpointId, clusterId, attributeId))) fun postCmd(networkId: Int, endpointId: Int, clusterId: Int, cmdId: Int) = threadPool.execute(ExecuteCommand(networkId, endpointId, clusterId, cmdId)) fun addListener(listener: NewSmartPlugDeviceListener) = listeners.add(listener) fun addListener(listener: PowerListener) = powerListener.add(listener) fun removeListener(listener: PowerListener) = powerListener.remove(listener) fun requestWhoAreYou() { } fun addAttributeListener(listener: AttributesListener) = attributeListener.add(listener) fun removeAttributeListener(listener: AttributesListener) = attributeListener.remove(listener) fun requestIdentify(shortAddress: Int, endpointId: Int) = threadPool.execute(RequestIdentify(shortAddress, endpointId)); fun requestPower(shortAddress: Int) = threadPool.execute(RequestPowerNode(shortAddress)) override fun handleMessage(message: Message?): Boolean { if (message != null) { when (message.what) { MessageType.WHO_ARE_YOU -> { handler.post(whoAreYou) Log.i(TAG, "Who are You") } MessageType.NEW_DEVICE -> { Log.i(TAG, "NEW Device") val device = message.obj as JsonDevice ZDevices.addDevice(device) device.endpoints. forEach { val endpoint = it.value.toInt(16) handler.post(GetEndpoint(device.short_address, endpoint)) } } MessageType.NEW_ENDPOINT -> { Log.i(TAG, "NEW endpoint_id") val endpoint = message.obj as ZEndpoint ZDevices.addEndpoint(endpoint) if (endpoint.device_id == Constants.ZCL_HA_DEVICEID_SMART_PLUG) { listeners.forEach({ it.newSmartPlugDevice(endpoint.short_address, endpoint.endpoint_id) }) } } MessageType.NEW_ATTRIBUTES -> { Log.i(TAG, "new attributes") val attributes = message.obj as Attributes attributeListener.forEach({ it.newAttributes(attributes) }) } MessageType.NEW_POWER -> { Log.i(TAG, "new power node response") val powerNode = message.obj as PowerNode powerListener.forEach({ it.newPower(powerNode) }) } } } return true } }
gpl-2.0
9467fdea0a53b4bc364afaeaa9bfadbe
37.362832
114
0.633679
4.646302
false
false
false
false
syrop/Wiktor-Navigator
navigator/src/main/kotlin/pl/org/seva/navigator/main/data/ActivityRecognitionObservable.kt
1
5319
/* * Copyright (C) 2017 Wiktor Nizio * * 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/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.navigator.main.data import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import androidx.lifecycle.Lifecycle import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.location.ActivityRecognition import com.google.android.gms.location.ActivityRecognitionResult import com.google.android.gms.location.DetectedActivity import io.reactivex.subjects.PublishSubject import pl.org.seva.navigator.main.extension.subscribe import pl.org.seva.navigator.main.init.instance val activityRecognition by instance<ActivityRecognitionObservable>() open class ActivityRecognitionObservable : GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private var initialized = false private var state = STATIONARY private var googleApiClient: GoogleApiClient? = null private lateinit var context: Context private var activityRecognitionReceiver : BroadcastReceiver? = null private val stateSubject = PublishSubject.create<Int>() private val mutableStateLiveData = MutableLiveData<Int>() val stateLiveData: LiveData<Int> = mutableStateLiveData infix fun initGoogleApiClient(context: Context) { if (initialized) { return } this.context = context googleApiClient?:let { googleApiClient = GoogleApiClient.Builder(context) .addApi(ActivityRecognition.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build() checkNotNull(googleApiClient).connect() } initialized = true } override fun onConnected(bundle: Bundle?) { registerReceiver() val intent = Intent(ACTIVITY_RECOGNITION_INTENT) val pendingIntent = PendingIntent.getBroadcast( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT, ) ActivityRecognition.getClient(context).requestActivityUpdates( ACTIVITY_RECOGNITION_INTERVAL_MS, pendingIntent, ) } override fun onConnectionSuspended(i: Int) = unregisterReceiver() private fun registerReceiver() { activityRecognitionReceiver = activityRecognitionReceiver?: ActivityRecognitionReceiver() context.registerReceiver(activityRecognitionReceiver, IntentFilter(ACTIVITY_RECOGNITION_INTENT)) } private fun unregisterReceiver() { activityRecognitionReceiver?: return context.unregisterReceiver(activityRecognitionReceiver) } override fun onConnectionFailed(connectionResult: ConnectionResult) = Unit fun listen(lifecycle: Lifecycle, f: (Int) -> Unit) { f(state) stateSubject.subscribe(lifecycle) { f(state) } } private fun onDeviceStationary() { state = STATIONARY stateSubject.onNext(STATIONARY) mutableStateLiveData.value = STATIONARY } private fun onDeviceMoving() { state = MOVING stateSubject.onNext(MOVING) mutableStateLiveData.value = MOVING } private inner class ActivityRecognitionReceiver: BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (ActivityRecognitionResult.hasResult(intent)) { val result = ActivityRecognitionResult.extractResult(intent) if (result probably DetectedActivity.STILL) { onDeviceStationary() } else { onDeviceMoving() } } } private infix fun ActivityRecognitionResult.probably(activity: Int) = mostProbableActivity.type == activity && getActivityConfidence(activity) >= MIN_CONFIDENCE } companion object { const val STATIONARY = 0 const val MOVING = 1 private const val ACTIVITY_RECOGNITION_INTENT = "activity_recognition_intent" private const val ACTIVITY_RECOGNITION_INTERVAL_MS = 1000L /** The device is only stationary if confidence >= this level. */ private const val MIN_CONFIDENCE = 80 // 70 does not work on LG G6 Android 7.0 } }
gpl-3.0
95480251904b85aaf6a9e5feeee15f15
34.46
106
0.6975
5.089952
false
false
false
false
square/sqldelight
sqldelight-gradle-plugin/src/test/multithreaded-sqlite/src/main/kotlin/com/example/db/DbHelper.kt
1
2015
package com.example.db import com.example.db.Database.Companion.Schema import com.example.db.Database.Companion.invoke import com.squareup.sqldelight.sqlite.driver.JdbcSqliteDriver import java.util.Properties /** * Database helper inits driver, creates schema, handles migrations and closes database. * * @property foreignKeys Corresponds to foreign_keys pragma and is true by default. * It turns on after schema creation for new databases, but turns before migration for existent databases. * * @property journalMode Corresponds to journal_mode pragma, should be set before first access to [database] property. */ class DbHelper( journalMode: String = "", foreignKeys: Boolean = false ) { val database: Database by lazy { if (journalMode.isNotEmpty()) { this.journalMode = journalMode } val currentVer = version if (currentVer == 0) { Schema.create(driver) version = Schema.version this.foreignKeys = foreignKeys } else { this.foreignKeys = foreignKeys val schemaVer = Schema.version if (schemaVer > currentVer) { Schema.migrate(driver, currentVer, schemaVer) version = schemaVer this.foreignKeys = foreignKeys } } invoke(driver) } fun close() { driver.close() } private val driver: JdbcSqliteDriver by lazy { JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY + "test.db", Properties()) } private var version: Int get() { val sqlCursor = driver.executeQuery(null, "PRAGMA user_version;", 0, null) return sqlCursor.getLong(0)!!.toInt() } set(value) { driver.execute(null, "PRAGMA user_version = $value;", 0, null) } var journalMode: String = journalMode private set(value) { driver.execute(null, "PRAGMA journal_mode = $value;", 0, null) field = value } var foreignKeys: Boolean = foreignKeys set(value) { driver.execute(null, "PRAGMA foreign_keys = ${if (value) 1 else 0};", 0, null) field = value } }
apache-2.0
6dd23866974f2a449c0be67b8b300817
28.202899
118
0.677916
4.095528
false
false
false
false
lisawray/groupie
example-viewbinding/src/main/java/com/xwray/groupie/example/viewbinding/MainActivity.kt
2
9792
package com.xwray.groupie.example.viewbinding import android.content.Intent import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.xwray.groupie.ExpandableGroup import com.xwray.groupie.Group import com.xwray.groupie.GroupieAdapter import com.xwray.groupie.OnItemClickListener import com.xwray.groupie.OnItemLongClickListener import com.xwray.groupie.Section import com.xwray.groupie.TouchCallback import com.xwray.groupie.example.core.InfiniteScrollListener import com.xwray.groupie.example.core.Prefs import com.xwray.groupie.example.core.SettingsActivity import com.xwray.groupie.example.core.decoration.CarouselItemDecoration import com.xwray.groupie.example.core.decoration.DebugItemDecoration import com.xwray.groupie.example.core.decoration.SwipeTouchCallback import com.xwray.groupie.example.viewbinding.databinding.ActivityMainBinding import com.xwray.groupie.example.viewbinding.item.CardItem import com.xwray.groupie.example.viewbinding.item.CarouselCardItem import com.xwray.groupie.example.viewbinding.item.ColumnItem import com.xwray.groupie.example.viewbinding.item.FullBleedCardItem import com.xwray.groupie.example.viewbinding.item.HeaderItem import com.xwray.groupie.example.viewbinding.item.HeartCardItem import com.xwray.groupie.example.viewbinding.item.SmallCardItem import com.xwray.groupie.example.viewbinding.item.SwipeToDeleteItem import com.xwray.groupie.example.viewbinding.item.UpdatableItem import kotlinx.coroutines.delay import kotlinx.coroutines.launch const val INSET_TYPE_KEY = "inset_type" const val INSET = "inset" class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var groupAdapter: GroupieAdapter private lateinit var prefs: Prefs private val gray: Int by lazy { ContextCompat.getColor(this, R.color.background) } private val betweenPadding: Int by lazy { resources.getDimensionPixelSize(R.dimen.padding_small) } private val rainbow200: IntArray by lazy { resources.getIntArray(R.array.rainbow_200) } private val rainbow500: IntArray by lazy { resources.getIntArray(R.array.rainbow_500) } private val infiniteLoadingSection: Section = Section(HeaderItem(R.string.infinite_loading)) private val swipeSection: Section = Section(HeaderItem(R.string.swipe_to_delete)) // Normally there's no need to hold onto a reference to this list, but for demonstration // purposes, we'll shuffle this list and post an update periodically private var updatableItems: ArrayList<UpdatableItem> = ArrayList() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) prefs = Prefs.get(this) groupAdapter = GroupieAdapter().apply { setOnItemClickListener(onItemClickListener) setOnItemLongClickListener(onItemLongClickListener) spanCount = 12 } populateAdapter() val layoutManager = GridLayoutManager(this, groupAdapter.spanCount).apply { spanSizeLookup = groupAdapter.spanSizeLookup } binding.recyclerView.also { it.layoutManager = layoutManager it.addItemDecoration(HeaderItemDecoration(gray, betweenPadding)) it.addItemDecoration(InsetItemDecoration(gray, betweenPadding)) it.addItemDecoration(DebugItemDecoration(it.context)) it.adapter = groupAdapter it.addOnScrollListener(object : InfiniteScrollListener(layoutManager) { override fun onLoadMore(currentPage: Int) { val color = rainbow200[currentPage % rainbow200.size] for (i in 0..4) { infiniteLoadingSection.add(CardItem(color)) } } }) ItemTouchHelper(touchCallback).attachToRecyclerView(it) } binding.fab.setOnClickListener { startActivity(Intent(this@MainActivity, SettingsActivity::class.java)) } prefs.registerListener(onSharedPrefChangeListener) } private fun populateAdapter() { // Full bleed item groupAdapter.add(Section(HeaderItem(R.string.full_bleed_item)).apply { add(FullBleedCardItem(ContextCompat.getColor(this@MainActivity, R.color.purple_200))) }) // Update in place group groupAdapter.add(Section().apply { val updatingGroup = Section() val updatingHeader = HeaderItem( R.string.updating_group, R.string.updating_group_subtitle, R.drawable.shuffle ) { updatingGroup.update(ArrayList(updatableItems).apply { shuffle() }) // You can also do this by forcing a change with payload binding.recyclerView.post { binding.recyclerView.invalidateItemDecorations() } } setHeader(updatingHeader) updatableItems = ArrayList() for (i in 1..12) { updatableItems.add(UpdatableItem(rainbow200[i], i)) } updatingGroup.update(updatableItems) add(updatingGroup) }) // Expandable group val expandableHeaderItem = ExpandableHeaderItem(R.string.expanding_group, R.string.expanding_group_subtitle) groupAdapter.add(ExpandableGroup(expandableHeaderItem).apply { for (i in 0..1) { add(CardItem(rainbow200[1])) } }) // Columns groupAdapter.add(Section(HeaderItem(R.string.vertical_columns)).apply { add(makeColumnGroup()) }) // Group showing even spacing with multiple columns groupAdapter.add(Section(HeaderItem(R.string.multiple_columns)).apply { for (i in 0..11) { add(SmallCardItem(rainbow200[5])) } }) // Swipe to delete (with add button in header) for (i in 0..2) { swipeSection.add(SwipeToDeleteItem(rainbow200[6])) } groupAdapter.add(swipeSection) // Horizontal carousel groupAdapter.add(Section(HeaderItem(R.string.carousel, R.string.carousel_subtitle)).apply { setHideWhenEmpty(true) add(makeCarouselGroup()) }) // Update with payload groupAdapter.add(Section(HeaderItem(R.string.update_with_payload, R.string.update_with_payload_subtitle)).also { for (i in rainbow500.indices) { it.add(HeartCardItem(rainbow200[i], i.toLong()) { item, favorite -> // Pretend to make a network request lifecycleScope.launch { delay(1000) item.setFavorite(favorite) item.notifyChanged(HeartCardItem.FAVORITE) } }) } }) // Infinite loading section groupAdapter.add(infiniteLoadingSection) } private fun makeColumnGroup(): ColumnGroup { val columnItems = ArrayList<ColumnItem>() for (i in 1..5) { // First five items are red -- they'll end up in a vertical column columnItems.add(ColumnItem(rainbow200[0], i)) } for (i in 6..10) { // Next five items are pink columnItems.add(ColumnItem(rainbow200[1], i)) } return ColumnGroup(columnItems) } private fun makeCarouselGroup(): Group { val carouselDecoration = CarouselItemDecoration(gray, betweenPadding) val carouselAdapter = GroupieAdapter() for (i in 0..9) { carouselAdapter.add(CarouselCardItem(rainbow200[i])) } return CarouselGroup(carouselDecoration, carouselAdapter) } private val onItemClickListener = OnItemClickListener { item, _ -> if (item is CardItem && item.text.isNotEmpty()) { Toast.makeText(this@MainActivity, item.text, Toast.LENGTH_SHORT).show() } } private val onItemLongClickListener = OnItemLongClickListener { item, _ -> if (item is CardItem && item.text.isNotEmpty()) { Toast.makeText(this@MainActivity, "Long clicked: " + item.text, Toast.LENGTH_SHORT).show() return@OnItemLongClickListener true } false } override fun onDestroy() { prefs.unregisterListener(onSharedPrefChangeListener) super.onDestroy() } private val touchCallback: TouchCallback by lazy { object : SwipeTouchCallback() { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val item = groupAdapter.getItem(viewHolder.bindingAdapterPosition) // Change notification to the adapter happens automatically when the section is // changed. swipeSection.remove(item) } } } private val onSharedPrefChangeListener = OnSharedPreferenceChangeListener { _, _ -> // This is pretty evil, try not to do this groupAdapter.notifyDataSetChanged() } }
mit
11e2a3a48695593b84c7d2ea37b47ca6
39.8
130
0.668709
4.957975
false
false
false
false
OpenConference/OpenConference-android
app/src/main/java/com/openconference/search/SearchActivity.kt
1
5777
package com.openconference.search import android.os.Bundle import android.support.annotation.StringRes import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.transition.Transition import android.transition.TransitionInflater import android.transition.TransitionManager import android.view.View import android.view.ViewGroup import android.widget.TextView import butterknife.bindView import com.hannesdorfmann.adapterdelegates2.AdapterDelegatesManager import com.hannesdorfmann.adapterdelegates2.ListDelegationAdapter import com.hannesdorfmann.mosby.mvp.viewstate.MvpViewStateActivity import com.jakewharton.rxbinding.widget.RxSearchView import com.openconference.Navigator import com.openconference.R import com.openconference.model.search.SearchableItem import com.openconference.util.applicationComponent import com.openconference.util.hideKeyboard import com.openconference.util.showKeyboard import com.primetime.search.SearchViewState import com.squareup.picasso.Picasso import rx.android.schedulers.AndroidSchedulers import java.util.concurrent.TimeUnit import javax.inject.Inject /** * * * @author Hannes Dorfmann */ class SearchActivity : SearchView, MvpViewStateActivity<SearchView, SearchPresenter>() { private lateinit var autoTransition: Transition private lateinit var adapter: ListDelegationAdapter<List<SearchableItem>> private val searchView: android.widget.SearchView by bindView(R.id.searchView) private val container: ViewGroup by bindView(R.id.container) private val errorView: TextView by bindView(R.id.errorView) private val loadingView: View by bindView(R.id.loadingView) private val contentView: RecyclerView by bindView(R.id.contentView) private val noResult: View by bindView(R.id.noResult) private val resultWrapper: View by bindView(R.id.resultsWrapper) private var lastQuery = "" private lateinit var component: SearchComponent @Inject lateinit var picasso: Picasso @Inject lateinit var navigator: Navigator override fun onCreate(savedInstanceState: Bundle?) { component = DaggerSearchComponent.builder() .applicationComponent(applicationComponent()) .searchViewModule(SearchViewModule(this)) .build() component.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_search) retainInstance = true autoTransition = TransitionInflater.from(this).inflateTransition(R.transition.auto) // init adapter val delegatesManager = AdapterDelegatesManager<List<SearchableItem>>() delegatesManager.addDelegate(SessionItemAdapterDelegate(layoutInflater, { searchView.hideKeyboard() navigator.showSessionDetails(it) })) .addDelegate(SpeakerAdapterDelegate(layoutInflater, picasso, { searchView.hideKeyboard() navigator.showSpeakerDetails(it) })) adapter = ListDelegationAdapter<List<SearchableItem>>(delegatesManager) contentView.adapter = adapter // contentView.addOnScrollListener(PicassoScrollListener(picasso)) contentView.layoutManager = LinearLayoutManager(this) RxSearchView.queryTextChangeEvents(searchView) .skip(2) .filter { it.queryText().toString() != lastQuery } .debounce(300, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe { if (it.isSubmitted) { searchView.hideKeyboard() } lastQuery = it.queryText().toString() presenter.search(lastQuery) } searchView.showKeyboard() resultWrapper.setOnClickListener { finish() } } override fun showResults(data: List<SearchableItem>) { castedViewState().setShowResults(data) if (!restoringViewState) { TransitionManager.beginDelayedTransition(container, autoTransition) } loadingView.visibility = View.GONE errorView.visibility = View.GONE adapter.items = data adapter.notifyDataSetChanged() if (data.isEmpty()) { contentView.visibility = View.GONE noResult.visibility = View.VISIBLE } else { contentView.visibility = View.VISIBLE noResult.visibility = View.GONE } } override fun createViewState() = SearchViewState() private inline fun castedViewState() = viewState as SearchViewState override fun createPresenter(): SearchPresenter = component.searchPresenter() override fun showLoading() { castedViewState().setShowLoading() if (!restoringViewState) { TransitionManager.beginDelayedTransition(container, autoTransition) } loadingView.visibility = View.VISIBLE errorView.visibility = View.GONE contentView.visibility = View.GONE noResult.visibility = View.GONE } override fun showSearchNotStarted() { castedViewState().setSearchNotStarted() if (!restoringViewState) { TransitionManager.beginDelayedTransition(container, autoTransition) } container.setOnClickListener { finish() } loadingView.visibility = View.GONE errorView.visibility = View.GONE contentView.visibility = View.GONE noResult.visibility = View.GONE } override fun showError(@StringRes errorMesgId: Int) { castedViewState().setShowError(errorMesgId) if (!restoringViewState) { TransitionManager.beginDelayedTransition(container, autoTransition) } loadingView.visibility = View.GONE errorView.visibility = View.VISIBLE errorView.setText(errorMesgId) contentView.visibility = View.GONE noResult.visibility = View.GONE } override fun onNewViewStateInstance() = showSearchNotStarted() override fun finish() { super.finish() overridePendingTransition(R.anim.fade_in, R.anim.fade_out) searchView.hideKeyboard() } }
apache-2.0
8137d85c26120bee1cce25b82ac100f3
32.593023
88
0.759391
4.920784
false
false
false
false
antoniolg/Kotlin-for-Android-Developers
app/src/main/java/com/antonioleiva/weatherapp/ui/activities/MainActivity.kt
1
1596
package com.antonioleiva.weatherapp.ui.activities import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.Toolbar import com.antonioleiva.weatherapp.R import com.antonioleiva.weatherapp.domain.commands.RequestForecastCommand import com.antonioleiva.weatherapp.extensions.DelegatesExt import com.antonioleiva.weatherapp.ui.adapters.ForecastListAdapter import kotlinx.android.synthetic.main.activity_main.* import kotlinx.coroutines.launch import org.jetbrains.anko.find import org.jetbrains.anko.startActivity class MainActivity : CoroutineScopeActivity(), ToolbarManager { private val zipCode: Long by DelegatesExt.preference(this, SettingsActivity.ZIP_CODE, SettingsActivity.DEFAULT_ZIP) override val toolbar by lazy { find<Toolbar>(R.id.toolbar) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initToolbar() forecastList.layoutManager = LinearLayoutManager(this) attachToScroll(forecastList) } override fun onResume() { super.onResume() loadForecast() } private fun loadForecast() = launch { val result = RequestForecastCommand(zipCode).execute() val adapter = ForecastListAdapter(result) { startActivity<DetailActivity>(DetailActivity.ID to it.id, DetailActivity.CITY_NAME to result.city) } forecastList.adapter = adapter toolbarTitle = "${result.city} (${result.country})" } }
apache-2.0
9543f0de590ef146b526d0f771ae7fde
35.272727
89
0.738095
4.721893
false
false
false
false
huzenan/EasyToggle
lib/src/main/java/com/hzn/lib/EasyToggle.kt
1
17961
package com.hzn.lib import android.animation.ValueAnimator import android.content.Context import android.graphics.* import android.os.Bundle import android.os.Parcelable import android.util.AttributeSet import android.util.TypedValue import android.view.MotionEvent import android.view.View /** * ToggleView, the default settings acts like ios toggle button style. * * Created by huzn on 2017/7/17. */ class EasyToggle : View { companion object { private const val KEY_CURRENT_STATE = "key_state" private const val KEY_SUPER_STATE = "key_super_state" } private var length = 0 private var radius = 0 private var range = 0 // default 4 times of radius private var bgOffColor = 0 private var bgOnColor = 0 private var bgStrokeWidth = 0 private var bgTopColor = 0 private var buttonColor = 0 private var buttonStrokeColor = 0 private var buttonStrokeWidth = 0 private var shadowOffsetY = 0 private var cx = 0f private var cy = 0f private var bgRectM = RectF() private var bgRectL = RectF() private var bgRectR = RectF() private var bgTopRectM = RectF() private var bgTopRectL = RectF() private var bgTopRectR = RectF() private var buttonRectL = RectF() private var buttonRectR = RectF() private var buttonExtensionLength = 0f private var bgPaint = Paint() private var bgPath = Path() private var bgTopPaint = Paint() private var bgTopPath = Path() private var buttonPaint = Paint() private var buttonStrokePaint = Paint() private var buttonPath = Path() private var shadowPaint = Paint() private var bgColorAnimator: ValueAnimator? = null private var bgColorFraction = 1f private var bgTopExtensionAnimator: ValueAnimator? = null private var bgTopExtensionValue = 1f private var buttonExtensionAnimator: ValueAnimator? = null private var buttonExtensionValue = 0f private var buttonMoveAnimator: ValueAnimator? = null private var buttonMoveValue = 0f private val ANIMATION_DURATION = 300L val STATE_OFF = 0 val STATE_ON = 1 private var currentState = STATE_OFF private var lastState = STATE_OFF private var hasToggled = false private var isTouchOutOfRange = false private var hasBeenTouchOutOfRange = false private var downX = 0f private var downY = 0f private var onToggledListener: ((Boolean) -> Unit)? = null constructor(context: Context?) : this(context, null) constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { context?.theme?.obtainStyledAttributes(attrs, R.styleable.EasyToggle, defStyleAttr, 0).let { length = it?.getDimensionPixelSize(R.styleable.EasyToggle_etLength, TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 22.5f, context?.resources?.displayMetrics).toInt())!! radius = it.getDimensionPixelSize(R.styleable.EasyToggle_etRadius, TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 15f, context?.resources?.displayMetrics).toInt()) range = it.getDimensionPixelSize(R.styleable.EasyToggle_etRange, TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 60f, context?.resources?.displayMetrics).toInt()) bgOffColor = it.getColor(R.styleable.EasyToggle_etBgOffColor, Color.parseColor("#FFE4E4E4")) bgOnColor = it.getColor(R.styleable.EasyToggle_etBgOnColor, Color.parseColor("#FF4DD863")) bgStrokeWidth = it.getDimensionPixelSize(R.styleable.EasyToggle_etBgStrokeWidth, TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 2f, context?.resources?.displayMetrics).toInt()) bgTopColor = it.getColor(R.styleable.EasyToggle_etBgTopColor, Color.WHITE) buttonColor = it.getColor(R.styleable.EasyToggle_etButtonColor, Color.WHITE) buttonStrokeColor = it.getColor(R.styleable.EasyToggle_etButtonStrokeColor, Color.parseColor("#FFE4E4E4")) buttonStrokeWidth = it.getDimensionPixelSize(R.styleable.EasyToggle_etButtonStrokeWidth, TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 0.1f, context?.resources?.displayMetrics).toInt()) shadowOffsetY = it.getDimensionPixelSize(R.styleable.EasyToggle_etShadowOffsetY, TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, -1f, context?.resources?.displayMetrics).toInt()) it.recycle() } buttonStrokeWidth = if (buttonStrokeWidth / 2f > radius - bgStrokeWidth / 2f) (radius - bgStrokeWidth / 2) * 2 else buttonStrokeWidth if (shadowOffsetY < 0) shadowOffsetY = bgStrokeWidth * 2 // default shadow offset y with(bgPaint) { isAntiAlias = true style = Paint.Style.FILL_AND_STROKE color = bgOffColor strokeWidth = bgStrokeWidth.toFloat() } with(bgTopPaint) { isAntiAlias = true style = Paint.Style.FILL color = bgTopColor } with(buttonPaint) { isAntiAlias = true style = Paint.Style.FILL color = buttonColor } with(shadowPaint) { isAntiAlias = true style = Paint.Style.FILL_AND_STROKE // this looks like wrong in xml preview, actually it is correct color = Color.parseColor("#11333333") strokeWidth = buttonStrokeWidth.toFloat() } with(buttonStrokePaint) { isAntiAlias = true style = Paint.Style.STROKE color = buttonStrokeColor strokeWidth = buttonStrokeWidth.toFloat() } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var widthSize: Int = MeasureSpec.getSize(widthMeasureSpec) var mode: Int? = MeasureSpec.getMode(widthMeasureSpec) if (mode != MeasureSpec.EXACTLY) { widthSize = paddingLeft + paddingRight + radius * 2 + length if (bgStrokeWidth > buttonStrokeWidth / 2f) widthSize += bgStrokeWidth else widthSize += buttonStrokeWidth - bgStrokeWidth } var heightSize: Int = MeasureSpec.getSize(heightMeasureSpec) mode = MeasureSpec.getMode(heightMeasureSpec) if (mode != MeasureSpec.EXACTLY) { heightSize = paddingTop + paddingBottom + radius * 2 if (bgStrokeWidth > buttonStrokeWidth / 2f + Math.abs(shadowOffsetY)) heightSize += bgStrokeWidth else heightSize += buttonStrokeWidth - bgStrokeWidth + Math.abs(shadowOffsetY) * 2 } val halfStrokeWidth = bgStrokeWidth / 2f cx = widthSize / 2f cy = heightSize / 2f // bg rect with(bgRectM) { left = cx - length / 2f top = cy - radius right = cx + length / 2f bottom = cy + radius } with(bgRectL) { left = bgRectM.left - radius top = bgRectM.top right = bgRectM.left + radius bottom = bgRectM.bottom } with(bgRectR) { left = bgRectM.right - radius top = bgRectM.top right = bgRectM.right + radius bottom = bgRectM.bottom } // bg top rect with(bgTopRectM) { left = bgRectM.left + halfStrokeWidth top = bgRectM.top + halfStrokeWidth right = bgRectM.right - halfStrokeWidth bottom = bgRectM.bottom - halfStrokeWidth } with(bgTopRectL) { left = bgTopRectM.left - radius top = bgTopRectM.top right = bgTopRectM.left + radius bottom = bgTopRectM.bottom } with(bgTopRectR) { left = bgTopRectM.right - radius top = bgTopRectM.top right = bgTopRectM.right + radius bottom = bgTopRectM.bottom } // button rect with(buttonRectL) { top = bgRectM.top + halfStrokeWidth bottom = bgRectM.bottom - halfStrokeWidth } with(buttonRectR) { top = bgRectM.top + halfStrokeWidth bottom = bgRectM.bottom - halfStrokeWidth } buttonExtensionLength = radius / 2f setMeasuredDimension(widthSize, heightSize) } override fun onDraw(canvas: Canvas?) { val halfStrokeWidth = bgStrokeWidth / 2f val halfExtensionLength = buttonExtensionLength * buttonExtensionValue / 2f // bg with(bgPath) { reset() moveTo(bgRectM.left, bgRectM.top) lineTo(bgRectM.right, bgRectM.top) arcTo(bgRectR, -90f, 180f, false) lineTo(bgRectM.left, bgRectM.bottom) arcTo(bgRectL, 90f, 180f, false) } val startColor: Int val endColor: Int if (currentState == STATE_ON) { startColor = bgOffColor endColor = bgOnColor } else { startColor = bgOnColor endColor = bgOffColor } val currentColor = getCurrentColor(bgColorFraction, startColor, endColor) bgPaint.color = currentColor canvas?.drawPath(bgPath, bgPaint) // bg top with(bgTopPath) { reset() moveTo(bgTopRectM.left, bgTopRectM.top) lineTo(bgTopRectM.right, bgTopRectM.top) arcTo(bgTopRectR, -90f, 180f, false) lineTo(bgTopRectM.left, bgTopRectM.bottom) arcTo(bgTopRectL, 90f, 180f, false) } canvas?.let { it.save() it.scale(bgTopExtensionValue, bgTopExtensionValue, cx, cy) it.drawPath(bgTopPath, bgTopPaint) it.restore() } // button // extension var buttonCenterX: Float if (currentState == STATE_ON) buttonCenterX = bgRectM.right - halfExtensionLength else buttonCenterX = bgRectM.left + halfExtensionLength // move buttonCenterX += (length - halfExtensionLength * 2) * buttonMoveValue with(buttonRectL) { left = buttonCenterX - halfExtensionLength - radius + halfStrokeWidth right = buttonCenterX - halfExtensionLength + radius - halfStrokeWidth } with(buttonRectR) { left = buttonCenterX + halfExtensionLength - radius + halfStrokeWidth right = buttonCenterX + halfExtensionLength + radius - halfStrokeWidth } with(buttonPath) { reset() moveTo(buttonCenterX - halfExtensionLength, bgRectM.top + halfStrokeWidth) lineTo(buttonCenterX + halfExtensionLength, bgRectM.top + halfStrokeWidth) arcTo(buttonRectR, -90f, 180f, false) lineTo(buttonCenterX - halfExtensionLength, bgRectM.bottom - halfStrokeWidth) arcTo(buttonRectL, 90f, 180f, false) } canvas?.let { it.save() it.translate(0f, shadowOffsetY.toFloat()) // move the canvas to draw shadow it.drawPath(buttonPath, shadowPaint) it.restore() it.drawPath(buttonPath, buttonPaint) it.drawPath(buttonPath, buttonStrokePaint) } } override fun onTouchEvent(event: MotionEvent?): Boolean { parent.requestDisallowInterceptTouchEvent(true) when (event?.action) { MotionEvent.ACTION_DOWN -> doActionDown(event) MotionEvent.ACTION_MOVE -> doActionMove(event) MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> doActionUp(event) } return true } private fun doActionDown(event: MotionEvent?) { downX = event?.rawX!! downY = event.rawY doButtonExtensionAnimation(0f, 1f) if (currentState == STATE_OFF) doBgTopExtensionAnimation(1f, 0f) } private fun doActionMove(event: MotionEvent?) { val nowX = event?.rawX!! val nowY = event.rawY val offsetX = nowX - downX val offsetY = nowY - downY isTouchOutOfRange = Math.abs(offsetY) > range if (currentState == STATE_ON && offsetX < -length) { downX = nowX toggle() if (isTouchOutOfRange) { doBgTopExtensionAnimation(0f, 1f) } else if (hasBeenTouchOutOfRange) { hasBeenTouchOutOfRange = false doButtonExtensionAnimation(0f, 1f) } } else if (currentState == STATE_OFF && offsetX > length) { downX = nowX toggle() if (isTouchOutOfRange) { doBgTopExtensionAnimation(1f, 0f) } else if (hasBeenTouchOutOfRange) { hasBeenTouchOutOfRange = false doButtonExtensionAnimation(0f, 1f) doBgTopExtensionAnimation(1f, 0f) } } if (!hasBeenTouchOutOfRange && Math.abs(offsetY) > range) { hasBeenTouchOutOfRange = true doButtonExtensionAnimation(1f, 0f) if (!hasToggled) toggle() if (currentState == STATE_OFF) doBgTopExtensionAnimation(0f, 1f) } } private fun doActionUp(event: MotionEvent?) { if (!hasBeenTouchOutOfRange) doButtonExtensionAnimation(1f, 0f) if (!hasToggled && lastState == currentState) toggle() if (!hasBeenTouchOutOfRange && currentState == STATE_OFF) doBgTopExtensionAnimation(0f, 1f) reset() } private fun reset() { lastState = currentState hasToggled = false buttonMoveValue = 0f hasBeenTouchOutOfRange = false } private fun toggle() { hasToggled = true val startMove: Float val endMove: Float if (currentState == STATE_ON) { currentState = STATE_OFF startMove = 1f endMove = 0f } else { currentState = STATE_ON startMove = -1f endMove = 0f } buttonMoveAnimator?.end() buttonMoveAnimator = ValueAnimator.ofFloat(startMove, endMove).apply { duration = ANIMATION_DURATION addUpdateListener { buttonMoveValue = it.animatedValue as Float invalidate() } start() } bgColorAnimator?.end() bgColorAnimator = ValueAnimator.ofFloat(0f, 1f).apply { duration = ANIMATION_DURATION addUpdateListener { bgColorFraction = it.animatedFraction invalidate() } start() } onToggledListener?.invoke(currentState == STATE_ON) } private fun toggleImmediately() { bgColorFraction = 1f bgTopExtensionValue = if (currentState == STATE_OFF) 1f else 0f buttonExtensionValue = 0f buttonMoveValue = 0f } private fun doButtonExtensionAnimation(start: Float, end: Float) { buttonExtensionAnimator?.end() buttonExtensionAnimator = ValueAnimator.ofFloat(start, end).apply { duration = ANIMATION_DURATION addUpdateListener { buttonExtensionValue = it.animatedValue as Float invalidate() } start() } } private fun doBgTopExtensionAnimation(start: Float, end: Float) { bgTopExtensionAnimator?.end() bgTopExtensionAnimator = ValueAnimator.ofFloat(start, end).apply { duration = ANIMATION_DURATION addUpdateListener { bgTopExtensionValue = it.animatedValue as Float invalidate() } start() } } private fun getCurrentColor(fraction: Float, startColor: Int, endColor: Int): Int { val redCurrent: Int val blueCurrent: Int val greenCurrent: Int val alphaCurrent: Int val redStart = Color.red(startColor) val blueStart = Color.blue(startColor) val greenStart = Color.green(startColor) val alphaStart = Color.alpha(startColor) val redEnd = Color.red(endColor) val blueEnd = Color.blue(endColor) val greenEnd = Color.green(endColor) val alphaEnd = Color.alpha(endColor) val redDifference = redEnd - redStart val blueDifference = blueEnd - blueStart val greenDifference = greenEnd - greenStart val alphaDifference = alphaEnd - alphaStart redCurrent = (redStart + fraction * redDifference).toInt() blueCurrent = (blueStart + fraction * blueDifference).toInt() greenCurrent = (greenStart + fraction * greenDifference).toInt() alphaCurrent = (alphaStart + fraction * alphaDifference).toInt() return Color.argb(alphaCurrent, redCurrent, greenCurrent, blueCurrent) } /** * Set the listener of toggle, true: on, false: off */ fun setOnToggledListener(l: (Boolean) -> Unit) { this.onToggledListener = l } override fun onSaveInstanceState(): Parcelable { return Bundle().apply { putInt(KEY_CURRENT_STATE, currentState) putParcelable(KEY_SUPER_STATE, super.onSaveInstanceState()) } } override fun onRestoreInstanceState(state: Parcelable?) { if (state is Bundle) { super.onRestoreInstanceState(state.getParcelable(KEY_SUPER_STATE)) currentState = state.getInt(KEY_CURRENT_STATE) lastState = currentState toggleImmediately() } } }
apache-2.0
0659ee48083e850da1f4c05cfc6ed0c2
33.945525
127
0.606536
4.593606
false
false
false
false
nistix/android-samples
binding/src/main/java/com/nistix/androidsamples/binding/employee/MyHandler.kt
1
662
package com.nistix.androidsamples.binding.employee import android.content.Context import android.view.View import timber.log.Timber class MyHandler { fun onDelete(view: View) { Timber.i("onDelete(View)...") } fun onDeleteEmployee(employee: Employee) { Timber.i("onDeleteEmployee(Employee = $employee)...") } fun onEnable(employee: Employee, enable: Boolean) { Timber.i("onEnable(Employee = $employee, enable = $enable)...") } fun onActive(employee: Employee, context: Context) { Timber.i("onActive(Employee = $employee)...") } fun onDeactive(employee: Employee) { Timber.i("onDeactive(Employee = $employee)...") } }
mit
e0fab8240dfb12842eec1948d8d19a6b
22.678571
67
0.690332
3.521277
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl-provider-plugins/src/main/kotlin/org/gradle/kotlin/dsl/provider/plugins/precompiled/tasks/GenerateScriptPluginAdapters.kt
2
3417
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.provider.plugins.precompiled.tasks import org.gradle.api.DefaultTask import org.gradle.api.file.DirectoryProperty import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.IgnoreEmptyDirectories import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Internal import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import org.gradle.kotlin.dsl.provider.plugins.precompiled.PrecompiledScriptPlugin import org.gradle.kotlin.dsl.provider.plugins.precompiled.scriptPluginFilesOf import java.io.File @CacheableTask abstract class GenerateScriptPluginAdapters : DefaultTask() { @get:OutputDirectory abstract val outputDirectory: DirectoryProperty @get:Internal internal lateinit var plugins: List<PrecompiledScriptPlugin> @get:InputFiles @get:IgnoreEmptyDirectories @get:PathSensitive(PathSensitivity.RELATIVE) @Suppress("unused") internal val scriptFiles: Set<File> get() = scriptPluginFilesOf(plugins) @TaskAction @Suppress("unused") internal fun generate() = outputDirectory.withOutputDirectory { outputDir -> for (scriptPlugin in plugins) { scriptPlugin.writeScriptPluginAdapterTo(outputDir) } } } internal fun PrecompiledScriptPlugin.writeScriptPluginAdapterTo(outputDir: File) { val (packageDir, packageDeclaration) = packageName?.let { packageName -> packageDir(outputDir, packageName) to "package $packageName" } ?: outputDir to "" val outputFile = packageDir.resolve("$simplePluginAdapterClassName.kt") outputFile.writeText( """ $packageDeclaration /** * Precompiled [$scriptFileName][$compiledScriptTypeName] script plugin. * * @see $compiledScriptTypeName */ public class $simplePluginAdapterClassName : org.gradle.api.Plugin<$targetType> { override fun apply(target: $targetType) { try { Class .forName("$compiledScriptTypeName") .getDeclaredConstructor($targetType::class.java, $targetType::class.java) .newInstance(target, target) } catch (e: java.lang.reflect.InvocationTargetException) { throw e.targetException } } } """.trimIndent().trim() + "\n" ) } private fun packageDir(outputDir: File, packageName: String) = outputDir.mkdir(packageName.replace('.', '/')) private fun File.mkdir(relative: String) = resolve(relative).apply { mkdirs() }
apache-2.0
8694f88e10e24870605deadcb02b4a62
29.508929
97
0.683641
4.674419
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/command/profile/ProfileCommand.kt
1
2323
/* * Copyright 2022 Ren 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.players.bukkit.command.profile import com.rpkit.core.command.RPKCommandExecutor import com.rpkit.core.command.result.CommandResult import com.rpkit.core.command.result.IncorrectUsageFailure import com.rpkit.core.command.sender.RPKCommandSender import com.rpkit.players.bukkit.RPKPlayersBukkit import java.util.concurrent.CompletableFuture class ProfileCommand(private val plugin: RPKPlayersBukkit) : RPKCommandExecutor { private val profileViewCommand = ProfileViewCommand(plugin) private val profileSetCommand = ProfileSetCommand(plugin) private val profileLinkCommand = ProfileLinkCommand(plugin) private val profileConfirmLinkCommand = ProfileConfirmLinkCommand(plugin) private val profileDenyLinkCommand = ProfileDenyLinkCommand(plugin) override fun onCommand(sender: RPKCommandSender, args: Array<out String>): CompletableFuture<out CommandResult> { if (args.isEmpty()) { sender.sendMessage(plugin.messages.profileUsage) return CompletableFuture.completedFuture(IncorrectUsageFailure()) } val newArgs = args.drop(1).toTypedArray() return when (args[0].lowercase()) { "view" -> profileViewCommand.onCommand(sender, newArgs) "set" -> profileSetCommand.onCommand(sender, newArgs) "link" -> profileLinkCommand.onCommand(sender, newArgs) "confirmlink" -> profileConfirmLinkCommand.onCommand(sender, newArgs) "denylink" -> profileDenyLinkCommand.onCommand(sender, newArgs) else -> { sender.sendMessage(plugin.messages.profileUsage) CompletableFuture.completedFuture(IncorrectUsageFailure()) } } } }
apache-2.0
d3f89636b373c6a009e5eb5168a5c7df
42.849057
117
0.732673
4.731161
false
false
false
false
LorittaBot/Loritta
web/spicy-morenitta/src/main/kotlin/net/perfectdreams/spicymorenitta/routes/ReputationRoute.kt
1
6682
package net.perfectdreams.spicymorenitta.routes import io.ktor.client.request.* import io.ktor.client.statement.* import jq import kotlinx.browser.document import kotlinx.browser.window import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.dom.addClass import kotlinx.dom.clear import kotlinx.dom.removeClass import kotlinx.html.* import kotlinx.html.dom.append import kotlinx.serialization.Serializable import net.perfectdreams.spicymorenitta.SpicyMorenitta import net.perfectdreams.spicymorenitta.application.ApplicationCall import net.perfectdreams.spicymorenitta.http import net.perfectdreams.spicymorenitta.utils.* import net.perfectdreams.spicymorenitta.views.dashboard.ServerConfig import org.w3c.dom.Audio import org.w3c.dom.HTMLButtonElement import org.w3c.dom.HTMLDivElement import org.w3c.dom.HTMLTextAreaElement import org.w3c.dom.url.URLSearchParams import utils.GoogleRecaptcha import utils.RecaptchaOptions import kotlin.js.json class ReputationRoute : BaseRoute("/user/{userId}/rep") { var userId: String? = null companion object { @JsName("recaptchaCallback") fun recaptchaCallback(response: String) { val currentRoute = SpicyMorenitta.INSTANCE.currentRoute if (currentRoute is ReputationRoute) currentRoute.recaptchaCallback(response) } } fun recaptchaCallback(token: String) { println("reCAPTCHA token is: $token") val urlParams = URLSearchParams(window.location.search) val guildId = urlParams.get("guild") val channelId = urlParams.get("channel") println("Guild is $guildId") println("Channel is $channelId") val json = json( "content" to (page.getElementById("reputation-reason") as HTMLTextAreaElement).value, "token" to token, "guildId" to guildId, "channelId" to channelId ) println(json.toString()) println(JSON.stringify(json)) GlobalScope.launch { val response = http.post("${loriUrl}api/v1/users/$userId/reputation") { setBody(JSON.stringify(json)) } val text = response.bodyAsText() println("Received: $text") if (response.status.value == 200) { println("Deu certo!") val ts1SkillUp = Audio("${loriUrl}assets/snd/ts1_skill.mp3") ts1SkillUp.play() updateReputationLeaderboard() page.getElementByClass("reputation-button").addClass("button-discord-disabled") page.getElementByClass("reputation-button").removeClass("button-discord-info") } else { println("Deu ruim!!!") } } } override fun onRender(call: ApplicationCall) { super.onRender(call) userId = call.parameters["userId"]!! val reputationButton = document.select<HTMLButtonElement>("#reputation-button") if (!reputationButton.hasAttribute("data-can-give-at") && !reputationButton.hasAttribute("data-need-login")) { reputationButton.addClass("button-discord-info") reputationButton.removeClass("button-discord-disabled") GoogleRecaptchaUtils.render(jq("#reputation-captcha").get()[0], RecaptchaOptions( "6Ld273kUAAAAAIIKfAhF4eIhBmOC80M6rx4sY2NE", "recaptchaCallback", "invisible" )) reputationButton.onClick { GoogleRecaptcha.execute() } } updateReputationLeaderboard() } fun updateReputationLeaderboard() { SpicyMorenitta.INSTANCE.launch { val leaderboardResultAsString = http.get("${loriUrl}api/v1/users/$userId/reputation") .bodyAsText() val leaderboardResult = kotlinx.serialization.json.Json.decodeFromString(ReputationLeaderboardResponse.serializer(), leaderboardResultAsString) page.getElementByClass("reputation-count").textContent = leaderboardResult.count.toString() val element = document.select<HTMLDivElement>(".leaderboard") element.clear() element.append { div(classes = "box-item") { var idx = 0 div(classes = "rank-title") { +"Placar de Reputações" } table { tbody { tr { th { + "Posição" } th {} th { + "Nome" } } for ((count, rankUser) in leaderboardResult.rank) { if (idx == 5) break tr { td { img(classes = "rank-avatar", src = rankUser.effectiveAvatarUrl) { width = "64" } } td(classes = "rank-position") { +"#${idx + 1}" } td { if (idx == 0) { div(classes = "rank-name rainbow") { +rankUser.name } } else { div(classes = "rank-name") { +rankUser.name } } div(classes = "reputations-received") { +"$count reputações" } } } idx++ } } } } } } } @Serializable data class ReputationLeaderboardResponse( val count: Int, val rank: List<ReputationLeaderboardEntry> ) @Serializable data class ReputationLeaderboardEntry( val count: Int, val user: ServerConfig.SelfMember ) }
agpl-3.0
417c8a2697c8c0b1a95efd11961c29c7
35.288043
155
0.503745
5.362249
false
false
false
false
owntracks/android
project/app/src/main/java/org/owntracks/android/support/preferences/SharedPreferencesStore.kt
1
6398
package org.owntracks.android.support.preferences import android.content.Context import android.content.SharedPreferences import androidx.preference.PreferenceManager import dagger.hilt.android.qualifiers.ApplicationContext import org.owntracks.android.R import org.owntracks.android.services.MessageProcessorEndpointHttp import org.owntracks.android.services.MessageProcessorEndpointMqtt import org.owntracks.android.support.Preferences import java.util.* import javax.inject.Inject import javax.inject.Singleton /*** * Implements a PreferencesStore that uses a SharedPreferecnces as a backend. */ @Singleton class SharedPreferencesStore @Inject constructor(@ApplicationContext context: Context) : PreferencesStore { private lateinit var sharedPreferencesName: String private val activeSharedPreferencesChangeListener = LinkedList<SharedPreferences.OnSharedPreferenceChangeListener>() private lateinit var activeSharedPreferences: SharedPreferences private val commonSharedPreferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) private val privateSharedPreferences: SharedPreferences = context.getSharedPreferences(FILENAME_PRIVATE, Context.MODE_PRIVATE) private val httpSharedPreferences: SharedPreferences = context.getSharedPreferences(FILENAME_HTTP, Context.MODE_PRIVATE) // Some preferences are always read from commonSharedPreferences. We list these out so that we can use the right store when these keys are requested. private val commonPreferenceKeys: Set<String> = setOf( context.getString(R.string.preferenceKeyFirstStart), context.getString(R.string.preferenceKeySetupNotCompleted), context.getString(R.string.preferenceKeyObjectboxMigrated), Preferences.preferenceKeyUserDeclinedEnableLocationPermissions, Preferences.preferenceKeyUserDeclinedEnableLocationServices ) override fun putString(key: String, value: String) { activeSharedPreferences.edit().putString(key, value).apply() } override fun getString(key: String, default: String): String? = activeSharedPreferences.getString(key, default) override fun remove(key: String) { activeSharedPreferences.edit().remove(key).apply() } override fun getBoolean(key: String, default: Boolean): Boolean = if (commonPreferenceKeys.contains(key)) commonSharedPreferences.getBoolean( key, default ) else activeSharedPreferences.getBoolean(key, default) override fun putBoolean(key: String, value: Boolean) { if (commonPreferenceKeys.contains(key)) commonSharedPreferences.edit() .putBoolean(key, value).apply() else activeSharedPreferences.edit() .putBoolean(key, value).apply() } override fun getInt(key: String, default: Int): Int = activeSharedPreferences.getInt(key, default) override fun putInt(key: String, value: Int) { activeSharedPreferences.edit().putInt(key, value).apply() } override fun getFloat(key: String, default: Float): Float = activeSharedPreferences.getFloat(key, default) override fun putFloat(key: String, value: Float) { activeSharedPreferences.edit().putFloat(key, value).apply() } override fun getSharedPreferencesName(): String = sharedPreferencesName override fun putStringSet(key: String, values: Set<String>) { activeSharedPreferences.edit().putStringSet(key, values).apply() } override fun getStringSet(key: String): Set<String> { return activeSharedPreferences.getStringSet(key, setOf()) ?: setOf() } override fun hasKey(key: String): Boolean { return this::activeSharedPreferences.isInitialized && activeSharedPreferences.contains(key) } override fun getInitMode(key: String, default: Int): Int { val initMode = commonSharedPreferences.getInt(key, default) return if (initMode in listOf( MessageProcessorEndpointMqtt.MODE_ID, MessageProcessorEndpointHttp.MODE_ID ) ) { initMode } else { default } } override fun setMode(key: String, mode: Int) { detachAllActivePreferenceChangeListeners() when (mode) { MessageProcessorEndpointMqtt.MODE_ID -> { activeSharedPreferences = privateSharedPreferences sharedPreferencesName = FILENAME_PRIVATE } MessageProcessorEndpointHttp.MODE_ID -> { activeSharedPreferences = httpSharedPreferences sharedPreferencesName = FILENAME_HTTP } } commonSharedPreferences.edit().putInt(key, mode).apply() // Mode switcher reads from currently active sharedPreferences, so we commit the value to all privateSharedPreferences.edit().putInt(key, mode).apply() httpSharedPreferences.edit().putInt(key, mode).apply() attachAllActivePreferenceChangeListeners() } override fun registerOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) { if (this::activeSharedPreferences.isInitialized) { activeSharedPreferences.registerOnSharedPreferenceChangeListener(listener) } activeSharedPreferencesChangeListener.push(listener) } override fun unregisterOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) { if (this::activeSharedPreferences.isInitialized) { activeSharedPreferences.unregisterOnSharedPreferenceChangeListener(listener) } activeSharedPreferencesChangeListener.remove(listener) } private fun detachAllActivePreferenceChangeListeners() { activeSharedPreferencesChangeListener.forEach { activeSharedPreferences.unregisterOnSharedPreferenceChangeListener(it) } } private fun attachAllActivePreferenceChangeListeners() { activeSharedPreferencesChangeListener.forEach { activeSharedPreferences.registerOnSharedPreferenceChangeListener(it) } } companion object { const val FILENAME_PRIVATE = "org.owntracks.android.preferences.private" private const val FILENAME_HTTP = "org.owntracks.android.preferences.http" } }
epl-1.0
fcc13e91c9bb1c6f593e96664adf94cc
39.751592
153
0.726321
5.506024
false
false
false
false
chrsep/Kingfish
app/src/main/java/com/directdev/portal/models/AssignmentIndividualModel.kt
1
832
package com.directdev.portal.models import com.squareup.moshi.Json import io.realm.RealmObject /** * Created by chris on 9/14/2016. */ open class AssignmentIndividualModel( open var classNumber: Int = 0, @Json(name = "AssignmentFrom") open var from: String = "N/A", @Json(name = "Date") open var date: String = "N/A", @Json(name = "StudentAssignmentID") open var id: String = "N/A", @Json(name = "Title") open var title: String = "N/A", @Json(name = "assignmentPathLocation") open var path: String = "N/A", @Json(name = "deadlineDuration") open var deadlineDate: String = "N/A", @Json(name = "deadlineTime") open var deadlineHour: String = "N/A", open var webcontent: String = "N/A" ) : RealmObject()
gpl-3.0
839a1ab80067d9d56c2eb0a19ccde9d9
31.038462
46
0.591346
3.570815
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/form/edit/dialog/SelectFieldDialog.kt
1
7054
package mil.nga.giat.mage.form.edit.dialog import android.os.Bundle import android.view.* import android.widget.ArrayAdapter import android.widget.ListView import androidx.appcompat.widget.SearchView import androidx.fragment.app.DialogFragment import mil.nga.giat.mage.R import mil.nga.giat.mage.databinding.DialogSelectFieldBinding import org.apache.commons.lang3.StringUtils import kotlin.collections.ArrayList class SelectFieldDialog : DialogFragment() { interface SelectFieldDialogListener { fun onSelect(choices: List<String>) } private lateinit var binding: DialogSelectFieldBinding private lateinit var adapter: ArrayAdapter<String> private var title: String? = null private var multi: Boolean = false private var choices: List<String> = ArrayList() private var selectedChoices: MutableList<String> = ArrayList() private var filteredChoices = ArrayList<String>() var listener: SelectFieldDialogListener? = null companion object { private const val TITLE_KEY = "TITLE_KEY" private const val MULTI_SELECT_KEY = "MULTI_SELECT_KEY" private const val VALUE_KEY = "VALUE_KEY" private const val CHOICES_KEY = "CHOICES_KEY" fun newInstance(title: String, choices: List<String>, value: String?): SelectFieldDialog { val fragment = SelectFieldDialog() val bundle = Bundle() bundle.putString(TITLE_KEY, title) bundle.putBoolean(MULTI_SELECT_KEY, false) bundle.putString(VALUE_KEY, value) bundle.putStringArray(CHOICES_KEY, choices.toTypedArray()) fragment.setStyle(STYLE_NO_TITLE, 0) fragment.isCancelable = false fragment.arguments = bundle return fragment } fun newInstance(title: String, choices: List<String>, value: List<String>?): SelectFieldDialog { val fragment = SelectFieldDialog() val bundle = Bundle() bundle.putString(TITLE_KEY, title) bundle.putBoolean(MULTI_SELECT_KEY, true) bundle.putStringArray(VALUE_KEY, value?.toTypedArray()) bundle.putStringArray(CHOICES_KEY, choices.toTypedArray()) fragment.setStyle(STYLE_NO_TITLE, 0) fragment.isCancelable = false fragment.arguments = bundle return fragment } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(STYLE_NORMAL, R.style.AppTheme_Dialog_Fullscreen) title = arguments?.getString(TITLE_KEY, null) val choices = arguments?.getStringArray(CHOICES_KEY) if (choices != null) { this.choices = choices.asList() } multi = arguments?.getBoolean(MULTI_SELECT_KEY, false) ?: false if (multi) { selectedChoices = arguments?.getStringArray(VALUE_KEY)?.asList()?.toMutableList() ?: mutableListOf() } else { arguments?.getString(VALUE_KEY)?.let { selectedChoices.add(it) } } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = DialogSelectFieldBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding.toolbar.setNavigationIcon(R.drawable.ic_close_white_24dp) binding.toolbar.setNavigationOnClickListener { dismiss() } binding.toolbar.title = title if (multi) { binding.toolbar.inflateMenu(R.menu.edit_select_menu) } filteredChoices.addAll(choices) if (multi) { adapter = ArrayAdapter( requireContext(), android.R.layout.simple_list_item_multiple_choice, filteredChoices ) binding.listView.adapter = adapter binding.listView.choiceMode = ListView.CHOICE_MODE_MULTIPLE } else { adapter = ArrayAdapter( requireContext(), android.R.layout.simple_list_item_single_choice, filteredChoices ) binding.listView.adapter = adapter binding.listView.choiceMode = ListView.CHOICE_MODE_SINGLE } if (selectedChoices.isNotEmpty()) { checkSelected() binding.selectedChoices.text = getSelectedChoicesString(selectedChoices) } binding.listView.setOnItemClickListener { adapterView, _, position, _ -> val selectedItem = adapterView.getItemAtPosition(position) as String if (multi) { if (binding.listView.isItemChecked(position)) { if (!selectedChoices.contains(selectedItem)) { selectedChoices.add(selectedItem) } } else { if (selectedChoices.contains(selectedItem)) { selectedChoices.remove(selectedItem) } } } else { selectedChoices.clear() selectedChoices.add(selectedItem) save() } binding.selectedChoices.text = getSelectedChoicesString(selectedChoices) } binding.searchView.isIconified = false binding.searchView.setIconifiedByDefault(false) binding.searchView.clearFocus() binding.searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(text: String): Boolean { return false } override fun onQueryTextChange(text: String): Boolean { onSearchTextChanged(text) return true } }) binding.toolbar.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.apply -> { save() true } else -> super.onOptionsItemSelected(item) } } binding.clear.setOnClickListener { clearSelected() } } private fun getSelectedChoicesString(choices: List<String>): String { return choices.joinToString(", ") } private fun checkSelected() { for (count in selectedChoices.indices) { val index = filteredChoices.indexOf(selectedChoices[count]) if (index != -1) { binding.listView.setItemChecked(index, true) } } } private fun clearSelected() { binding.listView.clearChoices() binding.listView.invalidateViews() selectedChoices.clear() binding.selectedChoices.text = "" if (!multi) { save() dismiss() } } private fun save() { listener?.onSelect(selectedChoices) dismiss() } private fun onSearchTextChanged(text: String) { val context = context ?: return filteredChoices.clear() for (position in choices.indices) { if (text.length <= choices[position].length) { val currentChoice = choices[position] if (StringUtils.containsIgnoreCase(currentChoice, text)) { filteredChoices.add(currentChoice) } } } if (multi) { binding.listView.adapter = ArrayAdapter(context, android.R.layout.simple_list_item_multiple_choice, filteredChoices) binding.listView.choiceMode = ListView.CHOICE_MODE_MULTIPLE } else { binding.listView.adapter = ArrayAdapter(context, android.R.layout.simple_list_item_single_choice, filteredChoices) binding.listView.choiceMode = ListView.CHOICE_MODE_SINGLE } checkSelected() } }
apache-2.0
349e78c3dd2ba7ce706b968c4161d10e
28.638655
106
0.6833
4.542176
false
false
false
false
jaychang0917/SimpleApiClient
library/src/main/java/com/jaychang/sac/calladapter/MockResponseAdapterFactory.kt
1
6845
package com.jaychang.sac.calladapter import android.content.Context import com.google.gson.reflect.TypeToken import com.jaychang.sac.JsonParser import com.jaychang.sac.SimpleApiResult import com.jaychang.sac.annotation.MockResponse import com.jaychang.sac.annotation.Status.* import com.jaychang.sac.annotation.WrappedResponse import com.jaychang.sac.util.Utils import io.reactivex.* import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import okhttp3.MediaType import okhttp3.ResponseBody import retrofit2.* import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.net.UnknownHostException import javax.net.ssl.SSLPeerUnverifiedException internal class MockResponseAdapterFactory(private val isEnabled: Boolean, private val context: Context, private val jsonParser: JsonParser) : CallAdapter.Factory() { companion object { fun create(isEnabled: Boolean, context: Context, jsonParser: JsonParser): MockResponseAdapterFactory { return MockResponseAdapterFactory(isEnabled, context, jsonParser) } } override fun get(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<*, *>? { val rawType = getRawType(type) val isObservable = rawType === Observable::class.java val isFlowable = rawType === Flowable::class.java val isSingle = rawType === Single::class.java val isMaybe = rawType === Maybe::class.java val isCompletable = rawType === Completable::class.java if (!isObservable && !isFlowable && !isSingle && !isMaybe && !isCompletable) { return null } if (annotations.none { it is MockResponse } || !isEnabled) { return null } val mockResponse = annotations.find { it is MockResponse } as MockResponse val status = mockResponse.status if (status == SUCCESS) { return SuccessCallAdapter(type, annotations, mockResponse, isObservable, isFlowable, isSingle, isMaybe, isCompletable) } return ErrorStatusCallAdapter(type, mockResponse, isObservable, isFlowable, isSingle, isMaybe, isCompletable) } inner class SuccessCallAdapter(type: Type, annotations: Array<Annotation>, private val mockAnnotation: MockResponse, private val isObservable: Boolean, private val isFlowable: Boolean, private val isSingle: Boolean, private val isMaybe: Boolean, private val isCompletable: Boolean) : CallAdapter<Any?, Any?> { private var apiResultType: Type? = null init { if (!isCompletable) { val dataType = (type as ParameterizedType).actualTypeArguments[0] apiResultType = if (annotations.any { it is WrappedResponse }) { val wrappedType = annotations.find { it is WrappedResponse } as WrappedResponse TypeToken.getParameterized(wrappedType.value.java, dataType).type } else { dataType } } } override fun adapt(call: Call<Any?>?): Any? { val callable = { if (mockAnnotation.json == -1 || isCompletable) { Unit } else { val json = Utils.toText(context, mockAnnotation.json) val data = jsonParser.parse<Any>(json, apiResultType!!) if (data is SimpleApiResult<Any>) { data.result } else { data } } } return when { isObservable -> Observable.fromCallable(callable).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) isFlowable -> Flowable.fromCallable(callable).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) isSingle -> Single.fromCallable(callable).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) isMaybe -> Maybe.fromCallable(callable).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) isCompletable -> Completable.complete().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) else -> throw IllegalArgumentException("Unsupported type") } } override fun responseType(): Type { return if (isCompletable) Unit::class.java else apiResultType!! } } inner class ErrorStatusCallAdapter(private val type: Type, private val mockResponse: MockResponse, private val isObservable: Boolean, private val isFlowable: Boolean, private val isSingle: Boolean, private val isMaybe: Boolean, private val isCompletable: Boolean) : CallAdapter<Any?, Any?> { override fun adapt(call: Call<Any?>?): Any? { fun error(code: Int? = null, exception: Exception? = null) : Throwable { if (code != null) { val message = if (mockResponse.json != -1) { Utils.toText(context, mockResponse.json) } else { "" } val response = Response.error<String>(code, ResponseBody.create(MediaType.parse("application/json"), message)) return HttpException(response) } return exception!! } fun errorSource(code: Int? = null, exception: Exception? = null): Any { return when { isObservable -> Observable.error<Throwable> { error(code, exception) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) isFlowable -> Flowable.error<Throwable> { error(code, exception) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) isSingle -> Single.error<Throwable> { error(code, exception) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) isMaybe -> Maybe.error<Throwable> { error(code, exception) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) isCompletable -> Completable.error { error(code, exception) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) else -> throw IllegalArgumentException("Unsupported type") } } return when (mockResponse.status) { AUTHENTICATION_ERROR -> { errorSource(code = 403) } CLIENT_ERROR -> { errorSource(code = 400)} SERVER_ERROR -> { errorSource(code = 500) } NETWORK_ERROR -> { errorSource(exception = UnknownHostException()) } SSL_ERROR -> { errorSource(exception = SSLPeerUnverifiedException("mock ssl error")) } else -> throw IllegalArgumentException("Unsupported type") } } override fun responseType(): Type { return type } } }
apache-2.0
f25985ffd8e0d95142d2a8b77827374a
43.745098
165
0.651132
4.985433
false
false
false
false
mcxiaoke/kotlin-koi
core/src/main/kotlin/com/mcxiaoke/koi/ext/Network.kt
1
1605
package com.mcxiaoke.koi.ext import android.content.Context import android.net.ConnectivityManager /** * User: mcxiaoke * Date: 16/1/27 * Time: 11:28 */ enum class NetworkType { WIFI, MOBILE, OTHER, NONE } fun Context.networkTypeName(): String { var result = "(No Network)" try { val cm = this.getConnectivityManager() val info = cm.activeNetworkInfo if (info == null || !info.isConnectedOrConnecting) { return result } result = info.typeName if (info.type == ConnectivityManager.TYPE_MOBILE) { result += info.subtypeName } } catch (ignored: Throwable) { } return result } fun Context.networkOperator(): String { val tm = this.getTelephonyManager() return tm.networkOperator } fun Context.networkType(): NetworkType { val cm = this.getConnectivityManager() val info = cm.activeNetworkInfo if (info == null || !info.isConnectedOrConnecting) { return NetworkType.NONE } val type = info.type if (ConnectivityManager.TYPE_WIFI == type) { return NetworkType.WIFI } else if (ConnectivityManager.TYPE_MOBILE == type) { return NetworkType.MOBILE } else { return NetworkType.OTHER } } fun Context.isWifi(): Boolean { return networkType() == NetworkType.WIFI } fun Context.isMobile(): Boolean { return networkType() == NetworkType.MOBILE } fun Context.isConnected(): Boolean { val cm = this.getConnectivityManager() val info = cm.activeNetworkInfo return info != null && info.isConnectedOrConnecting }
apache-2.0
307eae3409b561ff51914250a949cdd2
23.318182
60
0.653583
4.268617
false
false
false
false
lanhuaguizha/Christian
app/src/main/java/com/christian/nav/gospel/GospelDetailAdapter.kt
1
6338
package com.christian.nav.gospel import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bumptech.glide.Glide import com.christian.R import com.christian.databinding.GospelDetailItemBinding import com.christian.nav.NavActivity import com.google.firebase.firestore.* import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.debug import org.jetbrains.anko.warn import java.util.HashMap import kotlin.collections.ArrayList import kotlin.collections.get /** * Adapter for the RecyclerView in NavDetailFragment */ abstract class GospelDetailAdapter(private var gospelRef: DocumentReference, val navActivity: NavActivity) : androidx.recyclerview.widget.RecyclerView.Adapter<GospelDetailAdapter.ViewHolder>(), EventListener<DocumentSnapshot>, AnkoLogger { private var registration: ListenerRegistration? = null private val snapshots = ArrayList<DocumentSnapshot>() private var snapshot: DocumentSnapshot? = null override fun onEvent(documentSnapshots: DocumentSnapshot?, e: FirebaseFirestoreException?) { if (e != null) { warn { "onEvent:error$e" } onError(e) return } if (documentSnapshots == null) { return } snapshot = documentSnapshots // Dispatch the event debug { "onEvent:numChanges:$documentSnapshots.documentChanges.size" } // for (change in documentSnapshots.documentChanges) { // when (change.type) { // DocumentChange.Type.ADDED -> onDocumentAdded(change) // DocumentChange.Type.MODIFIED -> onDocumentModified(change) // DocumentChange.Type.REMOVED -> onDocumentRemoved(change) // } // } // onDocumentAdded(documentSnapshots) notifyDataSetChanged() onDataChanged() } private fun onDocumentAdded(change: DocumentChange) { snapshots.add(change.newIndex, change.document) notifyItemInserted(change.newIndex) } private fun onDocumentModified(change: DocumentChange) { if (change.oldIndex == change.newIndex) { // Item changed but remained in same position snapshots[change.oldIndex] = change.document notifyItemChanged(change.oldIndex) } else { // Item changed and changed position snapshots.removeAt(change.oldIndex) snapshots.add(change.newIndex, change.document) notifyItemMoved(change.oldIndex, change.newIndex) } } private fun onDocumentRemoved(change: DocumentChange) { snapshots.removeAt(change.oldIndex) notifyItemRemoved(change.oldIndex) } private fun startListening() { if (registration == null) { registration = gospelRef.addSnapshotListener(this) } } fun stopListening() { registration?.remove() registration = null snapshots.clear() notifyDataSetChanged() } fun setQuery(gospelRef: DocumentReference) { // Stop listening stopListening() // Clear existing data snapshots.clear() notifyDataSetChanged() // Listen to new query this.gospelRef = gospelRef startListening() } protected fun getSnapshot(index: Int): DocumentSnapshot { return snapshots[index] } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.gospel_detail_item, parent, false) val binding = GospelDetailItemBinding.bind(view) return ViewHolder(binding) } override fun getItemCount(): Int { if (snapshot != null) { return (snapshot?.data?.get("detail") as java.util.ArrayList<*>).size } else { return 0 } } override fun onBindViewHolder(holder: ViewHolder, position: Int) { snapshot?.let { holder.bind(it) } } class ViewHolder(private val binding: GospelDetailItemBinding) : androidx.recyclerview.widget.RecyclerView.ViewHolder(binding.root) { fun bind(snapshot: DocumentSnapshot) { val subtitle = ((snapshot.data?.get("detail") as java.util.ArrayList<*>)[adapterPosition] as HashMap<*, *>)["subtitle"] if (subtitle != null) { binding.tvGospelDetailItem.visibility = View.VISIBLE binding.tvGospelDetailItem.text = subtitle.toString() } else { binding.tvGospelDetailItem.visibility = View.GONE } val image = ((snapshot.data?.get("detail") as java.util.ArrayList<*>)[adapterPosition] as HashMap<*, *>)["image"] if (image != null) { binding.ivGospelDetailItem.visibility = View.VISIBLE Glide.with(binding.root.context).load(image).into(binding.ivGospelDetailItem) } else { binding.ivGospelDetailItem.visibility = View.GONE } binding.tv2DetailNavItem.text = ((snapshot.data?.get("detail") as java.util.ArrayList<*>)[adapterPosition] as HashMap<*, *>)["content"].toString() // val gospelDetailBean = snapshot.toObject(GospelDetailBean::class.java) // val resources = itemView.resources // Load image // Glide.with(imageView.getContext()) // .load(gospelDetailBean!!.getPhoto()) // .into(imageView) // // nameView.setText(gospelDetailBean!!.getName()) // ratingBar.setRating(gospelDetailBean!!.getAvgRating() as Float) // cityView.setText(gospelDetailBean!!.getCity()) // categoryView.setText(gospelDetailBean!!.getCategory()) // numRatingsView.setText(resources.getString(R.string.fmt_num_ratings, // gospelDetailBean!!.getNumRatings())) // priceView.setText(RestaurantUtil.getPriceString(gospelDetailBean)) // Click listener itemView.setOnClickListener { // if (listener != null) { // listener!!.onGospelSelected(snapshot) // } } } } abstract fun onDataChanged() abstract fun onError(e: FirebaseFirestoreException) }
gpl-3.0
56594341c3fbf929b452d78071d0b384
35.641618
239
0.637109
4.82344
false
false
false
false