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
edvin/tornadofx
src/main/java/tornadofx/Async.kt
1
17999
package tornadofx import com.sun.glass.ui.Application import com.sun.javafx.tk.Toolkit import javafx.application.Platform import javafx.beans.property.* import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import javafx.concurrent.Task import javafx.concurrent.Worker import javafx.scene.Node import javafx.scene.control.Labeled import javafx.scene.control.ProgressIndicator import javafx.scene.control.ToolBar import javafx.scene.layout.BorderPane import javafx.scene.layout.Region import javafx.util.Duration import java.util.* import java.util.concurrent.* import java.util.concurrent.atomic.AtomicLong import java.util.logging.Level import java.util.logging.Logger internal val log = Logger.getLogger("tornadofx.async") internal val dummyUncaughtExceptionHandler = Thread.UncaughtExceptionHandler { t, e -> log.log(Level.WARNING, e) { "Exception in ${t?.name ?: "?"}: ${e?.message ?: "?"}" } } private enum class ThreadPoolType { NoDaemon, Daemon } private val threadPools = mutableMapOf<ThreadPoolType, ExecutorService>() internal val tfxThreadPool: ExecutorService get() = threadPools.getOrPut(ThreadPoolType.NoDaemon) { Executors.newCachedThreadPool(TFXThreadFactory(daemon = false)) } internal val tfxDaemonThreadPool: ExecutorService get() = threadPools.getOrPut(ThreadPoolType.Daemon) { Executors.newCachedThreadPool(TFXThreadFactory(daemon = true)) } internal fun shutdownThreadPools() { threadPools.values.forEach { it.shutdown() } threadPools.clear() } private class TFXThreadFactory(val daemon: Boolean) : ThreadFactory { private val threadCounter = AtomicLong(0L) override fun newThread(runnable: Runnable?) = Thread(runnable, threadName()).apply { isDaemon = daemon } private fun threadName() = "tornadofx-thread-${threadCounter.incrementAndGet()}" + if (daemon) "-daemon" else "" } private fun awaitTermination(pool: ExecutorService, timeout: Long) { synchronized(pool) { // Disable new tasks from being submitted pool.shutdown() } try { // Wait a while for existing tasks to terminate if (!pool.awaitTermination(timeout, TimeUnit.MILLISECONDS)) { synchronized(pool) { pool.shutdownNow() // Cancel currently executing tasks } // Wait a while for tasks to respond to being cancelled if (!pool.awaitTermination(timeout, TimeUnit.MILLISECONDS)) { log.log(Level.SEVERE, "Executor did not terminate") } } } catch (ie: InterruptedException) { // (Re-)Cancel if current thread also interrupted synchronized(pool) { pool.shutdownNow() } // Preserve interrupt status Thread.currentThread().interrupt() } } fun terminateAsyncExecutors(timeoutMillis: Long) { awaitTermination(tfxThreadPool, timeoutMillis) awaitTermination(tfxDaemonThreadPool, timeoutMillis) threadPools.clear() } fun <T> task(taskStatus: TaskStatus? = null, func: FXTask<*>.() -> T): Task<T> = task(daemon = false, taskStatus = taskStatus, func = func) fun <T> task(daemon: Boolean = false, taskStatus: TaskStatus? = null, func: FXTask<*>.() -> T): Task<T> = FXTask(taskStatus, func = func).apply { setOnFailed({ (Thread.getDefaultUncaughtExceptionHandler() ?: dummyUncaughtExceptionHandler).uncaughtException(Thread.currentThread(), exception) }) if (daemon) { tfxDaemonThreadPool.execute(this) } else { tfxThreadPool.execute(this) } } fun <T> runAsync(status: TaskStatus? = null, func: FXTask<*>.() -> T) = task(status, func) fun <T> runAsync(daemon: Boolean = false, status: TaskStatus? = null, func: FXTask<*>.() -> T) = task(daemon, status, func) infix fun <T> Task<T>.ui(func: (T) -> Unit) = success(func) infix fun <T> Task<T>.success(func: (T) -> Unit) = apply { fun attachSuccessHandler() { if (state == Worker.State.SUCCEEDED) { func(value) } else { setOnSucceeded { func(value) } } } if (Application.isEventThread()) attachSuccessHandler() else runLater { attachSuccessHandler() } } infix fun <T> Task<T>.fail(func: (Throwable) -> Unit) = apply { fun attachFailHandler() { if (state == Worker.State.FAILED) { func(exception) } else { setOnFailed { func(exception) } } } if (Application.isEventThread()) attachFailHandler() else runLater { attachFailHandler() } } infix fun <T> Task<T>.cancel(func: () -> Unit) = apply { fun attachCancelHandler() { if (state == Worker.State.CANCELLED) { func() } else { setOnCancelled { func() } } } if (Application.isEventThread()) attachCancelHandler() else runLater { attachCancelHandler() } } /** * Run the specified Runnable on the JavaFX Application Thread at some * unspecified time in the future. */ fun runLater(op: () -> Unit) = Platform.runLater(op) private val runLaterTimer: Timer by lazy { Timer(true) } /** * Run the specified Runnable on the JavaFX Application Thread after a * specified delay. * * runLater(10.seconds) { * // Do something on the application thread * } * * This function returns a TimerTask which includes a runningProperty as well as the owning timer. * You can cancel the task before the time is up to abort the execution. */ fun runLater(delay: Duration, op: () -> Unit): FXTimerTask { val task = FXTimerTask(op, runLaterTimer) runLaterTimer.schedule(task, delay.toMillis().toLong()) return task } /** * Wait on the UI thread until a certain value is available on this observable. * * This method does not block the UI thread even though it halts further execution until the condition is met. */ fun <T> ObservableValue<T>.awaitUntil(condition: (T) -> Boolean) { check(Toolkit.getToolkit().canStartNestedEventLoop()) { "awaitUntil is not allowed during animation or layout processing" } val changeListener = object : ChangeListener<T> { override fun changed(observable: ObservableValue<out T>?, oldValue: T, newValue: T) { if (condition(value)) { runLater { Toolkit.getToolkit().exitNestedEventLoop(this@awaitUntil, null) removeListener(this) } } } } changeListener.changed(this, value, value) addListener(changeListener) Toolkit.getToolkit().enterNestedEventLoop(this) } /** * Wait on the UI thread until this observable value is true. * * This method does not block the UI thread even though it halts further execution until the condition is met. */ fun ObservableValue<Boolean>.awaitUntil() { this.awaitUntil { it } } /** * Replace this node with a progress node while a long running task * is running and swap it back when complete. * * If this node is Labeled, the graphic property will contain the progress bar instead while the task is running. * * The default progress node is a ProgressIndicator that fills the same * client area as the parent. You can swap the progress node for any Node you like. * * For latch usage see [runAsyncWithOverlay] */ fun Node.runAsyncWithProgress(latch: CountDownLatch, timeout: Duration? = null, progress: Node = ProgressIndicator()): Task<Boolean> { return if (timeout == null) { runAsyncWithProgress(progress) { latch.await(); true } } else { runAsyncWithOverlay(progress) { latch.await(timeout.toMillis().toLong(), TimeUnit.MILLISECONDS) } } } /** * Replace this node with a progress node while a long running task * is running and swap it back when complete. * * If this node is Labeled, the graphic property will contain the progress bar instead while the task is running. * * The default progress node is a ProgressIndicator that fills the same * client area as the parent. You can swap the progress node for any Node you like. */ fun <T> Node.runAsyncWithProgress(progress: Node = ProgressIndicator(), op: () -> T): Task<T> { if (this is Labeled) { val oldGraphic = graphic (progress as? Region)?.setPrefSize(16.0, 16.0) graphic = progress return task { try { op() } finally { runLater { [email protected] = oldGraphic } } } } else { val paddingHorizontal = (this as? Region)?.paddingHorizontal?.toDouble() ?: 0.0 val paddingVertical = (this as? Region)?.paddingVertical?.toDouble() ?: 0.0 (progress as? Region)?.setPrefSize(boundsInParent.width - paddingHorizontal, boundsInParent.height - paddingVertical) // Unwrap ToolBar parent, it has an extra HBox or VBox inside it, we need to target the items list val p = (parent?.parent as? ToolBar) ?: parent ?: throw IllegalArgumentException("runAsyncWithProgress cannot target an UI element with no parent!") val children = requireNotNull(p.getChildList()) { "This node has no child list, and cannot contain the progress node" } val index = children.indexOf(this) children.add(index, progress) removeFromParent() return task { val result = op() runLater { children.add(index, this@runAsyncWithProgress) progress.removeFromParent() } result } } } /** * Covers node with overlay (by default - an instance of [MaskPane]) until [latch] is released by another thread. * It's useful when more control over async execution is needed, like: * * A task already have its thread and overlay should be visible until some callback is invoked (it should invoke * [CountDownLatch.countDown] or [Latch.release]) in order to unlock UI. Keep in mind that if [latch] is not released * and [timeout] is not set, overlay may never get removed. * * An overlay should be removed after some time, even if task is getting unresponsive (use [timeout] for this). * Keep in mind that this timeout applies to overlay only, not the latch itself. * * In addition to masking UI, you need an access to property indicating if background process is running; * [Latch.lockedProperty] serves exactly that purpose. * * More threads are involved in task execution. You can create a [CountDownLatch] for number of workers, call * [CountDownLatch.countDown] from each of them when it's done and overlay will stay visible until all workers finish * their jobs. * * @param latch an instance of [CountDownLatch], usage of [Latch] is recommended. * @param timeout timeout after which overlay will be removed anyway. Can be `null` (which means no timeout). * @param overlayNode optional custom overlay node. For best effect set transparency. * * # Example 1 * The simplest case: overlay is visible for two seconds - until latch release. Replace [Thread.sleep] with any * blocking action. Manual thread creation is for the sake of the example only. * * ```kotlin * val latch = Latch() * root.runAsyncWithOverlay(latch) ui { * //UI action * } * * Thread({ * Thread.sleep(2000) * latch.release() * }).start() * ``` * * # Example 2 * The latch won't be released until both workers are done. In addition, until workers are done, button will stay * disabled. New latch has to be created and rebound every time. * * ```kotlin * val latch = Latch(2) * root.runAsyncWithOverlay(latch) * button.disableWhen(latch.lockedProperty()) * runAsync(worker1.work(); latch.countDown()) * runAsync(worker2.work(); latch.countDown()) */ @JvmOverloads fun Node.runAsyncWithOverlay(latch: CountDownLatch, timeout: Duration? = null, overlayNode: Node = MaskPane()): Task<Boolean> { return if (timeout == null) { runAsyncWithOverlay(overlayNode) { latch.await(); true } } else { runAsyncWithOverlay(overlayNode) { latch.await(timeout.toMillis().toLong(), TimeUnit.MILLISECONDS) } } } /** * Runs given task in background thread, covering node with overlay (default one is [MaskPane]) until task is done. * * # Example * * ```kotlin * root.runAsyncWithOverlay { * Thread.sleep(2000) * } ui { * //UI action * } * ``` * * @param overlayNode optional custom overlay node. For best effect set transparency. */ @JvmOverloads fun <T : Any> Node.runAsyncWithOverlay(overlayNode: Node = MaskPane(), op: () -> T): Task<T> { val overlayContainer = stackpane { add(overlayNode) } replaceWith(overlayContainer) overlayContainer.children.add(0, this) return task { try { op() } finally { runLater { overlayContainer.replaceWith(this@runAsyncWithOverlay) } } } } /** * A basic mask pane, intended for blocking gui underneath. Styling example: * * ```css * .mask-pane { * -fx-background-color: rgba(0,0,0,0.5); * -fx-accent: aliceblue; * } * * .mask-pane > .progress-indicator { * -fx-max-width: 300; * -fx-max-height: 300; * } * ``` */ class MaskPane : BorderPane() { init { addClass("mask-pane") center = progressindicator() } override fun getUserAgentStylesheet(): String = MaskPane::class.java.getResource("maskpane.css").toExternalForm() } /** * Adds some superpowers to good old [CountDownLatch], like exposed [lockedProperty] or ability to release latch * immediately. * * By default, initializes a latch with a count of `1`, which means that the first invocation of [countDown] will * allow all waiting threads to proceed. * * All documentation of superclass applies here. Default behavior has not been altered. */ class Latch(count: Int = 1) : CountDownLatch(count) { private val lockedProperty by lazy { ReadOnlyBooleanWrapper(locked) } /** * Locked state of this latch exposed as a property. Keep in mind that latch instance can be used only once, so * this property has to rebound every time. */ fun lockedProperty(): ReadOnlyBooleanProperty = lockedProperty.readOnlyProperty /** * Locked state of this latch. `true` if and only if [CountDownLatch.getCount] is greater than `0`. * Once latch is released it changes to `false` permanently. */ val locked get() = count > 0L /** * Releases latch immediately and allows waiting thread(s) to proceed. Can be safely used if this latch has been * initialized with `count` of `1`, should be used with care otherwise - [countDown] invocations ar preferred in * such cases. */ fun release() = (1..count).forEach { countDown() } //maybe not the prettiest way, but works fine override fun countDown() { super.countDown() lockedProperty.set(locked) } } class FXTimerTask(val op: () -> Unit, val timer: Timer) : TimerTask() { private val internalRunning = ReadOnlyBooleanWrapper(false) val runningProperty: ReadOnlyBooleanProperty get() = internalRunning.readOnlyProperty val running: Boolean get() = runningProperty.value private val internalCompleted = ReadOnlyBooleanWrapper(false) val completedProperty: ReadOnlyBooleanProperty get() = internalCompleted.readOnlyProperty val completed: Boolean get() = completedProperty.value override fun run() { internalRunning.value = true Platform.runLater { try { op() } finally { internalRunning.value = false internalCompleted.value = true } } } } infix fun <T> Task<T>.finally(func: () -> Unit) { require(this is FXTask<*>) { "finally() called on non-FXTask subclass" } finally(func) } class FXTask<T>(val status: TaskStatus? = null, val func: FXTask<*>.() -> T) : Task<T>() { private var internalCompleted = ReadOnlyBooleanWrapper(false) val completedProperty: ReadOnlyBooleanProperty get() = internalCompleted.readOnlyProperty val completed: Boolean get() = completedProperty.value private var finallyListener: (() -> Unit)? = null override fun call() = func(this) init { status?.item = this } fun finally(func: () -> Unit) { this.finallyListener = func } override fun succeeded() { internalCompleted.value = true finallyListener?.invoke() } override fun failed() { internalCompleted.value = true finallyListener?.invoke() } override fun cancelled() { internalCompleted.value = true finallyListener?.invoke() } public override fun updateProgress(workDone: Long, max: Long) { super.updateProgress(workDone, max) } public override fun updateProgress(workDone: Double, max: Double) { super.updateProgress(workDone, max) } @Suppress("UNCHECKED_CAST") fun value(v: Any) { super.updateValue(v as T) } public override fun updateTitle(t: String?) { super.updateTitle(t) } public override fun updateMessage(m: String?) { super.updateMessage(m) } } open class TaskStatus : ItemViewModel<FXTask<*>>() { val running: ReadOnlyBooleanProperty = bind { SimpleBooleanProperty().apply { if (item != null) bind(item.runningProperty()) } } val completed: ReadOnlyBooleanProperty = bind { SimpleBooleanProperty().apply { if (item != null) bind(item.completedProperty) } } val message: ReadOnlyStringProperty = bind { SimpleStringProperty().apply { if (item != null) bind(item.messageProperty()) } } val title: ReadOnlyStringProperty = bind { SimpleStringProperty().apply { if (item != null) bind(item.titleProperty()) } } val progress: ReadOnlyDoubleProperty = bind { SimpleDoubleProperty().apply { if (item != null) bind(item.progressProperty()) } } }
apache-2.0
6941d88a8f512d9939e8c298d5d7f81a
34.223092
173
0.668037
4.360223
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/MainActivity.kt
1
5371
/* * Copyright (c) 2018 NECTEC * National Electronics and Computer Technology Center, Thailand * * 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 ffc.app import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import android.net.Uri import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v7.app.ActionBarDrawerToggle import android.transition.Fade import android.view.MenuItem import android.widget.ImageView import android.widget.TextView import ffc.android.enter import ffc.android.load import ffc.android.observe import ffc.android.onClick import ffc.android.sceneTransition import ffc.android.setTransition import ffc.android.viewModel import ffc.app.auth.auth import ffc.app.location.GeoMapsFragment import ffc.app.location.housesOf import ffc.app.search.SearchActivity import ffc.app.setting.AboutActivity import ffc.app.setting.SettingsActivity import kotlinx.android.synthetic.main.activity_main.drawerLayout import kotlinx.android.synthetic.main.activity_main.navView import kotlinx.android.synthetic.main.activity_main_content.addLocationButton import kotlinx.android.synthetic.main.activity_main_content.searchButton import kotlinx.android.synthetic.main.activity_main_content.toolbar import kotlinx.android.synthetic.main.activity_main_content.versionView import org.jetbrains.anko.browse import org.jetbrains.anko.dimen import org.jetbrains.anko.find import org.jetbrains.anko.intentFor import org.jetbrains.anko.startActivity import org.jetbrains.anko.toast class MainActivity : FamilyFolderActivity(), NavigationView.OnNavigationItemSelectedListener { private val geoMapsFragment by lazy { GeoMapsFragment() } private val viewModel by lazy { viewModel<MainViewModel>() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setTransition { exitTransition = null reenterTransition = Fade().enter() } searchButton.onClick { startActivity(intentFor<SearchActivity>(), sceneTransition(toolbar to getString(R.string.transition_appbar))) } setupNavigationDrawer() versionView.text = BuildConfig.VERSION_NAME with(geoMapsFragment) { setPaddingTop(dimen(R.dimen.maps_padding_top)) } supportFragmentManager .beginTransaction() .replace(R.id.contentContainer, geoMapsFragment, "geomap") .commit() addLocationButton.hide() observe(viewModel.houseNoLocation) { if (it == true) addLocationButton.show() else addLocationButton.hide() } } private fun setupNavigationDrawer() { val toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawerLayout.addDrawerListener(toggle) toggle.syncState() navView.setNavigationItemSelectedListener(this) } override fun onResume() { super.onResume() checkHouseNoLocation() with(navView.getHeaderView(0)) { val user = auth(context).user!! find<TextView>(R.id.userDisplayNameView).text = user.displayName user.avatarUrl?.let { find<ImageView>(R.id.userAvartarView).load(Uri.parse(it)) } find<TextView>(R.id.orgDisplayNameView).text = org!!.displayName } } override fun onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onNavigationItemSelected(item: MenuItem): Boolean { // Handle navigation view item clicks here. when (item.itemId) { R.id.nav_main -> { } R.id.nav_follow -> browse("https://www.facebook.com/FFC.NECTEC/", true) R.id.nav_achivement, R.id.nav_manual -> { toast(R.string.under_construction) } R.id.nav_about -> startActivity<AboutActivity>() R.id.nav_settings -> startActivity<SettingsActivity>() R.id.nav_logout -> { auth(this).clear() finish() } } drawerLayout.closeDrawer(GravityCompat.START) return true } private fun checkHouseNoLocation() { housesOf(org!!).houseNoLocation { onFound { viewModel.houseNoLocation.value = true } onNotFound { viewModel.houseNoLocation.value = false } onFail { } } } class MainViewModel : ViewModel() { val houseNoLocation = MutableLiveData<Boolean>() } }
apache-2.0
6f49b2a4032c4e9c0d582ead856c3098
34.335526
94
0.695215
4.524853
false
false
false
false
pokk/KotlinKnifer
kotlinknifer/src/main/java/com/devrapid/kotlinknifer/Bundle.kt
1
829
package com.devrapid.kotlinknifer import android.app.Activity import androidx.fragment.app.Fragment inline fun <reified T : Any> Activity.extra(key: String, default: T? = null) = lazy { val value = intent?.extras?.get(key) if (value is T) value else default } inline fun <reified T : Any> Activity.extraNotNull(key: String, default: T? = null) = lazy { val value = intent?.extras?.get(key) requireNotNull(if (value is T) value else default) { key } } inline fun <reified T : Any> Fragment.extra(key: String, default: T? = null) = lazy { val value = arguments?.get(key) if (value is T) value else default } inline fun <reified T : Any> Fragment.extraNotNull(key: String, default: T? = null) = lazy { val value = arguments?.get(key) requireNotNull(if (value is T) value else default) { key } }
apache-2.0
8b60523e6babe54384e420a52a8fa5e8
33.541667
92
0.686369
3.42562
false
false
false
false
digammas/damas
solutions.digamma.damas.jcr/src/main/kotlin/solutions/digamma/damas/jcr/content/JcrFolderManager.kt
1
2051
package solutions.digamma.damas.jcr.content import solutions.digamma.damas.common.WorkspaceException import solutions.digamma.damas.content.Folder import solutions.digamma.damas.content.FolderManager import solutions.digamma.damas.jcr.model.JcrCrudManager import solutions.digamma.damas.jcr.model.JcrPathFinder import solutions.digamma.damas.jcr.model.JcrSearchEngine import solutions.digamma.damas.jcr.names.TypeNamespace import solutions.digamma.damas.logging.Logged import javax.inject.Singleton import javax.jcr.Node import javax.jcr.RepositoryException /** * JCR implementation convert folder manager. * * @author Ahmad Shahwan */ @Singleton internal open class JcrFolderManager : JcrCrudManager<Folder>(), JcrPathFinder<Folder>, JcrSearchEngine<Folder>, FolderManager { @Logged @Throws(WorkspaceException::class) override fun copy(sourceId: String, destinationId: String): Folder { return this.doRetrieve(sourceId).duplicate(destinationId) } @Throws(RepositoryException::class, WorkspaceException::class) override fun doRetrieve(id: String) = JcrFolder.of(this.session.getNodeByIdentifier(id)) @Throws(RepositoryException::class, WorkspaceException::class) override fun doCreate(pattern: Folder) = JcrFolder.from(this.session, pattern.parentId, pattern.name) @Throws(RepositoryException::class, WorkspaceException::class) override fun doUpdate(id: String, pattern: Folder) = this.doRetrieve(id).also { it.update(pattern) } @Throws(RepositoryException::class, WorkspaceException::class) override fun doDelete(id: String) = this.doRetrieve(id).remove() @Throws(RepositoryException::class, WorkspaceException::class) override fun doFind(path: String) = JcrFolder.of(this.session.getNode("${JcrFile.ROOT_PATH}$path")) override fun getNodePrimaryType() = TypeNamespace.FOLDER override fun getDefaultRootPath() = JcrFile.ROOT_PATH override fun fromNode(node: Node) = JcrFolder.of(node) }
mit
20a7808463c272add83135866869ecfb
34.362069
72
0.755241
4.160243
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/watchlist/WatchlistItemView.kt
1
5185
package org.wikipedia.watchlist import android.content.Context import android.graphics.Typeface import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.View.OnClickListener import android.view.ViewGroup import android.widget.FrameLayout import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.databinding.ItemWatchlistBinding import org.wikipedia.dataclient.mwapi.MwQueryResult import org.wikipedia.util.DateUtil import org.wikipedia.util.L10nUtil import org.wikipedia.util.ResourceUtil import org.wikipedia.util.StringUtil class WatchlistItemView constructor(context: Context, attrs: AttributeSet? = null) : FrameLayout(context, attrs) { val binding = ItemWatchlistBinding.inflate(LayoutInflater.from(context), this, true) var callback: Callback? = null private var item: MwQueryResult.WatchlistItem? = null private var clickListener = OnClickListener { if (item != null) { callback?.onItemClick(item!!) } } init { layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) binding.containerView.setOnClickListener(clickListener) binding.diffText.setOnClickListener(clickListener) binding.userNameText.setOnClickListener { if (item != null) { callback?.onUserClick(item!!, it) } } if (WikipediaApp.instance.languageState.appLanguageCodes.size == 1) { binding.langCodeBackground.visibility = GONE binding.langCodeText.visibility = GONE } else { binding.langCodeBackground.visibility = VISIBLE binding.langCodeText.visibility = VISIBLE } } fun setItem(item: MwQueryResult.WatchlistItem) { this.item = item var isSummaryEmpty = false binding.titleText.text = item.title binding.langCodeText.text = item.wiki!!.languageCode binding.summaryText.text = StringUtil.fromHtml(item.parsedComment).ifEmpty { isSummaryEmpty = true context.getString(R.string.page_edit_history_comment_placeholder) } binding.summaryText.setTypeface(Typeface.SANS_SERIF, if (isSummaryEmpty) Typeface.ITALIC else Typeface.NORMAL) binding.summaryText.setTextColor(ResourceUtil.getThemedColor(context, if (isSummaryEmpty) R.attr.material_theme_secondary_color else R.attr.material_theme_primary_color)) binding.timeText.text = DateUtil.getTimeString(context, item.date) binding.userNameText.text = item.user binding.userNameText.contentDescription = context.getString(R.string.talk_user_title, item.user) binding.userNameText.setIconResource(if (item.isAnon) R.drawable.ic_anonymous_ooui else R.drawable.ic_user_avatar) if (item.logtype.isNotEmpty()) { when (item.logtype) { context.getString(R.string.page_moved) -> { setButtonTextAndIconColor(context.getString(R.string.watchlist_page_moved), R.drawable.ic_info_outline_black_24dp) } context.getString(R.string.page_protected) -> { setButtonTextAndIconColor(context.getString(R.string.watchlist_page_protected), R.drawable.ic_baseline_lock_24) } context.getString(R.string.page_deleted) -> { setButtonTextAndIconColor(context.getString(R.string.watchlist_page_deleted), R.drawable.ic_delete_white_24dp) } } binding.containerView.alpha = 0.5f binding.containerView.isClickable = false } else { val diffByteCount = item.newlen - item.oldlen setButtonTextAndIconColor(StringUtil.getDiffBytesText(context, diffByteCount), textAllCaps = false) if (diffByteCount >= 0) { binding.diffText.setTextColor(if (diffByteCount > 0) ContextCompat.getColor(context, R.color.green50) else ResourceUtil.getThemedColor(context, R.attr.material_theme_secondary_color)) } else { binding.diffText.setTextColor(ContextCompat.getColor(context, R.color.red50)) } binding.containerView.alpha = 1.0f binding.containerView.isClickable = true } L10nUtil.setConditionalLayoutDirection(this, item.wiki!!.languageCode) } private fun setButtonTextAndIconColor(text: String, @DrawableRes iconResourceDrawable: Int = 0, textAllCaps: Boolean = true) { val themedTint = ResourceUtil.getThemedColorStateList(context, R.attr.color_group_61) binding.diffText.text = text binding.diffText.setTextColor(themedTint) binding.diffText.setIconResource(iconResourceDrawable) binding.diffText.iconTint = themedTint binding.diffText.isAllCaps = textAllCaps } interface Callback { fun onItemClick(item: MwQueryResult.WatchlistItem) fun onUserClick(item: MwQueryResult.WatchlistItem, view: View) } }
apache-2.0
64ed0013e9a5ffc95d7bd512d16c2f6b
46.568807
134
0.696046
4.556239
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/statuses/AbsRequestStatusesLoader.kt
1
8939
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.loader.statuses import android.accounts.AccountManager import android.content.Context import android.content.SharedPreferences import android.support.annotation.WorkerThread import org.mariotaku.kpreferences.get import de.vanita5.microblog.library.MicroBlogException import de.vanita5.microblog.library.twitter.model.Paging import de.vanita5.microblog.library.twitter.model.Status import de.vanita5.twittnuker.R import de.vanita5.twittnuker.TwittnukerConstants.LOGTAG import de.vanita5.twittnuker.constant.loadItemLimitKey import de.vanita5.twittnuker.extension.model.api.applyLoadLimit import de.vanita5.twittnuker.loader.iface.IPaginationLoader import de.vanita5.twittnuker.model.AccountDetails import de.vanita5.twittnuker.model.ListResponse import de.vanita5.twittnuker.model.ParcelableStatus import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.pagination.PaginatedArrayList import de.vanita5.twittnuker.model.pagination.PaginatedList import de.vanita5.twittnuker.model.pagination.Pagination import de.vanita5.twittnuker.model.pagination.SinceMaxPagination import de.vanita5.twittnuker.model.util.AccountUtils import de.vanita5.twittnuker.task.twitter.GetStatusesTask import de.vanita5.twittnuker.util.DebugLog import de.vanita5.twittnuker.util.UserColorNameManager import de.vanita5.twittnuker.util.cache.JsonCache import de.vanita5.twittnuker.util.dagger.GeneralComponent import java.io.IOException import java.util.* import java.util.concurrent.atomic.AtomicReference import javax.inject.Inject abstract class AbsRequestStatusesLoader( context: Context, val accountKey: UserKey?, adapterData: List<ParcelableStatus>?, private val savedStatusesArgs: Array<String>?, tabPosition: Int, fromUser: Boolean, protected val loadingMore: Boolean ) : ParcelableStatusesLoader(context, adapterData, tabPosition, fromUser), IPaginationLoader { // Statuses sorted descending by default open val comparator: Comparator<ParcelableStatus>? = ParcelableStatus.REVERSE_COMPARATOR var exception: MicroBlogException? get() = exceptionRef.get() private set(value) { exceptionRef.set(value) } override var pagination: Pagination? = null override var nextPagination: Pagination? = null protected set override var prevPagination: Pagination? = null protected set protected open val isGapEnabled: Boolean = true protected val profileImageSize: String = context.getString(R.string.profile_image_size) @Inject lateinit var jsonCache: JsonCache @Inject lateinit var preferences: SharedPreferences @Inject lateinit var userColorNameManager: UserColorNameManager private val exceptionRef = AtomicReference<MicroBlogException?>() private val cachedData: List<ParcelableStatus>? get() { val key = serializationKey ?: return null return jsonCache.getList(key, ParcelableStatus::class.java) } private val serializationKey: String? get() = savedStatusesArgs?.joinToString("_") init { GeneralComponent.get(context).inject(this) } @SuppressWarnings("unchecked") override final fun loadInBackground(): ListResponse<ParcelableStatus> { val context = context val comparator = this.comparator val accountKey = accountKey ?: return ListResponse.getListInstance<ParcelableStatus>(MicroBlogException("No Account")) val details = AccountUtils.getAccountDetails(AccountManager.get(context), accountKey, true) ?: return ListResponse.getListInstance<ParcelableStatus>(MicroBlogException("No Account")) if (isFirstLoad && tabPosition >= 0) { val cached = cachedData if (cached != null) { data.addAll(cached) if (comparator != null) { data.sortWith(comparator) } else { data.sort() } return ListResponse.getListInstance(data) } } if (!fromUser) return ListResponse.getListInstance(data) val noItemsBefore = data.isEmpty() val loadItemLimit = preferences[loadItemLimitKey] val statuses = try { val paging = Paging().apply { processPaging(this, details, loadItemLimit) } getStatuses(details, paging) } catch (e: MicroBlogException) { // mHandler.post(new ShowErrorRunnable(e)); exception = e DebugLog.w(tr = e) return ListResponse.getListInstance(data, e) } nextPagination = statuses.nextPage prevPagination = statuses.previousPage var minIdx = -1 var rowsDeleted = 0 for (i in 0 until statuses.size) { val status = statuses[i] if (minIdx == -1 || status < statuses[minIdx]) { minIdx = i } if (deleteStatus(data, status.id)) { rowsDeleted++ } } // Insert a gap. val deletedOldGap = rowsDeleted > 0 && statuses.foundInPagination() val noRowsDeleted = rowsDeleted == 0 val insertGap = minIdx != -1 && (noRowsDeleted || deletedOldGap) && !noItemsBefore && statuses.size >= loadItemLimit && !loadingMore if (statuses.isNotEmpty()) { val firstSortId = statuses.first().sort_id val lastSortId = statuses.last().sort_id // Get id diff of first and last item val sortDiff = firstSortId - lastSortId statuses.forEachIndexed { i, status -> status.is_gap = insertGap && isGapEnabled && minIdx == i status.position_key = GetStatusesTask.getPositionKey(status.timestamp, status.sort_id, lastSortId, sortDiff, i, statuses.size) } data.addAll(statuses) } data.forEach { it.is_filtered = shouldFilterStatus(it) } if (comparator != null) { data.sortWith(comparator) } else { data.sort() } saveCachedData(data) return ListResponse.getListInstance(data) } override final fun onStartLoading() { exception = null super.onStartLoading() } @WorkerThread protected abstract fun shouldFilterStatus(status: ParcelableStatus): Boolean protected open fun processPaging(paging: Paging, details: AccountDetails, loadItemLimit: Int) { paging.applyLoadLimit(details, loadItemLimit) pagination?.applyTo(paging) } protected open fun List<ParcelableStatus>.foundInPagination(): Boolean { val pagination = [email protected] return when (pagination) { is SinceMaxPagination -> return any { it.id == pagination.maxId } else -> false } } @Throws(MicroBlogException::class) protected abstract fun getStatuses(account: AccountDetails, paging: Paging): PaginatedList<ParcelableStatus> private fun saveCachedData(data: List<ParcelableStatus>?) { val key = serializationKey if (key == null || data == null) return val databaseItemLimit = preferences[loadItemLimitKey] try { val statuses = data.subList(0, Math.min(databaseItemLimit, data.size)) jsonCache.saveList(key, statuses, ParcelableStatus::class.java) } catch (e: Exception) { // Ignore if (e !is IOException) { DebugLog.w(LOGTAG, "Error saving cached data", e) } } } companion object { inline fun <R> List<Status>.mapMicroBlogToPaginated(transform: (Status) -> R): PaginatedList<R> { val result = mapTo(PaginatedArrayList(size), transform) result.nextPage = SinceMaxPagination().apply { maxId = lastOrNull()?.id } return result } } }
gpl-3.0
a3324d80cfeebea174c0170392feb7b3
37.369099
126
0.672558
4.69732
false
false
false
false
slartus/4pdaClient-plus
app/src/main/java/org/softeg/slartus/forpdaplus/ShortUserInfo.kt
1
14204
package org.softeg.slartus.forpdaplus import android.content.SharedPreferences import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.os.AsyncTask import android.os.Handler import android.os.Looper import android.text.InputType import android.text.TextUtils import android.util.Log import android.view.View import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.constraintlayout.widget.Group import coil.load import com.afollestad.materialdialogs.MaterialDialog import com.nostra13.universalimageloader.core.ImageLoader import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener import de.hdodenhof.circleimageview.CircleImageView import kotlinx.coroutines.* import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.distinctUntilChanged import org.jsoup.Jsoup import org.jsoup.nodes.Element import org.softeg.slartus.forpdacommon.setAllOnClickListener import org.softeg.slartus.forpdaplus.classes.FastBlur import org.softeg.slartus.forpdaplus.classes.common.StringUtils import org.softeg.slartus.forpdaplus.fragments.profile.ProfileFragment import org.softeg.slartus.forpdaplus.listtemplates.QmsContactsBrickInfo import org.softeg.slartus.forpdaplus.prefs.Preferences import org.softeg.slartus.forpdaplus.repositories.UserInfoRepositoryImpl import org.softeg.slartus.hosthelper.HostHelper import ru.slartus.http.Http import timber.log.Timber import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException import java.lang.ref.WeakReference import java.util.regex.Pattern class ShortUserInfo internal constructor(activity: MainActivity, private val view: View) { companion object { private const val TAG = "ShortUserInfo" } var mActivity: WeakReference<MainActivity> = WeakReference(activity) var prefs: SharedPreferences = App.getInstance().preferences private val imgAvatar: CircleImageView private val imgAvatarSquare: ImageView private val userBackground: ImageView private val userNick: TextView private val qmsMessages: TextView private val loginButton: TextView private val userRep: TextView private val profileGroup: Group private val avatarsGroup: Group var mHandler = Handler(Looper.getMainLooper()) var client: Client = Client.getInstance() private val isSquare: Boolean private var avatarUrl = "" private fun getContext() = mActivity.get() init { userNick = findViewById(R.id.userNick) as TextView qmsMessages = findViewById(R.id.qmsMessages) as TextView loginButton = findViewById(R.id.loginButton) as TextView userRep = findViewById(R.id.userRep) as TextView imgAvatar = findViewById(R.id.imgAvatar) as CircleImageView imgAvatarSquare = findViewById(R.id.imgAvatarSquare) as ImageView val infoRefresh = findViewById(R.id.infoRefresh) as ImageView val openLink = findViewById(R.id.openLink) as ImageView userBackground = findViewById(R.id.userBackground) as ImageView isSquare = prefs.getBoolean("isSquareAvarars", false) avatarsGroup = findViewById(R.id.avatar_group) as Group profileGroup = findViewById(R.id.profile_info_group) as Group profileGroup.setAllOnClickListener { val brickInfo = QmsContactsBrickInfo() MainActivity.addTab(brickInfo.title, brickInfo.name, brickInfo.createFragment()) //ListFragmentActivity.showListFragment(getContext(), QmsContactsBrickInfo.NAME, null); } openLink.setOnClickListener { var url: String? url = StringUtils.fromClipboard(getContext()) if (url == null) url = "" MaterialDialog.Builder(getContext()!!) .title(R.string.go_to_link) .input( App.getInstance().getString(R.string.insert_link), if (isPdaLink(url)) url else null ) { _, _ -> } .inputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE) .positiveText(R.string.open) .negativeText(R.string.cancel) .onPositive { dialog, _ -> assert(dialog.inputEditText != null) if (!IntentActivity.tryShowUrl( getContext(), getContext()?.getHandler(), dialog.inputEditText!!.text.toString() + "", false, false ) ) { Toast.makeText( getContext(), R.string.links_not_supported, Toast.LENGTH_SHORT ).show() } } .show() } val imgFile = File(prefs.getString("userInfoBg", "")!!) if (imgFile.exists()) { // ImageLoader.getInstance().displayImage("file://" + imgFile.path, userBackground) } avatarsGroup.setAllOnClickListener { ProfileFragment.showProfile( UserInfoRepositoryImpl.instance.getId(), client.user ) } loginButton.setOnClickListener { LoginDialog.showDialog(getContext()) } if (!Http.isOnline(App.getContext())) { loginButton.setText(R.string.check_connection) } infoRefresh.setOnClickListener { if (Http.isOnline(App.getContext()) and client.logined) { updateAsyncTask().execute() } } GlobalScope.launch(Dispatchers.IO) { UserInfoRepositoryImpl.instance.userInfo .distinctUntilChanged() .collect { userInfo -> withContext(Dispatchers.Main) { avatarsGroup.visibility = if (userInfo.logined) View.VISIBLE else View.GONE profileGroup.visibility = if (userInfo.logined) View.VISIBLE else View.GONE loginButton.visibility = if (userInfo.logined) View.GONE else View.VISIBLE if (userInfo.logined && !TextUtils.isEmpty(userInfo.id)) { updateAsyncTask().execute() } refreshQms(userInfo.qmsCount ?: 0) } } } } private fun findViewById(id: Int): View { return view.findViewById(id) } private fun refreshQms() { refreshQms(UserInfoRepositoryImpl.instance.getQmsCount() ?: 0) } private fun refreshQms(qmsCount: Int) { if (qmsCount != 0) { qmsMessages.text = String.format(App.getInstance().getString(R.string.new_qms_messages), qmsCount) } else { qmsMessages.setText(R.string.no_new_qms_messages) } } private inner class updateAsyncTask : AsyncTask<String, Void, Boolean?>() { var reputation = "" private var ex: Throwable? = null override fun doInBackground(vararg urls: String): Boolean? { try { val doc = Jsoup.parse(client.performGet("https://" + HostHelper.host + "/forum/index.php?showuser=" + UserInfoRepositoryImpl.instance.getId()).responseBody) var el: Element? = doc.selectFirst("div.user-box > div.photo > img") if (el != null) avatarUrl = el.attr("src") el = doc.selectFirst("div.statistic-box") if (el != null && el.children().size > 0) { val repa = el.child(1).selectFirst("ul > li > div.area")?.text() if (repa != null) { reputation = repa } } } catch (e: IOException) { ex = e } return null } override fun onPostExecute(result: Boolean?) { if (ex != null) { Timber.e(ex) } when { (avatarUrl == "") or (reputation == "") -> { loginButton.setText(R.string.unknown_error) qmsMessages.visibility = View.GONE } client.logined!! -> { userNick.text = client.user userRep.visibility = View.VISIBLE userRep.text = String.format( "%s: %s", App.getContext().getString(R.string.reputation), reputation ) refreshQms() if (prefs.getBoolean("isUserBackground", false)) { val imgFile = File(prefs.getString("userInfoBg", "")!!) if (imgFile.exists()) { userBackground.load(imgFile) } } else { if ((avatarUrl != prefs.getString("userAvatarUrl", "")) or (prefs.getString( "userInfoBg", "" ) == "") ) { ImageLoader.getInstance() .loadImage(avatarUrl, object : SimpleImageLoadingListener() { override fun onLoadingComplete( imageUri: String?, view: View?, loadedImage: Bitmap? ) { userBackground.post { if (loadedImage == null) return@post if (loadedImage.width == 0 || loadedImage.height == 0) return@post blur(loadedImage, userBackground, avatarUrl) prefs.edit().putString("userAvatarUrl", avatarUrl) .apply() } } }) } else { val imgFile = File(prefs.getString("userInfoBg", "")!!) if (imgFile.exists()) { ImageLoader.getInstance() .displayImage("file:///" + imgFile.path, userBackground) } } } ImageLoader.getInstance() .displayImage(avatarUrl, if (isSquare) imgAvatarSquare else imgAvatar) prefs.edit() .putString("shortUserInfoRep", reputation) .apply() //prefs.edit().putBoolean("isLoadShortUserInfo", true).apply(); //prefs.edit().putString("shortAvatarUrl", avatarUrl).apply(); } else -> { userRep.visibility = View.GONE loginButton.visibility = View.VISIBLE } } } } private fun blur(bkg: Bitmap?, view: ImageView, url: String) { try { var bkg = bkg bkg = Bitmap.createScaledBitmap(bkg!!, view.width, view.height, false) val scaleFactor = 3f val radius = 64 var overlay: Bitmap? = Bitmap.createBitmap( (view.width / scaleFactor).toInt(), (view.height / scaleFactor).toInt(), Bitmap.Config.RGB_565 ) val canvas = Canvas(overlay!!) canvas.translate(-view.left / scaleFactor, -view.top / scaleFactor) canvas.scale(1 / scaleFactor, 1 / scaleFactor) val paint = Paint() paint.flags = Paint.FILTER_BITMAP_FLAG canvas.drawBitmap(bkg!!, 0f, 0f, paint) overlay = FastBlur.doBlur(overlay, radius, true) view.setImageBitmap(overlay) storeImage(overlay, url) } catch (ex: Throwable) { ex.printStackTrace() } } private fun storeImage(image: Bitmap?, url: String) { val pictureFile = getOutputMediaFile(url) ?: return try { val fos = FileOutputStream(pictureFile) image!!.compress(Bitmap.CompressFormat.PNG, 100, fos) fos.close() } catch (e: FileNotFoundException) { Log.d(TAG, "File not found: " + e.message) } catch (e: IOException) { Log.d(TAG, "Error accessing file: " + e.message) } } private fun getOutputMediaFile(url: String): File? { // To be safe, you should check that the SDCard is mounted // using Environment.getExternalStorageState() before doing this. val mediaStorageDir = File(Preferences.System.systemDir) // This location works best if you want the created images to be shared // between applications and persist after your app has been uninstalled. // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { return null } } // Create a media file name val tsLong = System.currentTimeMillis() / 1000 var name = tsLong.toString() val m = Pattern.compile("https://s.4pda.to/(.*?)\\.").matcher(url) if (m.find()) { name = m.group(1) } val file = mediaStorageDir.path + File.separator + name + ".png" prefs.edit().putString("userInfoBg", file).apply() return File(file) } private fun isPdaLink(url: String): Boolean { return Pattern.compile(HostHelper.host + "/([^/$?&]+)", Pattern.CASE_INSENSITIVE) .matcher(url).find() } }
apache-2.0
bd73b7d953cd69091ec749177382ec0f
39.470085
166
0.54724
5.148242
false
false
false
false
kkorolyov/Pancake
killstreek/src/main/kotlin/dev/kkorolyov/killstreek/component/Health.kt
1
973
package dev.kkorolyov.killstreek.component import dev.kkorolyov.pancake.platform.entity.Component import dev.kkorolyov.pancake.platform.math.BoundedValue /** * Maintains an entity's state of existence. * @param max maximum value for health, constrained {@code > 0} * @param current initial health, constrained {@code <= max} */ class Health(max: Int, current: Int = max) : Component { /** health value */ val value: BoundedValue<Int> = BoundedValue<Int>(null, max, current) /** percentage of current health with respect to max health */ val percentage: Double get() = value.get().toDouble() / value.maximum.toDouble() /** whether current health {@code <= 0} */ val isDead: Boolean get() = value.get() <= 0 /** whether current health {@code < 0} */ val isSuperDead: Boolean get() = value.get() < 0 /** * Applies a change to current health. * @param amount change in current health */ fun change(amount: Int) { value.set(value.get() + amount) } }
bsd-3-clause
afc17981cd835d1d24ed9838db445717
31.433333
81
0.694758
3.426056
false
false
false
false
AndroidX/androidx
bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/AdvertiseSettings.kt
3
5679
/* * 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.bluetooth.core import android.bluetooth.le.AdvertiseSettings as FwkAdvertiseSettings import android.os.Bundle import androidx.annotation.RestrictTo /** * The {@link AdvertiseSettings} provide a way to adjust advertising preferences for each * Bluetooth LE advertisement instance. Use the constructor to create an instance of this class. */ @SuppressWarnings("HiddenSuperclass") // Bundleable class AdvertiseSettings internal constructor(internal val fwkInstance: FwkAdvertiseSettings) : Bundleable { companion object { internal const val FIELD_FWK_ADVERTISE_SETTINGS = 0 /** * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) @JvmField val CREATOR: Bundleable.Creator<AdvertiseSettings> = object : Bundleable.Creator<AdvertiseSettings> { override fun fromBundle(bundle: Bundle): AdvertiseSettings { val fwkAdvertiseSettings = Utils.getParcelableFromBundle( bundle, keyForField(FIELD_FWK_ADVERTISE_SETTINGS), android.bluetooth.le.AdvertiseSettings::class.java ) ?: throw IllegalArgumentException( "Bundle doesn't include a framework advertise settings" ) return AdvertiseSettings(fwkAdvertiseSettings) } } internal fun keyForField(field: Int): String { return field.toString(Character.MAX_RADIX) } internal fun buildFwkAdvertiseSettings( advertiseMode: Int, advertiseTxPowerLevel: Int, advertiseConnectable: Boolean, advertiseTimeoutMillis: Int, ): FwkAdvertiseSettings { val builder = FwkAdvertiseSettings.Builder() .setConnectable(advertiseConnectable) .setAdvertiseMode(advertiseMode) .setTxPowerLevel(advertiseTxPowerLevel) .setTimeout(advertiseTimeoutMillis) return builder.build() } /** * Perform Bluetooth LE advertising in low power mode. This is the default and preferred * advertising mode as it consumes the least power. */ const val ADVERTISE_MODE_LOW_POWER = FwkAdvertiseSettings.ADVERTISE_MODE_LOW_POWER /** * Perform Bluetooth LE advertising in balanced power mode. This is balanced between * advertising frequency and power consumption. */ const val ADVERTISE_MODE_BALANCED = FwkAdvertiseSettings.ADVERTISE_MODE_BALANCED /** * Perform Bluetooth LE advertising in low latency, high power mode. This has the highest * power consumption and should not be used for continuous background advertising. */ const val ADVERTISE_MODE_LOW_LATENCY = FwkAdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY /** * Advertise using the lowest transmission (TX) power level. Low transmission power can be * used to restrict the visibility range of advertising packets. */ const val ADVERTISE_TX_POWER_ULTRA_LOW = FwkAdvertiseSettings.ADVERTISE_TX_POWER_ULTRA_LOW /** * Advertise using low TX power level. */ const val ADVERTISE_TX_POWER_LOW = FwkAdvertiseSettings.ADVERTISE_TX_POWER_LOW /** * Advertise using medium TX power level. */ const val ADVERTISE_TX_POWER_MEDIUM = FwkAdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM /** * Advertise using high TX power level. This corresponds to largest visibility range of the * advertising packet. */ const val ADVERTISE_TX_POWER_HIGH = FwkAdvertiseSettings.ADVERTISE_TX_POWER_HIGH } val advertiseMode: Int /** Returns the advertise mode. */ get() = fwkInstance.mode val advertiseTxPowerLevel: Int /** Returns the TX power level for advertising. */ get() = fwkInstance.txPowerLevel val advertiseConnectable: Boolean /** Returns whether the advertisement will indicate connectable. */ get() = fwkInstance.isConnectable val advertiseTimeoutMillis: Int /** Returns the advertising time limit in milliseconds. */ get() = fwkInstance.timeout constructor( advertiseMode: Int = ADVERTISE_MODE_LOW_POWER, advertiseTxPowerLevel: Int = ADVERTISE_TX_POWER_MEDIUM, advertiseConnectable: Boolean = true, advertiseTimeoutMillis: Int = 0 ) : this(buildFwkAdvertiseSettings( advertiseMode, advertiseTxPowerLevel, advertiseConnectable, advertiseTimeoutMillis )) /** * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) override fun toBundle(): Bundle { val bundle = Bundle() bundle.putParcelable(keyForField(FIELD_FWK_ADVERTISE_SETTINGS), fwkInstance) return bundle } }
apache-2.0
c4598e718dcdda20cbbc9559c5cb7972
37.378378
99
0.650995
5.116216
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsImplItem.kt
2
5268
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import com.intellij.lang.ASTNode import com.intellij.navigation.ItemPresentation import com.intellij.psi.PsiElement import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.util.CachedValue import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.util.CachedValueImpl import org.rust.cargo.project.workspace.PackageOrigin import org.rust.ide.icons.RsIcons import org.rust.ide.presentation.getPresentation import org.rust.lang.core.macros.RsExpandedElement import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RsElementTypes.DEFAULT import org.rust.lang.core.psi.RsElementTypes.EXCL import org.rust.lang.core.resolve.RsCachedImplItem import org.rust.lang.core.resolve.knownItems import org.rust.lang.core.stubs.RsImplItemStub import org.rust.lang.core.types.BoundElement import org.rust.lang.core.types.RsPsiTypeImplUtil import org.rust.lang.core.types.normType import org.rust.lang.core.types.ty.* val RsImplItem.default: PsiElement? get() = node.findChildByType(DEFAULT)?.psi /** `impl !Sync for Bar` vs `impl Foo for Bar` */ val RsImplItem.isNegativeImpl: Boolean get() = greenStub?.isNegativeImpl ?: (node.findChildByType(EXCL) != null) val RsImplItem.isReservationImpl: Boolean get() = IMPL_ITEM_IS_RESERVATION_IMPL_PROP.getByPsi(this) val IMPL_ITEM_IS_RESERVATION_IMPL_PROP: StubbedAttributeProperty<RsImplItem, RsImplItemStub> = StubbedAttributeProperty({ it.hasAttribute("rustc_reservation_impl") }, RsImplItemStub::mayBeReservationImpl) val RsImplItem.implementingType: TyAdt? get() = typeReference?.normType as? TyAdt abstract class RsImplItemImplMixin : RsStubbedElementImpl<RsImplItemStub>, RsImplItem { constructor(node: ASTNode) : super(node) constructor(stub: RsImplItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override fun getIcon(flags: Int) = RsIcons.IMPL override val isPublic: Boolean get() = false // pub does not affect impls at all override fun getPresentation(): ItemPresentation = getPresentation(this) override fun getTextOffset(): Int = typeReference?.textOffset ?: impl.textOffset override val implementedTrait: BoundElement<RsTraitItem>? get() { val (trait, subst) = traitRef?.resolveToBoundTrait() ?: return null return BoundElement(trait, subst) } override val associatedTypesTransitively: Collection<RsTypeAlias> get() = CachedValuesManager.getCachedValue(this) { CachedValueProvider.Result.create( doGetAssociatedTypesTransitively(), rustStructureOrAnyPsiModificationTracker ) } private fun doGetAssociatedTypesTransitively(): List<RsTypeAlias> { val implAliases = expandedMembers.types val traitAliases = implementedTrait?.associatedTypesTransitively ?: emptyList() return implAliases + traitAliases.filter { trAl -> implAliases.find { it.name == trAl.name } == null } } override val declaredType: Ty get() = RsPsiTypeImplUtil.declaredType(this) override val isUnsafe: Boolean get() = unsafe != null override fun getContext(): PsiElement? = RsExpandedElement.getContextImpl(this) val cachedImplItem: CachedValue<RsCachedImplItem> = CachedValueImpl { val cachedImpl = RsCachedImplItem(this) val modTracker = if (cachedImpl.containingCrate?.origin == PackageOrigin.WORKSPACE) { project.rustStructureModificationTracker } else { project.rustPsiManager.rustStructureModificationTrackerInDependencies } CachedValueProvider.Result(cachedImpl, modTracker) } } // https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules fun checkOrphanRules(impl: RsImplItem, isSameCrate: (RsElement) -> Boolean): Boolean { val traitRef = impl.traitRef ?: return true val (trait, subst, _) = traitRef.resolveToBoundTrait() ?: return true if (isSameCrate(trait)) return true val typeParameters = subst.typeSubst.values + (impl.typeReference?.normType ?: return true) return typeParameters.any { tyWrapped -> val ty = tyWrapped.unwrapFundamentalTypes() ty is TyUnknown // `impl ForeignTrait<LocalStruct> for ForeignStruct` || ty is TyAdt && isSameCrate(ty.item) // `impl ForeignTrait for Box<dyn LocalTrait>` || ty is TyTraitObject && ty.baseTrait.let { it == null || isSameCrate(it) } // `impl<T> ForeignTrait for Box<T>` in stdlib || tyWrapped is TyAdt && isSameCrate(tyWrapped.item) } // TODO uncovering } // https://doc.rust-lang.org/reference/glossary.html#fundamental-type-constructors private fun Ty.unwrapFundamentalTypes(): Ty { when (this) { // &T -> T // &mut T -> T is TyReference -> return referenced // Box<T> -> T // Pin<T> -> T is TyAdt -> { if (item == item.knownItems.Box || item == item.knownItems.Pin) { return typeArguments.firstOrNull() ?: this } } } return this }
mit
a901e89d0fdb0dfe680420bbc785eb3f
39.523077
113
0.714503
4.234727
false
false
false
false
androidx/androidx
compose/material3/material3/src/androidAndroidTest/kotlin/androidx/compose/material3/ColorSchemeTest.kt
3
5165
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3 import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) class ColorSchemeTest { @get:Rule val rule = createComposeRule() /** * Test for switching between provided [ColorScheme]s, ensuring that the existing colors objects * are preserved. (b/182635582) */ @Test fun switchingBetweenColors() { val lightColors = lightColorScheme() val darkColors = darkColorScheme() val colorSchemeState = mutableStateOf(lightColors) var currentColorScheme: ColorScheme? = null rule.setContent { MaterialTheme(colorSchemeState.value) { Button(onReadColorScheme = { currentColorScheme = it }) } } rule.runOnIdle { // Initial colors should never be touched assertThat(lightColors.contentEquals(lightColorScheme())).isTrue() assertThat(darkColors.contentEquals(darkColorScheme())).isTrue() // Current colors should be light assertThat(currentColorScheme!!.contentEquals(lightColors)).isTrue() // Change current colors to dark colorSchemeState.value = darkColors } rule.runOnIdle { // Initial colors should never be touched assertThat(lightColors.contentEquals(lightColorScheme())).isTrue() assertThat(darkColors.contentEquals(darkColorScheme())).isTrue() // Current colors should be dark assertThat(currentColorScheme!!.contentEquals(darkColors)).isTrue() // Change current colors back to light colorSchemeState.value = lightColors } rule.runOnIdle { // Initial colors should never be touched assertThat(lightColors.contentEquals(lightColorScheme())).isTrue() assertThat(darkColors.contentEquals(darkColorScheme())).isTrue() // Current colors should be light assertThat(currentColorScheme!!.contentEquals(lightColors)).isTrue() } } @Composable private fun Button(onReadColorScheme: (ColorScheme) -> Unit) { val colorScheme = MaterialTheme.colorScheme onReadColorScheme(colorScheme) } } /** * [ColorScheme] is @Stable, so by contract it doesn't have equals implemented. And since it creates a * new Colors object to mutate internally, we can't compare references. Instead we compare the * properties to make sure that the properties are equal. * * @return true if all the properties inside [this] are equal to those in [other], false otherwise. */ private fun ColorScheme.contentEquals(other: ColorScheme): Boolean { if (primary != other.primary) return false if (onPrimary != other.onPrimary) return false if (primaryContainer != other.primaryContainer) return false if (onPrimaryContainer != other.onPrimaryContainer) return false if (inversePrimary != other.inversePrimary) return false if (secondary != other.secondary) return false if (onSecondary != other.onSecondary) return false if (secondaryContainer != other.secondaryContainer) return false if (onSecondaryContainer != other.onSecondaryContainer) return false if (tertiary != other.tertiary) return false if (onTertiary != other.onTertiary) return false if (tertiaryContainer != other.tertiaryContainer) return false if (onTertiaryContainer != other.onTertiaryContainer) return false if (background != other.background) return false if (onBackground != other.onBackground) return false if (surface != other.surface) return false if (onSurface != other.onSurface) return false if (surfaceVariant != other.surfaceVariant) return false if (onSurfaceVariant != other.onSurfaceVariant) return false if (inverseSurface != other.inverseSurface) return false if (inverseOnSurface != other.inverseOnSurface) return false if (error != other.error) return false if (onError != other.onError) return false if (errorContainer != other.errorContainer) return false if (onErrorContainer != other.onErrorContainer) return false if (outline != other.outline) return false return true }
apache-2.0
b916aaa16536cb55537ce789f73b22b7
40.99187
102
0.708616
4.985521
false
true
false
false
codebutler/odyssey
retrograde-metadata-ovgdb/src/main/java/com/codebutler/retrograde/metadata/ovgdb/OvgdbMetadataProvider.kt
1
6118
/* * OvgdbMetadataProvider.kt * * Copyright (C) 2017 Retrograde Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.codebutler.retrograde.metadata.ovgdb import com.codebutler.retrograde.common.rx.toSingleAsOptional import com.codebutler.retrograde.lib.library.GameSystem import com.codebutler.retrograde.lib.library.db.entity.Game import com.codebutler.retrograde.lib.library.metadata.GameMetadataProvider import com.codebutler.retrograde.lib.storage.StorageFile import com.codebutler.retrograde.metadata.ovgdb.db.OvgdbDatabase import com.codebutler.retrograde.metadata.ovgdb.db.OvgdbManager import com.codebutler.retrograde.metadata.ovgdb.db.entity.OvgdbRelease import com.gojuno.koptional.None import com.gojuno.koptional.Optional import com.gojuno.koptional.Some import com.gojuno.koptional.toOptional import io.reactivex.Maybe import io.reactivex.ObservableTransformer import io.reactivex.Single import timber.log.Timber class OvgdbMetadataProvider(private val ovgdbManager: OvgdbManager) : GameMetadataProvider { override fun transformer(startedAtMs: Long) = ObservableTransformer<StorageFile, Optional<Game>> { upstream -> ovgdbManager.dbReady .flatMapObservable { ovgdb: OvgdbDatabase -> upstream .flatMapSingle { file -> when (file.crc) { null -> Maybe.empty() else -> ovgdb.romDao().findByCRC(file.crc!!) }.switchIfEmpty(ovgdb.romDao().findByFileName(sanitizeRomFileName(file.name))) .toSingleAsOptional() .map { rom -> Pair(file, rom) } } .doOnNext { (file, rom) -> Timber.d("Rom Found: ${file.name} ${rom is Some}") } .flatMapSingle { (file, rom) -> when (rom) { is Some -> ovgdb.releaseDao().findByRomId(rom.value.id) .toSingleAsOptional() else -> Single.just<Optional<OvgdbRelease>>(None) }.map { release -> Triple(file, rom, release) } } .doOnNext { (file, _, release) -> Timber.d("Release found: ${file.name}, ${release is Some}") } .flatMapSingle { (file, rom, release) -> when (rom) { is Some -> ovgdb.systemDao().findById(rom.value.systemId) .toSingleAsOptional() else -> Single.just(None) }.map { ovgdbSystem -> Triple(file, release, ovgdbSystem) } } .doOnNext { (file, _, ovgdbSystem) -> Timber.d("OVGDB System Found: ${file.name}, ${ovgdbSystem is Some}") } .map { (file, release, ovgdbSystem) -> var system = when (ovgdbSystem) { is Some -> { val gs = GameSystem.findByShortName(ovgdbSystem.value.shortName) if (gs == null) { Timber.e("System '${ovgdbSystem.value.shortName}' not found") } gs } else -> null } if (system == null) { Timber.d("System not found, trying file extension: ${file.name}") system = GameSystem.findByFileExtension(file.extension) } if (system == null) { Timber.d("Giving up on ${file.name}") } else { Timber.d("Found system!! $system") } Triple(file, release, system.toOptional()) } .map { (file, release, system) -> when (system) { is Some -> Game( fileName = file.name, fileUri = file.uri, title = release.toNullable()?.titleName ?: file.name, systemId = system.value.id, developer = release.toNullable()?.developer, coverFrontUrl = release.toNullable()?.coverFront, lastIndexedAt = startedAtMs ).toOptional() else -> None } } } } private fun sanitizeRomFileName(fileName: String): String { return fileName .replace("(U)", "(USA)") .replace("(J)", "(Japan)") .replace(" [!]", "") .replace(Regex("\\.v64$"), ".n64") .replace(Regex("\\.z64$"), ".n64") } }
gpl-3.0
f647c6e5e97bc636b240ae50861a882b
49.561983
114
0.474828
5.283247
false
false
false
false
codehz/container
app/src/main/java/one/codehz/container/models/RunningAppHeaderModel.kt
1
444
package one.codehz.container.models class RunningAppHeaderModel(val uid: Int, val name: String) : RunningAppBaseModel(true) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as RunningAppHeaderModel if (uid != other.uid) return false return true } override fun hashCode(): Int { return uid } }
gpl-3.0
f74f4b0af8d5b7296476167937fd9626
23.722222
89
0.63964
4.352941
false
false
false
false
codehz/container
app/src/main/java/one/codehz/container/behavior/BottomNavigationBehavior.kt
1
3254
package one.codehz.container.behavior import android.content.Context import android.graphics.Rect import android.support.design.widget.AppBarLayout import android.support.design.widget.BottomNavigationView import android.support.design.widget.CoordinatorLayout import android.support.design.widget.Snackbar import android.support.v4.view.WindowInsetsCompat import android.util.AttributeSet import android.util.Log import android.view.Gravity import android.view.View import one.codehz.container.MainActivity @Suppress("unused") class BottomNavigationBehavior(context: Context, val attrs: AttributeSet) : CoordinatorLayout.Behavior<BottomNavigationView>(context, attrs) { override fun onApplyWindowInsets(coordinatorLayout: CoordinatorLayout?, child: BottomNavigationView?, insets: WindowInsetsCompat): WindowInsetsCompat { Log.d("BMB", insets.toString()) return super.onApplyWindowInsets(coordinatorLayout, child, insets) } fun adjustSnackBarLayout(dependency: Snackbar.SnackbarLayout, child: BottomNavigationView) = dependency.apply { setPadding(paddingLeft, paddingTop, paddingRight, (child.height - child.translationY).toInt()) } override fun layoutDependsOn(parent: CoordinatorLayout?, child: BottomNavigationView, dependency: View): Boolean { if ((dependency.context as? MainActivity)?.isTransition ?: false) return false return when (dependency) { is AppBarLayout -> true is Snackbar.SnackbarLayout -> { adjustSnackBarLayout(dependency, child) true } else -> super.layoutDependsOn(parent, child, dependency) } } var modified = false override fun onDependentViewChanged(parent: CoordinatorLayout?, child: BottomNavigationView, dependency: View): Boolean { if ((dependency.context as? MainActivity)?.isTransition ?: false) return false return when (dependency) { is AppBarLayout -> { val value = child.context.resources.getDimensionPixelSize(child.context.resources.getIdentifier("status_bar_height", "dimen", "android")) - dependency.y child.translationY = value / dependency.height * child.height modified = true true } is Snackbar.SnackbarLayout -> { if (modified) adjustSnackBarLayout(dependency, child) modified = false true } else -> false } } override fun onAttachedToLayoutParams(params: CoordinatorLayout.LayoutParams) { params.insetEdge = Gravity.BOTTOM super.onAttachedToLayoutParams(params) } override fun getInsetDodgeRect(parent: CoordinatorLayout, child: BottomNavigationView, rect: Rect): Boolean { Log.d("BMB", "Inset Doge Rect $rect") return super.getInsetDodgeRect(parent, child, rect) } override fun onRequestChildRectangleOnScreen(coordinatorLayout: CoordinatorLayout?, child: BottomNavigationView?, rectangle: Rect?, immediate: Boolean): Boolean { Log.d("BMB", rectangle.toString()) return super.onRequestChildRectangleOnScreen(coordinatorLayout, child, rectangle, immediate) } }
gpl-3.0
3e74a4634a584ddb43922959493e3fac
44.208333
212
0.703749
5.256866
false
false
false
false
CruGlobal/android-gto-support
gto-support-androidx-recyclerview/src/main/kotlin/org/ccci/gto/android/common/androidx/recyclerview/adapter/SimpleDataBindingAdapter.kt
2
857
package org.ccci.gto.android.common.androidx.recyclerview.adapter import androidx.databinding.ViewDataBinding import androidx.lifecycle.LifecycleOwner abstract class SimpleDataBindingAdapter<B : ViewDataBinding>(lifecycleOwner: LifecycleOwner? = null) : AbstractDataBindingAdapter<B, DataBindingViewHolder<B>>(lifecycleOwner) { final override fun onCreateViewHolder(binding: B, viewType: Int) = DataBindingViewHolder(binding) final override fun onBindViewHolder(holder: DataBindingViewHolder<B>, binding: B, position: Int) = onBindViewDataBinding(binding, position) final override fun onViewRecycled(holder: DataBindingViewHolder<B>, binding: B) = onViewDataBindingRecycled(binding) protected abstract fun onBindViewDataBinding(binding: B, position: Int) protected open fun onViewDataBindingRecycled(binding: B) = Unit }
mit
4a043414f19063758cd0a8dc9bf1aa1c
52.5625
120
0.803967
4.982558
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/translator/works/TranslatorWorksPresenter.kt
2
2353
package ru.fantlab.android.ui.modules.translator.works import io.reactivex.Single import io.reactivex.functions.Consumer import ru.fantlab.android.data.dao.model.Translator import ru.fantlab.android.data.dao.response.TranslatorResponse import ru.fantlab.android.provider.rest.DataManager import ru.fantlab.android.provider.rest.TranslationsSortOption import ru.fantlab.android.provider.rest.getTranslatorInformationPath import ru.fantlab.android.provider.storage.DbProvider import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter class TranslatorWorksPresenter : BasePresenter<TranslatorWorksMvp.View>(), TranslatorWorksMvp.Presenter { private var sort: TranslationsSortOption = TranslationsSortOption.BY_YEAR private var translator: Int = -1 override fun getTranslatorWorks(translatorId: Int) { translator = translatorId makeRestCall( retrieveTranslatorInfoInternal(translatorId).toObservable(), Consumer { translated -> sendToView { it.onTranslatorInformationRetrieved(translated) } } ) } private fun retrieveTranslatorInfoInternal(translatorId: Int) = retrieveTranslatorInfoFromServer(translatorId) .onErrorResumeNext { retrieveTranslatorInfoFromDb(translatorId) } private fun retrieveTranslatorInfoFromServer(translatorId: Int): Single<HashMap<String, Translator.TranslatedWork>> = DataManager.getTranslatorInformation(translatorId, showTranslated = true) .map { getTranslatorWorks(it) } private fun retrieveTranslatorInfoFromDb(translatorId: Int): Single<HashMap<String, Translator.TranslatedWork>> = DbProvider.mainDatabase .responseDao() .get(getTranslatorInformationPath(translatorId)) .map { it.response } .map { TranslatorResponse.Deserializer().deserialize(it) } .map { getTranslatorWorks(it) } private fun getTranslatorWorks(response: TranslatorResponse): HashMap<String, Translator.TranslatedWork> = response.translatedWorks override fun setCurrentSort(sortBy: TranslationsSortOption) { sort = sortBy getTranslatorWorks(translator) } override fun getCurrentSort() = sort }
gpl-3.0
fde743cb483a2ce66009274dacac6766
42.592593
121
0.714407
5.359909
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/messages/dto/MessagesChatSettingsPhoto.kt
1
2257
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * 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. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.messages.dto import com.google.gson.annotations.SerializedName import kotlin.Boolean import kotlin.String /** * @param photo50 - URL of the preview image with 50px in width * @param photo100 - URL of the preview image with 100px in width * @param photo200 - URL of the preview image with 200px in width * @param isDefaultPhoto - If provided photo is default * @param isDefaultCallPhoto - If provided photo is default call photo */ data class MessagesChatSettingsPhoto( @SerializedName("photo_50") val photo50: String? = null, @SerializedName("photo_100") val photo100: String? = null, @SerializedName("photo_200") val photo200: String? = null, @SerializedName("is_default_photo") val isDefaultPhoto: Boolean? = null, @SerializedName("is_default_call_photo") val isDefaultCallPhoto: Boolean? = null )
mit
5f26044fc6a21b2ed1cb897820d5bd76
42.403846
81
0.695614
4.442913
false
false
false
false
ohmae/DmsExplorer
mobile/src/main/java/net/mm2d/dmsexplorer/domain/AppRepository.kt
1
2992
/* * Copyright (c) 2017 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer.domain import android.app.Application import android.content.Context import io.reactivex.Completable import io.reactivex.schedulers.Schedulers import net.mm2d.android.upnp.avt.MediaRenderer import net.mm2d.android.upnp.cds.MediaServer import net.mm2d.dmsexplorer.Repository import net.mm2d.dmsexplorer.domain.entity.ContentEntity import net.mm2d.dmsexplorer.domain.formatter.CdsFormatter import net.mm2d.dmsexplorer.domain.model.* import net.mm2d.dmsexplorer.domain.tabs.CustomTabsBinder import net.mm2d.dmsexplorer.domain.tabs.CustomTabsHelper import net.mm2d.dmsexplorer.settings.Settings /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ class AppRepository(application: Application) : Repository() { private val context: Context = application override val controlPointModel: ControlPointModel = ControlPointModel(context, this::updateMediaServer, this::updateMediaRenderer) override val themeModel: ThemeModelImpl = ThemeModelImpl() override val openUriModel: OpenUriCustomTabsModel get() { field.setUseCustomTabs(Settings.get().useCustomTabs()) return field } override var mediaServerModel: MediaServerModel? = null private set override var mediaRendererModel: MediaRendererModel? = null private set override var playbackTargetModel: PlaybackTargetModel? = null private set init { Completable.fromAction { CdsFormatter.initialize(application) } .subscribeOn(Schedulers.io()) .subscribe() val helper = CustomTabsHelper(context) openUriModel = OpenUriCustomTabsModel(helper, themeModel) application.registerActivityLifecycleCallbacks(CustomTabsBinder(helper)) application.registerActivityLifecycleCallbacks(themeModel) } private fun updateMediaServer(server: MediaServer?) { mediaServerModel?.terminate() mediaServerModel = null if (server != null) { mediaServerModel = createMediaServerModel(server).also { it.initialize() } } } private fun updateMediaRenderer(renderer: MediaRenderer?) { mediaRendererModel?.terminate() mediaRendererModel = null if (renderer != null) { mediaRendererModel = createMediaRendererModel(renderer) } } private fun createMediaServerModel(server: MediaServer): MediaServerModel = MediaServerModel(context, server, this::updatePlaybackTarget) private fun createMediaRendererModel(renderer: MediaRenderer): MediaRendererModel = MediaRendererModel(context, renderer) private fun updatePlaybackTarget(entity: ContentEntity?) { playbackTargetModel = if (entity != null) PlaybackTargetModel(entity) else null } }
mit
4a3810a3f14a4f9afe70e2d2d2f40663
35.740741
87
0.725806
4.613953
false
false
false
false
inorichi/tachiyomi-extensions
src/pt/muitomanga/src/eu/kanade/tachiyomi/extension/pt/muitomanga/MuitoManga.kt
1
9009
package eu.kanade.tachiyomi.extension.pt.muitomanga import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import okhttp3.Headers import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.Interceptor import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Protocol import okhttp3.Request import okhttp3.Response import okhttp3.ResponseBody.Companion.toResponseBody import org.jsoup.nodes.Document import org.jsoup.nodes.Element import uy.kohesive.injekt.injectLazy import java.text.ParseException import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit import kotlin.math.ceil @Nsfw class MuitoManga : ParsedHttpSource() { override val name = "Muito Mangá" override val baseUrl = "https://muitomanga.com" override val lang = "pt-BR" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient.newBuilder() .addInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS)) .addInterceptor(::directoryCacheIntercept) .build() override fun headersBuilder(): Headers.Builder = Headers.Builder() .add("Accept", ACCEPT) .add("Accept-Language", ACCEPT_LANGUAGE) .add("Referer", "$baseUrl/") private val json: Json by injectLazy() private val directoryCache: MutableMap<Int, String> = mutableMapOf() override fun popularMangaRequest(page: Int): Request { val newHeaders = headersBuilder() .set("Accept", ACCEPT_JSON) .set("Referer", "$baseUrl/lista-de-mangas") .add("X-Page", page.toString()) .add("X-Requested-With", "XMLHttpRequest") .build() return GET("$baseUrl/lib/diretorio.json?pagina=1&tipo_pag=$DIRECTORY_TYPE_POPULAR&pega_busca=", newHeaders) } override fun popularMangaParse(response: Response): MangasPage { val directory = json.decodeFromString<MuitoMangaDirectoryDto>(response.body!!.string()) val totalPages = ceil(directory.results.size.toDouble() / ITEMS_PER_PAGE) val currentPage = response.request.header("X-Page")!!.toInt() val mangaList = directory.results .drop(ITEMS_PER_PAGE * (currentPage - 1)) .take(ITEMS_PER_PAGE) .map(::popularMangaFromObject) return MangasPage(mangaList, hasNextPage = currentPage < totalPages) } private fun popularMangaFromObject(manga: MuitoMangaTitleDto): SManga = SManga.create().apply { title = manga.title thumbnail_url = manga.image url = "/manga/" + manga.url } override fun latestUpdatesRequest(page: Int): Request { val newHeaders = headersBuilder() .set("Accept", ACCEPT_JSON) .set("Referer", "$baseUrl/lista-de-mangas/mais-vistos") .add("X-Page", page.toString()) .add("X-Requested-With", "XMLHttpRequest") .build() return GET("$baseUrl/lib/diretorio.json?pagina=1&tipo_pag=$DIRECTORY_TYPE_LATEST&pega_busca=", newHeaders) } override fun latestUpdatesParse(response: Response): MangasPage = popularMangaParse(response) override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val url = "$baseUrl/buscar".toHttpUrlOrNull()!!.newBuilder() .addQueryParameter("q", query) return GET(url.toString(), headers) } override fun searchMangaSelector() = "div.content_post div.anime" override fun searchMangaFromElement(element: Element): SManga = SManga.create().apply { title = element.select("h3 a").first()!!.text() thumbnail_url = element.select("div.capaMangaBusca img").first()!!.attr("src") setUrlWithoutDomain(element.select("a").first()!!.attr("abs:href")) } override fun searchMangaNextPageSelector(): String? = null override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply { val infoElement = document.select("div.content_post").first()!! title = document.select("div.content div.widget-title h1").first()!!.text() author = infoElement.select("span.series_autor2").first()!!.text() genre = infoElement.select("ul.lancamento-list a").joinToString { it.text() } description = document.select("ul.lancamento-list ~ p").text().trim() thumbnail_url = infoElement.select("div.capaMangaInfo img").first()!!.attr("data-src") } override fun chapterListSelector() = "div.manga-chapters div.single-chapter" override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply { name = element.select("a").first()!!.text() date_upload = element.select("small[title]").first()!!.text().toDate() scanlator = element.select("scanlator2 a").joinToString { it.text().trim() } setUrlWithoutDomain(element.select("a").first()!!.attr("abs:href")) } override fun pageListParse(document: Document): List<Page> { return document.select("script:containsData(imagens_cap)").first()!! .data() .substringAfter("[") .substringBefore("]") .split(",") .mapIndexed { i, imageUrl -> val fixedImageUrl = imageUrl .replace("\"", "") .replace("\\/", "/") Page(i, document.location(), fixedImageUrl) } } override fun imageUrlParse(document: Document) = "" override fun imageRequest(page: Page): Request { val newHeaders = headersBuilder() .set("Accept", ACCEPT_IMAGE) .set("Referer", page.url) .build() return GET(page.imageUrl!!, newHeaders) } override fun popularMangaSelector(): String = throw UnsupportedOperationException("Not used") override fun popularMangaFromElement(element: Element): SManga = throw UnsupportedOperationException("Not used") override fun popularMangaNextPageSelector(): String = throw UnsupportedOperationException("Not used") override fun latestUpdatesSelector(): String = throw UnsupportedOperationException("Not used") override fun latestUpdatesFromElement(element: Element): SManga = throw UnsupportedOperationException("Not used") override fun latestUpdatesNextPageSelector(): String = throw UnsupportedOperationException("Not used") private fun directoryCacheIntercept(chain: Interceptor.Chain): Response { if (!chain.request().url.toString().contains("diretorio.json")) { return chain.proceed(chain.request()) } val directoryType = chain.request().url.queryParameter("tipo_pag")!!.toInt() if (directoryCache.containsKey(directoryType)) { val jsonContentType = "application/json; charset=UTF-8".toMediaTypeOrNull() val responseBody = directoryCache[directoryType]!!.toResponseBody(jsonContentType) return Response.Builder() .code(200) .protocol(Protocol.HTTP_1_1) .request(chain.request()) .message("OK") .body(responseBody) .build() } val response = chain.proceed(chain.request()) val responseContentType = response.body!!.contentType() val responseString = response.body!!.string() directoryCache[directoryType] = responseString return response.newBuilder() .body(responseString.toResponseBody(responseContentType)) .build() } private fun String.toDate(): Long { return try { DATE_FORMATTER.parse(this)?.time ?: 0L } catch (e: ParseException) { 0L } } companion object { private const val ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9," + "image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" private const val ACCEPT_IMAGE = "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8" private const val ACCEPT_JSON = "application/json, text/javascript, */*; q=0.01" private const val ACCEPT_LANGUAGE = "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7,es;q=0.6,gl;q=0.5" private const val ITEMS_PER_PAGE = 21 private const val DIRECTORY_TYPE_POPULAR = 5 private const val DIRECTORY_TYPE_LATEST = 6 private val DATE_FORMATTER by lazy { SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH) } } }
apache-2.0
0d1d070c45aba776104d60eeb61254c1
38.682819
117
0.665964
4.454995
false
false
false
false
geckour/Glyph
app/src/main/java/jp/org/example/geckour/glyph/ui/model/Result.kt
1
1066
package jp.org.example.geckour.glyph.ui.model import android.graphics.Bitmap import se.ansman.kotshi.JsonSerializable @JsonSerializable data class Result( val details: List<ResultDetail>, val count: Long ) { fun calcHackBonus(): Int { val c = when (details.size) { 1 -> 38 2 -> 60 3 -> 85 4 -> 120 5 -> 162 else -> 0 } val correctRate = details.count { it.correct }.toFloat() / details.size return Math.round(c * correctRate) } fun calcSpeedBonus(allowableTime: Long): Int = if (details.count { it.correct } == details.size) { Math.round( (allowableTime - details.map { it.spentTime }.sum()) * 100.0 / allowableTime ).toInt() } else 0 } @JsonSerializable data class ResultDetail( val id: Long, var name: String?, val correct: Boolean, val spentTime: Long, var bitmap: Bitmap? )
gpl-2.0
4f9a8c470fd9686bb32455f0142b7b7c
25.02439
84
0.526266
4.281124
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryDefaultNamespaceDeclPsiImpl.kt
1
2745
/* * Copyright (C) 2016, 2018-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.util.elementType import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.xdm.types.XdmNamespaceNode.Companion.EMPTY_PREFIX import uk.co.reecedunn.intellij.plugin.xdm.types.XdmNode import uk.co.reecedunn.intellij.plugin.xdm.types.XsAnyUriValue import uk.co.reecedunn.intellij.plugin.xdm.types.XsNCNameValue import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XdmNamespaceType import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryDefaultNamespaceDecl import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQueryTokenType import xqt.platform.intellij.xpath.XPathTokenProvider class XQueryDefaultNamespaceDeclPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XQueryDefaultNamespaceDecl, XpmSyntaxValidationElement { // region XdmNamespaceNode override val namespacePrefix: XsNCNameValue = EMPTY_PREFIX override val namespaceUri: XsAnyUriValue? get() = children().filterIsInstance<XsAnyUriValue>().firstOrNull() override val parentNode: XdmNode? = null // endregion // region XpmDefaultNamespaceDeclaration override fun accepts(namespaceType: XdmNamespaceType): Boolean = when (conformanceElement.elementType) { XPathTokenProvider.KElement -> when (namespaceType) { XdmNamespaceType.DefaultElement, XdmNamespaceType.DefaultType -> true else -> false } XPathTokenProvider.KFunction -> when (namespaceType) { XdmNamespaceType.DefaultFunctionDecl, XdmNamespaceType.DefaultFunctionRef -> true else -> false } else -> false } // endregion // region XpmSyntaxValidationElement override val conformanceElement: PsiElement get() = findChildByType(XQueryTokenType.DEFAULT_NAMESPACE_TOKENS) ?: firstChild // endregion }
apache-2.0
8176cfef7430ffb0300461cd53e73a29
39.367647
108
0.765392
4.5
false
false
false
false
HabitRPG/habitica-android
wearos/src/main/java/com/habitrpg/wearos/habitica/ui/viewmodels/TaskResultViewModel.kt
1
1292
package com.habitrpg.wearos.habitica.ui.viewmodels import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.asLiveData import com.habitrpg.shared.habitica.models.responses.TaskScoringResult import com.habitrpg.wearos.habitica.data.repositories.TaskRepository import com.habitrpg.wearos.habitica.data.repositories.UserRepository import com.habitrpg.wearos.habitica.managers.AppStateManager import com.habitrpg.wearos.habitica.util.ExceptionHandlerBuilder import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class TaskResultViewModel @Inject constructor( savedStateHandle: SavedStateHandle, taskRepository: TaskRepository, userRepository: UserRepository, exceptionBuilder: ExceptionHandlerBuilder, appStateManager: AppStateManager ) : BaseViewModel(userRepository, taskRepository, exceptionBuilder, appStateManager) { val user = userRepository.getUser().asLiveData() val hasLeveledUp: Boolean get() = result?.hasLeveledUp == true val hasDied: Boolean get() = result?.hasDied == true val hasDrop: Boolean get() { return result?.drop?.key?.isNotBlank() == true // || (result?.questItemsFound ?: 0) > 0 } val result = savedStateHandle.get<TaskScoringResult>("result") }
gpl-3.0
8e7b19958bae52b850fa63ac1d5814f3
42.066667
99
0.784056
4.785185
false
false
false
false
grueni75/GeoDiscoverer
Source/Platform/Target/Android/wear/src/main/java/com/untouchableapps/android/geodiscoverer/Dialog.kt
1
7732
//============================================================================ // Name : Dialog // Author : Matthias Gruenewald // Copyright : Copyright 2010-2022 Matthias Gruenewald // // This file is part of GeoDiscoverer. // // GeoDiscoverer 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. // // GeoDiscoverer 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 GeoDiscoverer. If not, see <http://www.gnu.org/licenses/>. // //============================================================================ package com.untouchableapps.android.geodiscoverer import android.Manifest import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.Settings import android.view.WindowManager import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.wear.ambient.AmbientModeSupport import androidx.wear.compose.material.* import com.untouchableapps.android.geodiscoverer.theme.WearAppTheme import com.untouchableapps.android.geodiscoverer.core.GDAppInterface import android.transition.Explode import android.transition.Fade import android.view.Window import androidx.compose.foundation.Image import androidx.compose.ui.res.painterResource class Dialog : ComponentActivity() { // Identifiers for extras object Extras { const val TEXT = "com.untouchableapps.android.geodiscoverer.dialog.TEXT" const val MAX = "com.untouchableapps.android.geodiscoverer.dialog.MAX" const val PROGRESS = "com.untouchableapps.android.geodiscoverer.dialog.PROGRESS" const val KIND = "com.untouchableapps.android.geodiscoverer.dialog.KIND" const val CLOSE = "com.untouchableapps.android.geodiscoverer.dialog.CLOSE" const val GET_PERMISSIONS = "com.untouchableapps.android.geodiscoverer.dialog.GET_PERMISSIONS" } // Identifiers for dialogs object Types { const val FATAL = 0 const val ERROR = 2 const val WARNING = 1 const val INFO = 3 } // UI state inner class ViewModel() : androidx.lifecycle.ViewModel() { var kind: Int by mutableStateOf(-1) var message: String by mutableStateOf("") var progressMax: Int by mutableStateOf(-1) var progressCurrent: Int by mutableStateOf(0) } val viewModel = ViewModel() // Called when the activity is created override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Prevent animation when closed window.setWindowAnimations(0) // Set the content viewModel.message=getString(R.string.permission_instructions) setContent{ content() } // Check which type is requested onNewIntent(intent); } // Checks for a new intent override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) // Message update? if (intent.hasExtra(Extras.TEXT)) { viewModel.message=intent.getStringExtra(Extras.TEXT)!! viewModel.progressMax=-1 viewModel.kind=-1 } // Shall permissions be granted? if (intent.hasExtra(Extras.GET_PERMISSIONS)) { // Request the permissions GDApplication.addMessage(GDAppInterface.DEBUG_MSG, "GDApp", "Requesting general permissions") requestPermissions( arrayOf( Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.VIBRATE, ), 0 ) if (!Settings.canDrawOverlays(applicationContext)) { GDApplication.addMessage(GDAppInterface.DEBUG_MSG, "GDApp", "Requesting overlay permission") GDApplication.showMessageBar( applicationContext, resources.getString(R.string.overlay_instructions), GDApplication.MESSAGE_BAR_DURATION_LONG ) val packageName = applicationContext.packageName val t = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName")) startActivity(t) } } // Max value for progress dialog? if (intent.hasExtra(Extras.MAX)) { viewModel.progressMax = intent.getIntExtra(Extras.MAX, 0) viewModel.progressCurrent = 0 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } // Progress update? if (intent.hasExtra(Extras.PROGRESS)) { viewModel.progressCurrent = intent.getIntExtra(Extras.PROGRESS, 0) } // Dialog with button? if (intent.hasExtra(Extras.KIND)) { viewModel.kind = intent.getIntExtra(Extras.KIND, -1) } // Shall we close? if (intent.hasExtra(Extras.CLOSE)) { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); finish() } } // Displays the permission request content @Composable fun content() { WearAppTheme { Box( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colors.background), ) { if (viewModel.progressMax != -1) { if (viewModel.progressMax == 0) { CircularProgressIndicator( modifier = Modifier .fillMaxSize(), strokeWidth = 10.dp ) } else { CircularProgressIndicator( modifier = Modifier .fillMaxSize(), progress = viewModel.progressCurrent.toFloat() / viewModel.progressMax.toFloat(), strokeWidth = 10.dp ) } } Column( modifier = Modifier .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { if ((viewModel.kind == Types.FATAL) || (viewModel.kind == Types.ERROR)) { Icon( imageVector = Icons.Default.Warning, contentDescription = null, ) } else { Image( modifier = Modifier .size(60.dp), painter = painterResource(R.mipmap.ic_launcher_foreground), contentDescription = null ) } if (viewModel.message != "") { Text( modifier = Modifier .fillMaxWidth() .padding(20.dp), textAlign = TextAlign.Center, fontSize = 20.sp, text = viewModel.message ) } if ((viewModel.kind == Types.ERROR) || (viewModel.kind == Types.FATAL)) { Button( onClick = { finish() if (viewModel.kind == Types.FATAL) { System.exit(1) } } ) { Icon( imageVector = Icons.Default.Done, contentDescription = null, ) } } } } } } }
gpl-3.0
e107b8187614c5714424dc66b3aea1b5
31.902128
100
0.641102
4.572442
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/step_quiz_fill_blanks/ui/adapter/delegate/FillBlanksItemSelectAdapterDelegate.kt
2
4794
package org.stepik.android.view.step_quiz_fill_blanks.ui.adapter.delegate import android.content.Context import android.graphics.drawable.Drawable import android.graphics.drawable.LayerDrawable import android.util.DisplayMetrics import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.ArrayAdapter import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.annotation.IdRes import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.widget.ListPopupWindow import androidx.core.graphics.drawable.DrawableCompat import kotlinx.android.synthetic.main.item_step_quiz_fill_blanks_select.view.* import org.stepic.droid.R import org.stepik.android.view.step_quiz_choice.ui.delegate.LayerListDrawableDelegate import org.stepik.android.view.step_quiz_fill_blanks.ui.model.FillBlanksItem import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder class FillBlanksItemSelectAdapterDelegate( private val onItemClicked: (Int, String) -> Unit ) : AdapterDelegate<FillBlanksItem, DelegateViewHolder<FillBlanksItem>>() { override fun isForViewType(position: Int, data: FillBlanksItem): Boolean = data is FillBlanksItem.Select override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<FillBlanksItem> = ViewHolder(createView(parent, R.layout.item_step_quiz_fill_blanks_select)) private inner class ViewHolder(root: View) : DelegateViewHolder<FillBlanksItem>(root) { private val stepQuizFillBlanksText = root.stepQuizFillBlanksText private val layerListDrawableDelegate: LayerListDrawableDelegate init { stepQuizFillBlanksText.setOnClickListener(::showOptions) layerListDrawableDelegate = LayerListDrawableDelegate( listOf( R.id.checked_layer, R.id.correct_layer, R.id.incorrect_layer ), stepQuizFillBlanksText.background.mutate() as LayerDrawable ) } override fun onBind(data: FillBlanksItem) { data as FillBlanksItem.Select itemView.isEnabled = data.isEnabled stepQuizFillBlanksText.text = data.text val (@IdRes layer, @DrawableRes statusIconRes, @ColorRes arrowColorRes) = when (data.correct) { true -> Triple(R.id.correct_layer, R.drawable.ic_step_quiz_correct, R.color.color_correct_arrow_down) false -> Triple(R.id.incorrect_layer, R.drawable.ic_step_quiz_wrong, R.color.color_wrong_arrow_down) else -> Triple(R.id.checked_layer, null, R.color.color_enabled_arrow_down) } layerListDrawableDelegate.showLayer(layer) val iconDrawable = statusIconRes?.let { AppCompatResources.getDrawable(context, it) } val arrowDrawable = prepareArrowIcon(arrowColorRes) stepQuizFillBlanksText.setCompoundDrawablesWithIntrinsicBounds(iconDrawable, null, arrowDrawable, null) } private fun prepareArrowIcon(arrowColorRes: Int): Drawable? = AppCompatResources .getDrawable(context, R.drawable.ic_arrow_bottom) ?.let(DrawableCompat::wrap) ?.let(Drawable::mutate) ?.also { DrawableCompat.setTintList(it, AppCompatResources.getColorStateList(context, arrowColorRes)) } private fun showOptions(view: View) { val options = (itemData as? FillBlanksItem.Select) ?.options ?: return val popupWindow = ListPopupWindow(context) popupWindow.setAdapter(ArrayAdapter(context, R.layout.item_fill_blanks_select_spinner, options)) popupWindow.setOnItemClickListener { _, _, position, _ -> val text = options[position] onItemClicked(adapterPosition, text) popupWindow.dismiss() } popupWindow.anchorView = view val displayMetrics = DisplayMetrics() val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager windowManager.defaultDisplay.getMetrics(displayMetrics) val calculatedWidth = displayMetrics.widthPixels - context.resources.getDimensionPixelSize(R.dimen.step_quiz_fill_blanks_select_popup_margin) popupWindow.width = minOf(calculatedWidth, context.resources.getDimensionPixelSize(R.dimen.step_quiz_fill_blanks_select_popup_max_width)) popupWindow.height = WindowManager.LayoutParams.WRAP_CONTENT popupWindow.show() } } }
apache-2.0
320e03c9e4d0e12037fedd71ecfcf226
45.105769
153
0.69441
4.99375
false
false
false
false
dhleong/ideavim
src/com/maddyhome/idea/vim/action/motion/updown/MotionGotoLineFirstAction.kt
1
2543
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.action.motion.updown import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.action.MotionEditorAction import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.MappingMode import com.maddyhome.idea.vim.handler.MotionActionHandler import java.util.* import javax.swing.KeyStroke class MotionGotoLineFirstAction : MotionEditorAction() { override val mappingModes: Set<MappingMode> = MappingMode.NVO override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("gg", "<C-Home>") override val flags: EnumSet<CommandFlags> = EnumSet.of(CommandFlags.FLAG_MOT_LINEWISE, CommandFlags.FLAG_SAVE_JUMP) override fun makeActionHandler(): MotionActionHandler = MotionGotoLineFirstActionHandler } class MotionGotoLineFirstInsertAction : MotionEditorAction() { override val mappingModes: Set<MappingMode> = MappingMode.I override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("<C-Home>") override val flags: EnumSet<CommandFlags> = EnumSet.of(CommandFlags.FLAG_CLEAR_STROKES) override fun makeActionHandler(): MotionActionHandler = MotionGotoLineFirstActionHandler } private object MotionGotoLineFirstActionHandler : MotionActionHandler.ForEachCaret() { override fun getOffset(editor: Editor, caret: Caret, context: DataContext, count: Int, rawCount: Int, argument: Argument?): Int { return VimPlugin.getMotion().moveCaretGotoLineFirst(editor, count - 1) } }
gpl-2.0
98ae83d8e0543d74941e48f536f8ba82
40.016129
117
0.750688
4.469244
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/network/NetworkHelper.kt
1
5027
package eu.kanade.tachiyomi.network import android.content.Context import android.os.Build import exh.log.maybeInjectEHLogger import okhttp3.* import java.io.File import java.io.IOException import java.net.InetAddress import java.net.Socket import java.net.UnknownHostException import java.security.KeyManagementException import java.security.KeyStore import java.security.NoSuchAlgorithmException import javax.net.ssl.* open class NetworkHelper(context: Context) { private val cacheDir = File(context.cacheDir, "network_cache") private val cacheSize = 5L * 1024 * 1024 // 5 MiB open val cookieManager = AndroidCookieJar(context) open val client = OkHttpClient.Builder() .cookieJar(cookieManager) .cache(Cache(cacheDir, cacheSize)) .enableTLS12() .maybeInjectEHLogger() .build() open val cloudflareClient = client.newBuilder() .addInterceptor(CloudflareInterceptor(context)) .maybeInjectEHLogger() .build() private fun OkHttpClient.Builder.enableTLS12(): OkHttpClient.Builder { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { return this } val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) trustManagerFactory.init(null as KeyStore?) val trustManagers = trustManagerFactory.trustManagers if (trustManagers.size == 1 && trustManagers[0] is X509TrustManager) { class TLSSocketFactory @Throws(KeyManagementException::class, NoSuchAlgorithmException::class) constructor() : SSLSocketFactory() { private val internalSSLSocketFactory: SSLSocketFactory init { val context = SSLContext.getInstance("TLS") context.init(null, null, null) internalSSLSocketFactory = context.socketFactory } override fun getDefaultCipherSuites(): Array<String> { return internalSSLSocketFactory.defaultCipherSuites } override fun getSupportedCipherSuites(): Array<String> { return internalSSLSocketFactory.supportedCipherSuites } @Throws(IOException::class) override fun createSocket(): Socket? { return enableTLSOnSocket(internalSSLSocketFactory.createSocket()) } @Throws(IOException::class) override fun createSocket(s: Socket, host: String, port: Int, autoClose: Boolean): Socket? { return enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose)) } @Throws(IOException::class, UnknownHostException::class) override fun createSocket(host: String, port: Int): Socket? { return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port)) } @Throws(IOException::class, UnknownHostException::class) override fun createSocket(host: String, port: Int, localHost: InetAddress, localPort: Int): Socket? { return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort)) } @Throws(IOException::class) override fun createSocket(host: InetAddress, port: Int): Socket? { return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port)) } @Throws(IOException::class) override fun createSocket(address: InetAddress, port: Int, localAddress: InetAddress, localPort: Int): Socket? { return enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort)) } private fun enableTLSOnSocket(socket: Socket?): Socket? { if (socket != null && socket is SSLSocket) { socket.enabledProtocols = socket.supportedProtocols } return socket } } sslSocketFactory(TLSSocketFactory(), trustManagers[0] as X509TrustManager) } val specCompat = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0) .cipherSuites( *ConnectionSpec.MODERN_TLS.cipherSuites().orEmpty().toTypedArray(), CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ) .build() val specs = listOf(specCompat, ConnectionSpec.CLEARTEXT) connectionSpecs(specs) return this } }
apache-2.0
7a019b3ed2d93cb3b3c69f3ff21f0c9d
39.891667
128
0.609708
5.39957
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupRestorer.kt
1
7015
package eu.kanade.tachiyomi.data.backup import android.content.Context import android.net.Uri import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.backup.models.BackupCategory import eu.kanade.tachiyomi.data.backup.models.BackupHistory import eu.kanade.tachiyomi.data.backup.models.BackupManga import eu.kanade.tachiyomi.data.backup.models.BackupSerializer import eu.kanade.tachiyomi.data.backup.models.BackupSource import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.util.system.createFileInCacheDir import kotlinx.coroutines.Job import okio.buffer import okio.gzip import okio.source import java.io.File import java.text.SimpleDateFormat import java.util.Date import java.util.Locale class BackupRestorer( private val context: Context, private val notifier: BackupNotifier, ) { var job: Job? = null private var backupManager = BackupManager(context) private var restoreAmount = 0 private var restoreProgress = 0 /** * Mapping of source ID to source name from backup data */ private var sourceMapping: Map<Long, String> = emptyMap() private val errors = mutableListOf<Pair<Date, String>>() suspend fun restoreBackup(uri: Uri): Boolean { val startTime = System.currentTimeMillis() restoreProgress = 0 errors.clear() if (!performRestore(uri)) { return false } val endTime = System.currentTimeMillis() val time = endTime - startTime val logFile = writeErrorLog() notifier.showRestoreComplete(time, errors.size, logFile.parent, logFile.name) return true } fun writeErrorLog(): File { try { if (errors.isNotEmpty()) { val file = context.createFileInCacheDir("tachiyomi_restore.txt") val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault()) file.bufferedWriter().use { out -> errors.forEach { (date, message) -> out.write("[${sdf.format(date)}] $message\n") } } return file } } catch (e: Exception) { // Empty } return File("") } @Suppress("BlockingMethodInNonBlockingContext") private suspend fun performRestore(uri: Uri): Boolean { val backupString = context.contentResolver.openInputStream(uri)!!.source().gzip().buffer().use { it.readByteArray() } val backup = backupManager.parser.decodeFromByteArray(BackupSerializer, backupString) restoreAmount = backup.backupManga.size + 1 // +1 for categories // Restore categories if (backup.backupCategories.isNotEmpty()) { restoreCategories(backup.backupCategories) } // Store source mapping for error messages val backupMaps = backup.backupBrokenSources.map { BackupSource(it.name, it.sourceId) } + backup.backupSources sourceMapping = backupMaps.associate { it.sourceId to it.name } // Restore individual manga backup.backupManga.forEach { if (job?.isActive != true) { return false } restoreManga(it, backup.backupCategories) } // TODO: optionally trigger online library + tracker update return true } private suspend fun restoreCategories(backupCategories: List<BackupCategory>) { backupManager.restoreCategories(backupCategories) restoreProgress += 1 showRestoreProgress(restoreProgress, restoreAmount, context.getString(R.string.categories)) } private suspend fun restoreManga(backupManga: BackupManga, backupCategories: List<BackupCategory>) { val manga = backupManga.getMangaImpl() val chapters = backupManga.getChaptersImpl() val categories = backupManga.categories.map { it.toInt() } val history = backupManga.brokenHistory.map { BackupHistory(it.url, it.lastRead, it.readDuration) } + backupManga.history val tracks = backupManga.getTrackingImpl() try { val dbManga = backupManager.getMangaFromDatabase(manga.url, manga.source) if (dbManga == null) { // Manga not in database restoreExistingManga(manga, chapters, categories, history, tracks, backupCategories) } else { // Manga in database // Copy information from manga already in database backupManager.restoreExistingManga(manga, dbManga) // Fetch rest of manga information restoreNewManga(manga, chapters, categories, history, tracks, backupCategories) } } catch (e: Exception) { val sourceName = sourceMapping[manga.source] ?: manga.source.toString() errors.add(Date() to "${manga.title} [$sourceName]: ${e.message}") } restoreProgress += 1 showRestoreProgress(restoreProgress, restoreAmount, manga.title) } /** * Fetches manga information * * @param manga manga that needs updating * @param chapters chapters of manga that needs updating * @param categories categories that need updating */ private suspend fun restoreExistingManga( manga: Manga, chapters: List<Chapter>, categories: List<Int>, history: List<BackupHistory>, tracks: List<Track>, backupCategories: List<BackupCategory>, ) { val fetchedManga = backupManager.restoreNewManga(manga) fetchedManga.id ?: return backupManager.restoreChapters(fetchedManga, chapters) restoreExtras(fetchedManga, categories, history, tracks, backupCategories) } private suspend fun restoreNewManga( backupManga: Manga, chapters: List<Chapter>, categories: List<Int>, history: List<BackupHistory>, tracks: List<Track>, backupCategories: List<BackupCategory>, ) { backupManager.restoreChapters(backupManga, chapters) restoreExtras(backupManga, categories, history, tracks, backupCategories) } private suspend fun restoreExtras(manga: Manga, categories: List<Int>, history: List<BackupHistory>, tracks: List<Track>, backupCategories: List<BackupCategory>) { backupManager.restoreCategories(manga, categories, backupCategories) backupManager.restoreHistory(history) backupManager.restoreTracking(manga, tracks) } /** * Called to update dialog in [BackupConst] * * @param progress restore progress * @param amount total restoreAmount of manga * @param title title of restored manga */ private fun showRestoreProgress(progress: Int, amount: Int, title: String) { notifier.showRestoreProgress(title, progress, amount) } }
apache-2.0
0495921563f478f3cc7d2f45767a47d5
34.790816
167
0.660727
4.888502
false
false
false
false
SirLYC/Android-Gank-Share
app/src/main/java/com/lyc/gank/discover/DiscoverViewModel.kt
1
2114
package com.lyc.gank.discover import android.arch.lifecycle.ViewModel import com.lyc.data.category.CategoryRepository import com.lyc.data.resp.async import com.lyc.gank.utils.* import io.reactivex.disposables.CompositeDisposable /** * Created by Liu Yuchuan on 2018/2/23. */ class DiscoverViewModel : ViewModel() { val discoverList = ObservableList<Any>(mutableListOf()) val refreshEvent = NonNullSingleLiveEvent<RefreshState>(RefreshState.Empty) val refreshState = NonNullLiveData<RefreshState>(RefreshState.Empty) private val compositeDisposable = CompositeDisposable() private var categoryRepository = CategoryRepository(TYPE) companion object { private const val TYPE = "瞎推荐" } init { refreshState.observeForever { refreshEvent.value = it!! } } fun refresh() { refreshState.value.refresh()?.let { nextState -> if (NetworkStateReceiver.isNetWorkConnected()) { refreshState.value = nextState doRefresh() } else { refreshState.value = RefreshState.Error("没有网络连接") } } } private fun doRefresh() { categoryRepository.getItems(1) .async() .subscribe({ itemList -> if (itemList.isNotEmpty()) { discoverList.clear() discoverList.addAll(itemList) } assertState(refreshState.value is RefreshState.Refreshing, "${refreshState.value}") refreshState.value.result(discoverList.isEmpty())?.let { refreshState.value = it } }, { loge("SingleContentViewModel", "", it) refreshState.value.error("获取推荐失败")?.let(refreshState::setValue) }) .also { compositeDisposable.add(it) } } override fun onCleared() { compositeDisposable.dispose() super.onCleared() } }
apache-2.0
dd0450de00637da655f187832ba81074
29.202899
103
0.577735
5.082927
false
false
false
false
Heiner1/AndroidAPS
automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt
1
2010
package info.nightscout.androidaps.plugins.general.automation.actions import dagger.android.HasAndroidInjector import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.UserEntry import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.transactions.CancelCurrentTemporaryTargetIfAnyTransaction import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.shared.logging.LTag import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import javax.inject.Inject class ActionStopTempTarget(injector: HasAndroidInjector) : Action(injector) { @Inject lateinit var repository: AppRepository @Inject lateinit var dateUtil: DateUtil @Inject lateinit var uel: UserEntryLogger private val disposable = CompositeDisposable() override fun friendlyName(): Int = R.string.stoptemptarget override fun shortDescription(): String = rh.gs(R.string.stoptemptarget) override fun icon(): Int = R.drawable.ic_stop_24dp override fun doAction(callback: Callback) { disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(dateUtil.now())) .subscribe({ result -> uel.log(UserEntry.Action.CANCEL_TT, Sources.Automation, title) result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } }, { aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) }) callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok)).run() } override fun isValid(): Boolean = true }
agpl-3.0
5b24b2e34ca4395b19c5738641f1eecb
46.880952
118
0.755224
4.843373
false
false
false
false
sjnyag/stamp
app/src/main/java/com/sjn/stamp/ui/item/DateHeaderItem.kt
1
1743
package com.sjn.stamp.ui.item import android.view.View import com.sjn.stamp.R import com.sjn.stamp.ui.item.holder.HeaderViewHolder import com.sjn.stamp.utils.TimeHelper import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractHeaderItem import eu.davidea.flexibleadapter.items.IFilterable import java.util.* class DateHeaderItem(date: Date) : AbstractHeaderItem<HeaderViewHolder>(), IFilterable { val date = TimeHelper.toDateOnly(date) val title = TimeHelper.toDateTime(date).toLocalDate().toString() init { isDraggable = false } override fun equals(other: Any?): Boolean { if (other is DateHeaderItem) { val inItem = other as DateHeaderItem? return this.date == inItem!!.date } return false } override fun hashCode(): Int = date.hashCode() override fun getLayoutRes(): Int = R.layout.recycler_header_item override fun createViewHolder(view: View, adapter: FlexibleAdapter<*>): HeaderViewHolder = HeaderViewHolder(view, adapter) override fun bindViewHolder(adapter: FlexibleAdapter<*>, holder: HeaderViewHolder, position: Int, payloads: List<*>) { holder.title.text = title holder.subtitle.text = holder.title.context.run { adapter.getSectionItems(this@DateHeaderItem).run { if (isEmpty()) getString(R.string.item_date_header_empty) else getString(R.string.item_date_header_item_counts, size.toString()) } } } override fun filter(constraint: String): Boolean = title.toLowerCase().trim { it <= ' ' }.contains(constraint) fun isDateOf(recordedAt: Date): Boolean = TimeHelper.toDateOnly(recordedAt).compareTo(date) == 0 }
apache-2.0
2a2a9aa5eed0d8d32ea523811d83c71e
36.106383
144
0.703959
4.303704
false
false
false
false
orbite-mobile/monastic-jerusalem-community
app/src/main/java/pl/orbitemobile/wspolnoty/activities/contact/ContactPresenter.kt
1
1239
/* * Copyright (c) 2017. All Rights Reserved. Michal Jankowski orbitemobile.pl */ package pl.orbitemobile.wspolnoty.activities.contact import android.content.Intent import android.net.Uri import io.reactivex.disposables.CompositeDisposable import pl.orbitemobile.wspolnoty.R class ContactPresenter(override var disposable: CompositeDisposable? = null, override var view: ContactContract.View? = null) : ContactContract.Presenter { override fun onViewAttached() {} override fun onPhoneClick() { val callIntent = Intent(Intent.ACTION_DIAL) callIntent.data = Uri.parse("tel:" + view?.context?.getString(R.string.contact_phone)) view?.context?.startActivity(callIntent) } override fun onMailClick() { val intent = Intent(Intent.ACTION_SENDTO, Uri.fromParts( "mailto", view?.context?.getString(R.string.contact_mail), null)) view?.context?.startActivity(Intent.createChooser(intent, "Choose an Email client :")) } override fun onWebsiteClick() { val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("http://" + view?.context?.getString(R.string.contact_web))) view?.context?.startActivity(browserIntent) } }
agpl-3.0
bd74f52de90fb585293f234251e761b6
36.545455
125
0.701372
4.362676
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/Utils.kt
2
1413
// 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.formatter import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings fun PsiFile.commitAndUnblockDocument(): Boolean { val virtualFile = this.virtualFile ?: return false val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: return false val documentManager = PsiDocumentManager.getInstance(project) documentManager.doPostponedOperationsAndUnblockDocument(document) documentManager.commitDocument(document) return true } fun PsiFile.adjustLineIndent(startOffset: Int, endOffset: Int) { if (!commitAndUnblockDocument()) return CodeStyleManager.getInstance(project).adjustLineIndent(this, TextRange(startOffset, endOffset)) } fun trailingCommaAllowedInModule(source: PsiElement): Boolean { return source.module ?.languageVersionSettings ?.supportsFeature(LanguageFeature.TrailingCommas) == true }
apache-2.0
16d7283a3ef3c194559b2db69106746c
41.818182
120
0.811748
5.02847
false
false
false
false
Jakeler/UT61E-Toolkit
Application/src/main/java/jk/ut61eTool/Alarms.kt
1
2431
package jk.ut61eTool import android.app.NotificationChannel import android.app.NotificationManager import android.os.Build import android.util.Log import androidx.core.app.NotificationCompat import java.util.* /** * Created by jan on 23.12.17. */ class Alarms(var activity: LogActivity) { val CHANNEL_ID = "alarm" @JvmField var samples = 0 var samples_ol = 0 @JvmField var condition: String? = null @JvmField var enabled = false @JvmField var vibration = false @JvmField var low_limit = 0.0 @JvmField var high_limit = 0.0 init { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = activity.getString(R.string.alarm_channel_name) // Register the channel with the system val channel = NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT) channel.description = activity.getString(R.string.alarm_channel_name) activity.mNotifyMgr.createNotificationChannel(channel) } } fun isAlarm(value: Double): Boolean { if (!enabled) { return false } when (condition) { "both" -> if (value > high_limit || value < low_limit) samples_ol++ "above" -> if (value > high_limit) samples_ol++ "below" -> if (value < low_limit) samples_ol++ } return if (samples > 0 && samples_ol >= samples) { samples_ol = 0 true } else { false } } fun alarm(value: String) { Log.d("ALARM", "alarm: $value") val mBuilder = NotificationCompat.Builder(activity, CHANNEL_ID) mBuilder.setContentTitle("Alarm triggered!") val i = Arrays.asList(*activity.resources.getStringArray(R.array.alarm_condition_values)).indexOf(condition) mBuilder.setContentText(activity.resources.getStringArray(R.array.alarm_conditions)[i].toString() + ": " + value) mBuilder.setSmallIcon(R.drawable.ic_error_outline_black_24dp) mBuilder.setAutoCancel(true) mBuilder.priority = NotificationCompat.PRIORITY_DEFAULT if (vibration) mBuilder.setVibrate(longArrayOf(0, 500, 500)) activity.mNotifyMgr.notify(0, mBuilder.build()) } }
apache-2.0
7e770f26e04796a0d36cf45164065fa2
32.777778
121
0.637186
4.220486
false
false
false
false
NCBSinfo/NCBSinfo
app/src/main/java/com/rohitsuratekar/NCBSinfo/models/Trip.kt
1
2060
package com.rohitsuratekar.NCBSinfo.models import android.util.Log import com.rohitsuratekar.NCBSinfo.common.Constants import java.text.ParseException import java.text.SimpleDateFormat import java.util.* class Trip(private var tripString: String, private var dayIndex: Int, private var cal: Calendar) { fun displayTime(): String { val inputFormat = SimpleDateFormat(Constants.FORMAT_TRIP_LIST, Locale.ENGLISH) val outputFormat = SimpleDateFormat(Constants.FORMAT_DISPLAY_TIME, Locale.ENGLISH) val returnCal = Calendar.getInstance().apply { timeInMillis = cal.timeInMillis } val tempCal = Calendar.getInstance() try { tempCal.timeInMillis = inputFormat.parse(tripString)?.time!! } catch (e: ParseException) { Log.e("Trip", "Message : ${e.localizedMessage}") return "--:--" } returnCal.set(Calendar.HOUR_OF_DAY, tempCal.get(Calendar.HOUR_OF_DAY)) returnCal.set(Calendar.MINUTE, tempCal.get(Calendar.MINUTE)) return outputFormat.format(Date(returnCal.timeInMillis)) } fun raw(): String { return tripString } fun tripHighlightDay(): Int { val tempCal = Calendar.getInstance().apply { cal.timeInMillis } when (dayIndex) { -1 -> { tempCal.add(Calendar.DATE, -1) } 0 -> { } 1 -> { } else -> { tempCal.add(Calendar.DATE, dayIndex-1) } } return tempCal.get(Calendar.DAY_OF_WEEK) } fun tripCalender(): Calendar { val tempCal = Calendar.getInstance().apply { cal.timeInMillis } when (dayIndex) { -1 -> { tempCal.add(Calendar.DATE, -1) } 0 -> { } 1 -> { } else -> { tempCal.add(Calendar.DATE, dayIndex-1) } } return tempCal } }
mit
68535b6f20e844fb1f3ca96c73319881
30.21875
98
0.548058
4.458874
false
false
false
false
zephir-lang/idea-plugin
src/main/kotlin/com/zephir/lang/core/ZephirLanguage.kt
1
967
// Copyright (c) 2014-2020 Zephir Team // // This source file is subject the MIT license, that is bundled with // this package in the file LICENSE, and is available through the // world-wide-web at the following url: // // https://github.com/zephir-lang/idea-plugin/blob/master/LICENSE package com.zephir.lang.core import com.intellij.lang.Language import com.intellij.openapi.fileTypes.LanguageFileType import com.zephir.ide.icons.ZephirIcons object ZephirLanguage : Language("Zephir", "text/zephir", "text/x-zephir", "application/x-zephir") { /** Zephir is case sensitive language */ override fun isCaseSensitive(): Boolean { return true } } object ZephirFileType : LanguageFileType(ZephirLanguage) { private const val EXTENSION = "zep" override fun getIcon() = ZephirIcons.FILE override fun getName() = language.id override fun getDefaultExtension() = EXTENSION override fun getDescription() = "Zephir language file" }
mit
ad757224bab12c30c1ec08af48e1b49e
32.344828
100
0.737332
3.762646
false
false
false
false
LittleLightCz/SheepsGoHome
core/src/com/sheepsgohome/steerable/SteerableBody.kt
1
2141
package com.sheepsgohome.steerable import com.badlogic.gdx.ai.steer.Steerable import com.badlogic.gdx.ai.steer.SteeringAcceleration import com.badlogic.gdx.ai.steer.behaviors.PrioritySteering import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.physics.box2d.Body open class SteerableBody(val body: Body) : Steerable<Vector2> { private val boundingRadius = 1f private var speed = 10f private var angularSpeed = 10f private var tagged = false private val steeringBehaviour = PrioritySteering(this).apply { isEnabled = true } protected var steeringAcceleration = SteeringAcceleration(Vector2()) open fun calculateSteeringBehaviour() { steeringBehaviour.calculateSteering(steeringAcceleration) body.linearVelocity = steeringAcceleration.linear } override fun getPosition(): Vector2 = body.position override fun getOrientation() = body.angle override fun getLinearVelocity(): Vector2 = body.linearVelocity override fun getAngularVelocity() = body.angularVelocity override fun getBoundingRadius() = boundingRadius override fun isTagged() = tagged override fun setTagged(tagged: Boolean) { this.tagged = tagged } override fun newVector() = Vector2() override fun vectorToAngle(vector: Vector2) = vector.angle() override fun angleToVector(outVector: Vector2, angle: Float): Vector2 { outVector.x = -Math.sin(angle.toDouble()).toFloat() outVector.y = Math.cos(angle.toDouble()).toFloat() return outVector } override fun getMaxLinearSpeed() = speed override fun setMaxLinearSpeed(maxLinearSpeed: Float) { speed = maxLinearSpeed } override fun getMaxLinearAcceleration() = speed override fun setMaxLinearAcceleration(maxLinearAcceleration: Float) {} override fun getMaxAngularSpeed() = angularSpeed override fun setMaxAngularSpeed(maxAngularSpeed: Float) { angularSpeed = maxAngularSpeed } override fun getMaxAngularAcceleration() = angularSpeed override fun setMaxAngularAcceleration(maxAngularAcceleration: Float) {} }
gpl-3.0
7f1f7038d77608c545c4a9d703fe19cc
27.932432
76
0.732368
4.360489
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceRangeToWithUntilInspection.kt
1
5128
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeInsight.hints.RangeKtExpressionType import org.jetbrains.kotlin.idea.codeInsight.hints.RangeKtExpressionType.* import org.jetbrains.kotlin.idea.intentions.getArguments import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.nj2k.isPossibleToUseRangeUntil import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.isDouble import org.jetbrains.kotlin.types.typeUtil.isFloat import org.jetbrains.kotlin.types.typeUtil.isPrimitiveNumberType sealed class AbstractReplaceRangeToWithRangeUntilInspection : AbstractRangeInspection() { override fun visitRange(range: KtExpression, context: Lazy<BindingContext>, type: RangeKtExpressionType, holder: ProblemsHolder) { when (type) { UNTIL, RANGE_UNTIL, DOWN_TO -> return RANGE_TO -> Unit } val useRangeUntil = range.isPossibleToUseRangeUntil(context) if (useRangeUntil xor (this is ReplaceRangeToWithRangeUntilInspection)) return if (!isApplicable(range, context, useRangeUntil)) return val desc = if (useRangeUntil) KotlinBundle.message("inspection.replace.range.to.with.rangeUntil.display.name") else KotlinBundle.message("inspection.replace.range.to.with.until.display.name") holder.registerProblem(range, desc, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, ReplaceWithUntilQuickFix(useRangeUntil)) } private class ReplaceWithUntilQuickFix(private val useRangeUntil: Boolean) : LocalQuickFix { override fun getName(): String = if (useRangeUntil) KotlinBundle.message("replace.with.rangeUntil.quick.fix.text") else KotlinBundle.message("replace.with.until.quick.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as KtExpression applyFix(element, useRangeUntil) } } companion object { fun applyFixIfApplicable(expression: KtExpression) { val context = lazy { expression.analyze(BodyResolveMode.PARTIAL_NO_ADDITIONAL) } val useRangeUntil = expression.isPossibleToUseRangeUntil(context) if (isApplicable(expression, context, useRangeUntil)) { applyFix(expression, useRangeUntil) } } private fun isApplicable(expression: KtExpression, context: Lazy<BindingContext>, useRangeUntil: Boolean): Boolean { val (left, right) = expression.getArguments() ?: return false // `until` isn't available for floating point numbers fun KtExpression.isRangeUntilOrUntilApplicable() = getType(context.value) ?.let { it.isPrimitiveNumberType() && (useRangeUntil || !it.isDouble() && !it.isFloat()) } return right?.deparenthesize()?.isMinusOne() == true && left?.isRangeUntilOrUntilApplicable() == true && right.isRangeUntilOrUntilApplicable() == true } private fun applyFix(element: KtExpression, useRangeUntil: Boolean) { val args = element.getArguments() ?: return val operator = if (useRangeUntil) "..<" else " until " element.replace( KtPsiFactory(element).createExpressionByPattern( "$0$operator$1", args.first ?: return, (args.second?.deparenthesize() as? KtBinaryExpression)?.left ?: return ) ) } private fun KtExpression.isMinusOne(): Boolean { if (this !is KtBinaryExpression) return false if (operationToken != KtTokens.MINUS) return false val constantValue = right?.constantValueOrNull() val rightValue = (constantValue?.value as? Number)?.toInt() ?: return false return rightValue == 1 } } } /** * Tests: [org.jetbrains.kotlin.idea.inspections.LocalInspectionTestGenerated.ReplaceRangeToWithUntil] */ class ReplaceRangeToWithUntilInspection : AbstractReplaceRangeToWithRangeUntilInspection() /** * Tests: [org.jetbrains.kotlin.idea.inspections.LocalInspectionTestGenerated.ReplaceRangeToWithRangeUntil] */ class ReplaceRangeToWithRangeUntilInspection : AbstractReplaceRangeToWithRangeUntilInspection() private fun KtExpression.deparenthesize() = KtPsiUtil.safeDeparenthesize(this)
apache-2.0
bd4a9f8d6f883e0dd94484ee6f619fa8
48.307692
134
0.717434
4.945034
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateEqualsAndHashcodeAction.kt
1
15115
// 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.actions.generate import com.intellij.codeInsight.CodeInsightSettings import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.util.IncorrectOperationException import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.insertMembersAfterAndReformat import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.kotlin.utils.addToStdlib.lastIsInstanceOrNull fun ClassDescriptor.findDeclaredEquals(checkSupers: Boolean): FunctionDescriptor? { return findDeclaredFunction("equals", checkSupers) { it.modality != Modality.ABSTRACT && it.valueParameters.singleOrNull()?.type == it.builtIns.nullableAnyType && it.typeParameters.isEmpty() } } fun ClassDescriptor.findDeclaredHashCode(checkSupers: Boolean): FunctionDescriptor? { return findDeclaredFunction("hashCode", checkSupers) { it.modality != Modality.ABSTRACT && it.valueParameters.isEmpty() && it.typeParameters.isEmpty() } } class KotlinGenerateEqualsAndHashcodeAction : KotlinGenerateMemberActionBase<KotlinGenerateEqualsAndHashcodeAction.Info>() { companion object { private val LOG = Logger.getInstance(KotlinGenerateEqualsAndHashcodeAction::class.java) } class Info( val needEquals: Boolean, val needHashCode: Boolean, val classDescriptor: ClassDescriptor, val variablesForEquals: List<VariableDescriptor>, val variablesForHashCode: List<VariableDescriptor> ) override fun isValidForClass(targetClass: KtClassOrObject): Boolean { return targetClass is KtClass && targetClass !is KtEnumEntry && !targetClass.isEnum() && !targetClass.isAnnotation() && !targetClass.isInterface() } override fun prepareMembersInfo(klass: KtClassOrObject, project: Project, editor: Editor?): Info? { if (klass !is KtClass) throw AssertionError("Not a class: ${klass.getElementTextWithContext()}") val context = klass.analyzeWithContent() val classDescriptor = context.get(BindingContext.CLASS, klass) ?: return null val equalsDescriptor = classDescriptor.findDeclaredEquals(false) val hashCodeDescriptor = classDescriptor.findDeclaredHashCode(false) var needEquals = equalsDescriptor == null var needHashCode = hashCodeDescriptor == null if (!needEquals && !needHashCode) { if (!confirmMemberRewrite(klass, equalsDescriptor!!, hashCodeDescriptor!!)) return null runWriteAction { try { equalsDescriptor.source.getPsi()?.delete() hashCodeDescriptor.source.getPsi()?.delete() needEquals = true needHashCode = true } catch (e: IncorrectOperationException) { LOG.error(e) } } } val properties = getPropertiesToUseInGeneratedMember(klass) if (properties.isEmpty() || isUnitTestMode()) { val descriptors = properties.map { context[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as VariableDescriptor } return Info(needEquals, needHashCode, classDescriptor, descriptors, descriptors) } return with(KotlinGenerateEqualsWizard(project, klass, properties, needEquals, needHashCode)) { if (!klass.hasExpectModifier() && !showAndGet()) return null Info(needEquals, needHashCode, classDescriptor, getPropertiesForEquals().map { context[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as VariableDescriptor }, getPropertiesForHashCode().map { context[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as VariableDescriptor }) } } private fun generateClassLiteralsNotEqual(paramName: String, targetClass: KtClassOrObject): String { val defaultExpression = "javaClass != $paramName?.javaClass" if (!targetClass.languageVersionSettings.supportsFeature(LanguageFeature.BoundCallableReferences)) return defaultExpression return when { targetClass.platform.isJs() -> "other == null || this::class.js != $paramName::class.js" targetClass.platform.isCommon() -> "other == null || this::class != $paramName::class" else -> defaultExpression } } private fun generateClassLiteral(targetClass: KtClassOrObject): String { val defaultExpression = "javaClass" if (!targetClass.languageVersionSettings.supportsFeature(LanguageFeature.BoundCallableReferences)) return defaultExpression return when { targetClass.platform.isJs() -> "this::class.js" targetClass.platform.isCommon() -> "this::class" else -> defaultExpression } } private fun isNestedArray(variable: VariableDescriptor) = KotlinBuiltIns.isArrayOrPrimitiveArray(variable.builtIns.getArrayElementType(variable.type)) private fun KtElement.canUseArrayContentFunctions() = languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_1 private fun generateArraysEqualsCall( variable: VariableDescriptor, canUseContentFunctions: Boolean, arg1: String, arg2: String ): String { return if (canUseContentFunctions) { val methodName = if (isNestedArray(variable)) "contentDeepEquals" else "contentEquals" "$arg1.$methodName($arg2)" } else { val methodName = if (isNestedArray(variable)) "deepEquals" else "equals" "java.util.Arrays.$methodName($arg1, $arg2)" } } private fun generateArrayHashCodeCall( variable: VariableDescriptor, canUseContentFunctions: Boolean, argument: String ): String { return if (canUseContentFunctions) { val methodName = if (isNestedArray(variable)) "contentDeepHashCode" else "contentHashCode" val dot = if (TypeUtils.isNullableType(variable.type)) "?." else "." "$argument$dot$methodName()" } else { val methodName = if (isNestedArray(variable)) "deepHashCode" else "hashCode" "java.util.Arrays.$methodName($argument)" } } private fun generateEquals(project: Project, info: Info, targetClass: KtClassOrObject): KtNamedFunction? { with(info) { if (!needEquals) return null val superEquals = classDescriptor.getSuperClassOrAny().findDeclaredEquals(true)!! val equalsFun = generateFunctionSkeleton(superEquals, targetClass) val paramName = equalsFun.valueParameters.first().name!!.quoteIfNeeded() var typeForCast = IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(classDescriptor) val typeParams = classDescriptor.declaredTypeParameters if (typeParams.isNotEmpty()) { typeForCast += typeParams.joinToString(prefix = "<", postfix = ">") { "*" } } val useIsCheck = CodeInsightSettings.getInstance().USE_INSTANCEOF_ON_EQUALS_PARAMETER val isNotInstanceCondition = if (useIsCheck) { "$paramName !is $typeForCast" } else { generateClassLiteralsNotEqual(paramName, targetClass) } val bodyText = buildString { append("if (this === $paramName) return true\n") append("if ($isNotInstanceCondition) return false\n") val builtIns = superEquals.builtIns if (!builtIns.isMemberOfAny(superEquals)) { append("if (!super.equals($paramName)) return false\n") } if (variablesForEquals.isNotEmpty()) { if (!useIsCheck) { append("\n$paramName as $typeForCast\n") } append('\n') variablesForEquals.forEach { val isNullable = TypeUtils.isNullableType(it.type) val isArray = KotlinBuiltIns.isArrayOrPrimitiveArray(it.type) val canUseArrayContentFunctions = targetClass.canUseArrayContentFunctions() val propName = (DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) as PsiNameIdentifierOwner).nameIdentifier!!.text val notEquals = when { isArray -> { "!${generateArraysEqualsCall(it, canUseArrayContentFunctions, propName, "$paramName.$propName")}" } else -> { "$propName != $paramName.$propName" } } val equalsCheck = "if ($notEquals) return false\n" if (isArray && isNullable && canUseArrayContentFunctions) { append("if ($propName != null) {\n") append("if ($paramName.$propName == null) return false\n") append(equalsCheck) append("} else if ($paramName.$propName != null) return false\n") } else { append(equalsCheck) } } append('\n') } append("return true") } equalsFun.replaceBody { KtPsiFactory(project).createBlock(bodyText) } return equalsFun } } private fun generateHashCode(project: Project, info: Info, targetClass: KtClassOrObject): KtNamedFunction? { fun VariableDescriptor.genVariableHashCode(parenthesesNeeded: Boolean): String { val ref = (DescriptorToSourceUtilsIde.getAnyDeclaration(project, this) as PsiNameIdentifierOwner).nameIdentifier!!.text val isNullable = TypeUtils.isNullableType(type) val builtIns = builtIns val typeClass = type.constructor.declarationDescriptor var text = when { typeClass == builtIns.byte || typeClass == builtIns.short || typeClass == builtIns.int -> ref KotlinBuiltIns.isArrayOrPrimitiveArray(type) -> { val canUseArrayContentFunctions = targetClass.canUseArrayContentFunctions() val shouldWrapInLet = isNullable && !canUseArrayContentFunctions val hashCodeArg = if (shouldWrapInLet) "it" else ref val hashCodeCall = generateArrayHashCodeCall(this, canUseArrayContentFunctions, hashCodeArg) if (shouldWrapInLet) "$ref?.let { $hashCodeCall }" else hashCodeCall } else -> if (isNullable) "$ref?.hashCode()" else "$ref.hashCode()" } if (isNullable) { text += " ?: 0" if (parenthesesNeeded) { text = "($text)" } } return text } with(info) { if (!needHashCode) return null val superHashCode = classDescriptor.getSuperClassOrAny().findDeclaredHashCode(true)!! val hashCodeFun = generateFunctionSkeleton(superHashCode, targetClass) val builtins = superHashCode.builtIns val propertyIterator = variablesForHashCode.iterator() val initialValue = when { !builtins.isMemberOfAny(superHashCode) -> "super.hashCode()" propertyIterator.hasNext() -> propertyIterator.next().genVariableHashCode(false) else -> generateClassLiteral(targetClass) + ".hashCode()" } val bodyText = if (propertyIterator.hasNext()) { val validator = CollectingNameValidator(variablesForEquals.map { it.name.asString().quoteIfNeeded() }) val resultVarName = Fe10KotlinNameSuggester.suggestNameByName("result", validator) StringBuilder().apply { append("var $resultVarName = $initialValue\n") propertyIterator.forEach { append("$resultVarName = 31 * $resultVarName + ${it.genVariableHashCode(true)}\n") } append("return $resultVarName") }.toString() } else "return $initialValue" hashCodeFun.replaceBody { KtPsiFactory(project).createBlock(bodyText) } return hashCodeFun } } override fun generateMembers(project: Project, editor: Editor?, info: Info): List<KtDeclaration> { val targetClass = info.classDescriptor.source.getPsi() as KtClass val prototypes = ArrayList<KtDeclaration>(2) .apply { addIfNotNull(generateEquals(project, info, targetClass)) addIfNotNull(generateHashCode(project, info, targetClass)) } val anchor = with(targetClass.declarations) { lastIsInstanceOrNull<KtNamedFunction>() ?: lastOrNull() } return insertMembersAfterAndReformat(editor, targetClass, prototypes, anchor) } }
apache-2.0
a29dfad01e27783e3a65361442d27352
45.940994
158
0.644195
5.561074
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddNameToArgumentIntention.kt
1
5019
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.AddArgumentNamesApplicators import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespace import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatchStatus.ARGUMENT_HAS_NO_TYPE import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatchStatus.SUCCESS import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.VarargValueArgument class AddNameToArgumentIntention : SelfTargetingIntention<KtValueArgument>( KtValueArgument::class.java, KotlinBundle.lazyMessage("add.name.to.argument") ), LowPriorityAction { override fun isApplicableTo(element: KtValueArgument, caretOffset: Int): Boolean { val expression = element.getArgumentExpression() ?: return false val name = detectNameToAdd( element, shouldBeLastUnnamed = !element.languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition) ) ?: return false setTextGetter(KotlinBundle.lazyMessage("add.0.to.argument", name)) if (expression is KtLambdaExpression) { val range = expression.textRange return caretOffset == range.startOffset || caretOffset == range.endOffset } return true } override fun skipProcessingFurtherElementsAfter(element: PsiElement) = element is KtValueArgumentList || element is KtContainerNode || super.skipProcessingFurtherElementsAfter(element) override fun applyTo(element: KtValueArgument, editor: Editor?) { apply(element, givenResolvedCall = null, editor) } companion object { fun apply(element: KtValueArgument, givenResolvedCall: ResolvedCall<*>?, editor: Editor?) { val name = detectNameToAdd(element, shouldBeLastUnnamed = false, givenResolvedCall = givenResolvedCall) ?: return AddArgumentNamesApplicators.singleArgumentApplicator .applyTo(element, AddArgumentNamesApplicators.SingleArgumentInput(name), element.project, editor) } fun detectNameToAdd(argument: KtValueArgument, shouldBeLastUnnamed: Boolean, givenResolvedCall: ResolvedCall<*>? = null): Name? { if (argument.isNamed()) return null if (argument is KtLambdaArgument) return null val argumentList = argument.parent as? KtValueArgumentList ?: return null if (shouldBeLastUnnamed && argument != argumentList.arguments.last { !it.isNamed() }) return null val callExpr = argumentList.parent as? KtCallElement ?: return null val resolvedCall = givenResolvedCall ?: callExpr.resolveToCall() ?: return null if (!resolvedCall.candidateDescriptor.hasStableParameterNames()) return null if (!argumentMatchedAndCouldBeNamedInCall(argument, resolvedCall, callExpr.languageVersionSettings)) return null return (resolvedCall.getArgumentMapping(argument) as? ArgumentMatch)?.valueParameter?.name } fun argumentMatchedAndCouldBeNamedInCall( argument: ValueArgument, resolvedCall: ResolvedCall<out CallableDescriptor>, versionSettings: LanguageVersionSettings ): Boolean { val argumentMatch = resolvedCall.getArgumentMapping(argument) as? ArgumentMatch ?: return false if (argumentMatch.status != SUCCESS && argumentMatch.status != ARGUMENT_HAS_NO_TYPE) return false if (argumentMatch.valueParameter.varargElementType != null) { val varargArgument = resolvedCall.valueArguments[argumentMatch.valueParameter] as? VarargValueArgument ?: return false if (varargArgument.arguments.size != 1) return false if (versionSettings.supportsFeature(LanguageFeature.ProhibitAssigningSingleElementsToVarargsInNamedForm)) { if (argument.getSpreadElement() == null) return false } } return true } } }
apache-2.0
da5129ba0a8f40c200b12774d5480664
51.831579
158
0.741781
5.328025
false
false
false
false
npryce/robots
common/src/main/kotlin/robots/PListFocus.kt
1
1723
package robots data class PListFocus<T>(internal val back: PList<T>, val current: T, internal val forth: PList<T>) { fun hasNext(): Boolean = forth.isNotEmpty() fun next(): PListFocus<T>? = forth.notEmpty { (head, tail) -> PListFocus(Cons(current, back), head, tail) } fun next(n: Int): PListFocus<T>? = if (n > 0) { val next = next() if (next == null) { null } else { next.next(n - 1) } } else { this } fun hasPrev(): Boolean = back.isNotEmpty() fun prev(): PListFocus<T>? = back.notEmpty { (head, tail) -> PListFocus(tail, head, Cons(current, forth)) } fun remove(): PListFocus<T>? = forth.notEmpty { (head, tail) -> PListFocus(back, head, tail) } ?: back.notEmpty { (head, tail) -> PListFocus(tail, head, forth) } fun insertBefore(t: T): PListFocus<T> = PListFocus(back, t, Cons(current, forth)) fun insertAfter(t: T): PListFocus<T> = PListFocus(back, current, Cons(t, forth)) fun replaceWith(t: T): PListFocus<T> = copy(current = t) fun toPList(): PList<T> = back.fold(Cons(current, forth), { xs, x -> Cons(x, xs) }) } fun <T> PList<T>.focusHead(): PListFocus<T>? = this.notEmpty { (head, tail) -> PListFocus(Empty, head, tail) } fun <T> PList<T>.focusNth(n: Int): PListFocus<T>? = focusHead()?.next(n) fun PList<AST>.focusElements(): List<PListFocus<AST>> = generateSequence(focusHead(), { it.next() }).toList() fun <T> PListFocus<T>?.toPList(): PList<T> = when(this) { null -> emptyPList() else -> this.toPList() }
gpl-3.0
2d149ca01a9c5df67e2efa5a325f967c
30.327273
101
0.546721
3.257089
false
false
false
false
mdaniel/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRViewComponentFactory.kt
3
19927
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui.toolwindow import com.intellij.collaboration.ui.SingleValueModel import com.intellij.collaboration.ui.codereview.commits.CommitsBrowserComponentBuilder import com.intellij.ide.DataManager import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.ChangesUtil import com.intellij.openapi.vcs.changes.EditorTabDiffPreviewManager.Companion.EDITOR_TAB_DIFF_PREVIEW import com.intellij.openapi.vcs.changes.ui.ChangesTree import com.intellij.openapi.vcs.changes.ui.VcsTreeModelData import com.intellij.ui.IdeBorderFactory import com.intellij.ui.OnePixelSplitter import com.intellij.ui.ScrollPaneFactory import com.intellij.ui.SideBorder import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.tabs.JBTabs import com.intellij.util.containers.TreeTraversal import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import com.intellij.util.ui.tree.TreeUtil import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.VcsLogObjectsFactory import com.intellij.vcs.log.impl.HashImpl import com.intellij.vcsUtil.VcsUtil import git4idea.repo.GitRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import org.jetbrains.plugins.github.api.data.GHCommit import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequest import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestFileViewedState import org.jetbrains.plugins.github.api.data.pullrequest.isViewed import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.GHPRCombinedDiffPreviewBase.Companion.createAndSetupDiffPreview import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys.PULL_REQUEST_FILES import org.jetbrains.plugins.github.pullrequest.data.GHPRChangesProvider import org.jetbrains.plugins.github.pullrequest.data.GHPRDataContext import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier import org.jetbrains.plugins.github.pullrequest.ui.GHApiLoadingErrorHandler import org.jetbrains.plugins.github.pullrequest.ui.GHCompletableFutureLoadingModel import org.jetbrains.plugins.github.pullrequest.ui.GHLoadingPanelFactory import org.jetbrains.plugins.github.pullrequest.ui.changes.* import org.jetbrains.plugins.github.pullrequest.ui.details.GHPRBranchesModelImpl import org.jetbrains.plugins.github.pullrequest.ui.details.GHPRDetailsModelImpl import org.jetbrains.plugins.github.pullrequest.ui.details.GHPRMetadataModelImpl import org.jetbrains.plugins.github.pullrequest.ui.details.GHPRStateModelImpl import org.jetbrains.plugins.github.pullrequest.ui.getResultFlow import org.jetbrains.plugins.github.ui.HtmlInfoPanel import org.jetbrains.plugins.github.ui.util.GHUIUtil import org.jetbrains.plugins.github.util.DiffRequestChainProducer import javax.swing.JComponent import javax.swing.JList import javax.swing.JPanel import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.TreeNode internal class GHPRViewComponentFactory(private val actionManager: ActionManager, private val project: Project, private val dataContext: GHPRDataContext, private val viewController: GHPRToolWindowTabComponentController, pullRequest: GHPRIdentifier, private val disposable: Disposable) { private val dataProvider = dataContext.dataProviderRepository.getDataProvider(pullRequest, disposable) private val detailsLoadingModel = GHCompletableFutureLoadingModel<GHPullRequest>(disposable) private val commitsLoadingModel = GHCompletableFutureLoadingModel<List<GHCommit>>(disposable) private val changesLoadingModel = GHCompletableFutureLoadingModel<GHPRChangesProvider>(disposable) private val viewedStateLoadingModel = GHCompletableFutureLoadingModel<Map<String, GHPullRequestFileViewedState>>(disposable) init { dataProvider.detailsData.loadDetails(disposable) { detailsLoadingModel.future = it } dataProvider.changesData.loadCommitsFromApi(disposable) { commitsLoadingModel.future = it } dataProvider.changesData.loadChanges(disposable) { changesLoadingModel.future = it } setupViewedStateModel() // pre-fetch to show diff quicker dataProvider.changesData.fetchBaseBranch() dataProvider.changesData.fetchHeadBranch() } private val reloadDetailsAction = actionManager.getAction("Github.PullRequest.Details.Reload") private val reloadChangesAction = actionManager.getAction("Github.PullRequest.Changes.Reload") private val detailsLoadingErrorHandler = GHApiLoadingErrorHandler(project, dataContext.securityService.account) { dataProvider.detailsData.reloadDetails() } private val changesLoadingErrorHandler = GHApiLoadingErrorHandler(project, dataContext.securityService.account) { dataProvider.changesData.reloadChanges() } private val repository: GitRepository get() = dataContext.repositoryDataService.remoteCoordinates.repository private val diffRequestProducer: GHPRDiffRequestChainProducer = object : GHPRDiffRequestChainProducer(project, dataProvider, dataContext.avatarIconsProvider, dataContext.repositoryDataService, dataContext.securityService.currentUser) { private val viewedStateSupport = GHPRViewedStateDiffSupportImpl(repository, dataProvider.viewedStateData) override fun createCustomContext(change: Change): Map<Key<*>, Any> { if (diffBridge.activeTree != GHPRDiffController.ActiveTree.FILES) return emptyMap() return mapOf( GHPRViewedStateDiffSupport.KEY to viewedStateSupport, GHPRViewedStateDiffSupport.PULL_REQUEST_FILE to ChangesUtil.getFilePath(change) ) } } private val diffBridge = GHPRDiffController(dataProvider.diffRequestModel, diffRequestProducer) private val uiDisposable = Disposer.newDisposable().also { Disposer.register(disposable, it) } private fun setupViewedStateModel() { fun update() { viewedStateLoadingModel.future = dataProvider.viewedStateData.loadViewedState() } dataProvider.viewedStateData.addViewedStateListener(disposable) { update() } update() } fun create(): JComponent { val infoComponent = createInfoComponent() val filesComponent = createFilesComponent() val filesCountModel = createFilesCountModel() val notViewedFilesCountModel = createNotViewedFilesCountModel() val commitsComponent = createCommitsComponent() val commitsCountModel = createCommitsCountModel() val tabs = GHPRViewTabsFactory(project, viewController::viewList, uiDisposable) .create(infoComponent, diffBridge, filesComponent, filesCountModel, notViewedFilesCountModel, commitsComponent, commitsCountModel) .apply { setDataProvider { dataId -> when { GHPRActionKeys.GIT_REPOSITORY.`is`(dataId) -> repository GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER.`is`(dataId) -> [email protected] DiffRequestChainProducer.DATA_KEY.`is`(dataId) -> diffRequestProducer else -> null } } } val controller = Controller(tabs, filesComponent, commitsComponent) return tabs.component.also { UIUtil.putClientProperty(it, GHPRViewComponentController.KEY, controller) } } private inner class Controller(private val tabs: JBTabs, private val filesComponent: JComponent, private val commitsComponent: JComponent) : GHPRViewComponentController { override fun selectCommit(oid: String) { tabs.findInfo(commitsComponent)?.let { tabs.select(it, false) } val list = findCommitsList(commitsComponent) ?: return for (i in 0 until list.model.size) { val commit = list.model.getElementAt(i) if (commit.id.asString().startsWith(oid)) { list.selectedIndex = i break } } GHUIUtil.focusPanel(list) } private fun findCommitsList(parent: JComponent): JList<VcsCommitMetadata>? { UIUtil.getClientProperty(parent, CommitsBrowserComponentBuilder.COMMITS_LIST_KEY)?.run { return this } for (component in parent.components) { if (component is JComponent) { findCommitsList(component)?.run { return this } } } return null } override fun selectChange(oid: String?, filePath: String) { tabs.findInfo(filesComponent)?.let { tabs.select(it, false) } val tree = UIUtil.findComponentOfType(filesComponent, ChangesTree::class.java) ?: return GHUIUtil.focusPanel(tree) if (oid == null || !changesLoadingModel.resultAvailable) { tree.selectFile(VcsUtil.getFilePath(filePath, false)) } else { val change = changesLoadingModel.result!!.findCumulativeChange(oid, filePath) if (change == null) { tree.selectFile(VcsUtil.getFilePath(filePath, false)) } else { tree.selectChange(change) } } } } private fun createInfoComponent(): JComponent { val detailsLoadingPanel = GHLoadingPanelFactory(detailsLoadingModel, null, GithubBundle.message("cannot.load.details"), detailsLoadingErrorHandler).createWithUpdatesStripe(uiDisposable) { _, model -> val branchesModel = GHPRBranchesModelImpl(model, dataProvider.detailsData, repository, disposable) val detailsModel = GHPRDetailsModelImpl(model) val metadataModel = GHPRMetadataModelImpl(model, dataContext.securityService, dataContext.repositoryDataService, dataProvider.detailsData) val stateModel = GHPRStateModelImpl(project, dataProvider.stateData, dataProvider.changesData, model, disposable) GHPRDetailsComponent.create(project, dataContext.securityService, dataContext.avatarIconsProvider, branchesModel, detailsModel, metadataModel, stateModel) }.also { reloadDetailsAction.registerCustomShortcutSet(it, uiDisposable) } return Wrapper(detailsLoadingPanel).apply { isOpaque = true background = UIUtil.getListBackground() } } private fun createCommitsComponent(): JComponent { val splitter = OnePixelSplitter(true, "Github.PullRequest.Commits.Component", 0.4f).apply { isOpaque = true background = UIUtil.getListBackground() }.also { reloadChangesAction.registerCustomShortcutSet(it, uiDisposable) } val commitSelectionListener = CommitSelectionListener() val commitsLoadingPanel = GHLoadingPanelFactory(commitsLoadingModel, null, GithubBundle.message("cannot.load.commits"), changesLoadingErrorHandler) .createWithUpdatesStripe(uiDisposable) { _, model -> val commitsModel = model.map { list -> val logObjectsFactory = project.service<VcsLogObjectsFactory>() list.map { commit -> logObjectsFactory.createCommitMetadata( HashImpl.build(commit.oid), commit.parents.map { HashImpl.build(it.oid) }, commit.committer?.date?.time ?: 0L, repository.root, commit.messageHeadline, commit.author?.name ?: "unknown user", commit.author?.email ?: "", commit.messageHeadlineHTML + if (commit.messageBodyHTML.isEmpty()) "" else "\n\n${commit.messageBodyHTML}", commit.committer?.name ?: "unknown user", commit.committer?.email ?: "", commit.author?.date?.time ?: 0L ) } } CommitsBrowserComponentBuilder(project, commitsModel) .installPopupActions(DefaultActionGroup(actionManager.getAction("Github.PullRequest.Changes.Reload")), "GHPRCommitsPopup") .setEmptyCommitListText(GithubBundle.message("pull.request.does.not.contain.commits")) .onCommitSelected(commitSelectionListener) .create() } val changesLoadingPanel = GHLoadingPanelFactory(changesLoadingModel, GithubBundle.message("pull.request.select.commit.to.view.changes"), GithubBundle.message("cannot.load.changes"), changesLoadingErrorHandler) .withContentListener { diffBridge.commitsTree = UIUtil.findComponentOfType(it, ChangesTree::class.java) } .createWithUpdatesStripe(uiDisposable) { parent, model -> val reviewUnsupportedWarning = createReviewUnsupportedPlaque(model) JBUI.Panels.simplePanel(createChangesTree(parent, createCommitChangesModel(model, commitSelectionListener), GithubBundle.message("pull.request.commit.does.not.contain.changes"))) .addToTop(reviewUnsupportedWarning) .andTransparent() }.apply { border = IdeBorderFactory.createBorder(SideBorder.TOP) } val toolbar = GHPRChangesTreeFactory.createTreeToolbar(actionManager, changesLoadingPanel) val changesBrowser = BorderLayoutPanel().andTransparent() .addToTop(toolbar) .addToCenter(changesLoadingPanel) return splitter.apply { firstComponent = commitsLoadingPanel secondComponent = changesBrowser } } private fun createCommitsCountModel(): Flow<Int?> = commitsLoadingModel.getResultFlow().map { it?.size } private fun createFilesComponent(): JComponent { val panel = BorderLayoutPanel().withBackground(UIUtil.getListBackground()) val changesLoadingPanel = GHLoadingPanelFactory(changesLoadingModel, null, GithubBundle.message("cannot.load.changes"), changesLoadingErrorHandler) .withContentListener { val tree = UIUtil.findComponentOfType(it, ChangesTree::class.java) diffBridge.filesTree = tree tree?.showPullRequestProgress(uiDisposable, repository, dataProvider.reviewData, dataProvider.viewedStateData) } .createWithUpdatesStripe(uiDisposable) { parent, model -> val getCustomData = { tree: ChangesTree, dataId: String -> if (PULL_REQUEST_FILES.`is`(dataId)) tree.getPullRequestFiles() else null } createChangesTree(parent, model.map { it.changes }, GithubBundle.message("pull.request.does.not.contain.changes"), getCustomData) }.apply { border = IdeBorderFactory.createBorder(SideBorder.TOP) } val toolbar = GHPRChangesTreeFactory.createTreeToolbar(actionManager, changesLoadingPanel) return panel.addToTop(toolbar).addToCenter(changesLoadingPanel) } private fun createFilesCountModel(): Flow<Int?> = changesLoadingModel.getResultFlow().map { it?.changes?.size } private fun createNotViewedFilesCountModel(): Flow<Int?> = viewedStateLoadingModel.getResultFlow().map { it?.count { (_, state) -> !state.isViewed() } } private fun createReviewUnsupportedPlaque(model: SingleValueModel<GHPRChangesProvider>) = HtmlInfoPanel().apply { setInfo(GithubBundle.message("pull.request.review.not.supported.non.linear"), HtmlInfoPanel.Severity.WARNING) border = IdeBorderFactory.createBorder(SideBorder.BOTTOM) model.addAndInvokeListener { isVisible = !model.value.linearHistory } } private fun createCommitChangesModel(changesModel: SingleValueModel<GHPRChangesProvider>, commitSelectionListener: CommitSelectionListener): SingleValueModel<List<Change>> { val model = SingleValueModel(changesModel.value.changesByCommits[commitSelectionListener.currentCommit?.id?.asString()].orEmpty()) fun update() { val commit = commitSelectionListener.currentCommit model.value = changesModel.value.changesByCommits[commit?.id?.asString()].orEmpty() } commitSelectionListener.delegate = ::update changesModel.addAndInvokeListener { update() } return model } private fun createChangesTree( parentPanel: JPanel, model: SingleValueModel<List<Change>>, emptyTextText: String, getCustomData: ChangesTree.(String) -> Any? = { null } ): JComponent { val tree = GHPRChangesTreeFactory(project, model).create(emptyTextText) val diffPreviewController = createAndSetupDiffPreview(tree, diffRequestProducer.changeProducerFactory, dataProvider, dataContext.filesManager) reloadChangesAction.registerCustomShortcutSet(tree, null) tree.installPopupHandler(actionManager.getAction("Github.PullRequest.Changes.Popup") as ActionGroup) DataManager.registerDataProvider(parentPanel) { dataId -> when { EDITOR_TAB_DIFF_PREVIEW.`is`(dataId) -> diffPreviewController.activePreview tree.isShowing -> tree.getCustomData(dataId) ?: tree.getData(dataId) else -> null } } return ScrollPaneFactory.createScrollPane(tree, true) } private class CommitSelectionListener : (VcsCommitMetadata?) -> Unit { var currentCommit: VcsCommitMetadata? = null var delegate: (() -> Unit)? = null override fun invoke(commit: VcsCommitMetadata?) { currentCommit = commit delegate?.invoke() } } companion object { private fun ChangesTree.selectChange(toSelect: Change) { val rowInTree = findRowContainingChange(root, toSelect) if (rowInTree == -1) return setSelectionRow(rowInTree) TreeUtil.showRowCentered(this, rowInTree, false) } private fun ChangesTree.findRowContainingChange(root: TreeNode, toSelect: Change): Int { val targetNode = TreeUtil.treeNodeTraverser(root).traverse(TreeTraversal.POST_ORDER_DFS).find { node -> node is DefaultMutableTreeNode && node.userObject?.let { it is Change && it == toSelect && it.beforeRevision == toSelect.beforeRevision && it.afterRevision == toSelect.afterRevision } ?: false } return if (targetNode != null) TreeUtil.getRowForNode(this, targetNode as DefaultMutableTreeNode) else -1 } } } private fun ChangesTree.getPullRequestFiles(): Iterable<FilePath> = VcsTreeModelData.selected(this) .iterateUserObjects(Change::class.java) .map { ChangesUtil.getFilePath(it) }
apache-2.0
64f6a682c093a365ba94cdce15f6c819
44.3918
158
0.700507
5.129215
false
false
false
false
rubengees/ktask
sample-android/src/main/kotlin/com/rubengees/ktask/sample/android/MainFragment.kt
1
4308
package com.rubengees.ktask.sample.android import android.os.Bundle import android.os.Parcelable import android.support.v4.app.Fragment import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import butterknife.bindView import com.rubengees.ktask.android.AndroidLifecycleTask import com.rubengees.ktask.android.bindToLifecycle import com.rubengees.ktask.retrofit.asyncRetrofitTask import com.rubengees.ktask.sample.RepositoryInfo import com.rubengees.ktask.sample.Utils import com.rubengees.ktask.util.TaskBuilder import retrofit2.Call /** * TODO: Describe class * * @author Ruben Gees */ class MainFragment : Fragment() { companion object { private const val LIST_STATE = "list_state" fun newInstance(): MainFragment { return MainFragment() } } private lateinit var task: AndroidLifecycleTask<Call<RepositoryInfo>, RepositoryInfo> private lateinit var adapter: RepositoryAdapter private var listState: Parcelable? = null private val progress: SwipeRefreshLayout by bindView(R.id.progress) private val content: RecyclerView by bindView(R.id.content) private val errorContainer: ViewGroup by bindView(R.id.errorContainer) private val errorText: TextView by bindView(R.id.errorText) private val errorButton: Button by bindView(R.id.errorButton) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) task = TaskBuilder.asyncRetrofitTask<RepositoryInfo>() .cache() .bindToLifecycle(this) .onInnerStart { content.visibility = View.INVISIBLE errorContainer.visibility = View.INVISIBLE progress.isRefreshing = true } .onSuccess { content.visibility = View.VISIBLE adapter.replace(it.repositories) } .onError { errorContainer.visibility = View.VISIBLE errorText.text = it.message ?: getString(R.string.error_unknown) } .onFinish { progress.isRefreshing = false if (listState != null) { content.layoutManager.onRestoreInstanceState(listState) listState = null } } .build() adapter = RepositoryAdapter() listState = savedInstanceState?.getParcelable(LIST_STATE) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_main, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) progress.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark) progress.isRefreshing = task.isWorking progress.setOnRefreshListener { task.freshExecute(MainApplication.api.mostStarredRepositories(Utils.query())) } content.setHasFixedSize(true) content.adapter = adapter content.layoutManager = LinearLayoutManager(context) content.addItemDecoration(MarginDecoration(marginDp = 8, columns = 1)) content.visibility = View.INVISIBLE errorContainer.visibility = View.INVISIBLE errorButton.setOnClickListener { task.freshExecute(MainApplication.api.mostStarredRepositories(Utils.query())) } } override fun onResume() { super.onResume() task.execute(MainApplication.api.mostStarredRepositories(Utils.query())) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable(LIST_STATE, content.layoutManager.onSaveInstanceState()) } override fun onDestroy() { super.onDestroy() MainApplication.refWatcher.watch(this) } }
mit
129c1dedc62edd98094b0ed414de3a2a
32.65625
116
0.672934
5.03271
false
false
false
false
jk1/intellij-community
uast/uast-common/src/org/jetbrains/uast/values/UPhiValue.kt
3
1683
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.values class UPhiValue private constructor(val values: Set<UValue>) : UValueBase() { override val dependencies: Set<UDependency> = values.flatMapTo(linkedSetOf()) { it.dependencies } override fun equals(other: Any?): Boolean = other is UPhiValue && values == other.values override fun hashCode(): Int = values.hashCode() override fun toString(): String = values.joinToString(prefix = "Phi(", postfix = ")", separator = ", ") companion object { private val PHI_LIMIT = 4 fun create(values: Iterable<UValue>): UValue { val flattenedValues = values.flatMapTo(linkedSetOf<UValue>()) { (it as? UPhiValue)?.values ?: listOf(it) } if (flattenedValues.size <= 1) { throw AssertionError("UPhiValue should contain two or more values: $flattenedValues") } if (flattenedValues.size > PHI_LIMIT || UUndeterminedValue in flattenedValues) { return UUndeterminedValue } return UPhiValue(flattenedValues) } fun create(vararg values: UValue): UValue = create(values.asIterable()) } }
apache-2.0
084cf64c6b9782f7c296969540b4345b
36.4
112
0.708259
4.271574
false
false
false
false
ktorio/ktor
ktor-utils/posix/src/io/ktor/util/collections/LockFreeMPSCQueueNative.kt
1
10691
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.collections import io.ktor.util.* import kotlinx.atomicfu.* import kotlin.native.concurrent.* private typealias Core<E> = LockFreeMPSCQueueCore<E> /** * Lock-free Multiply-Producer Single-Consumer Queue. * *Note: This queue is NOT linearizable. It provides only quiescent consistency for its operations.* * * In particular, the following execution is permitted for this queue, but is not permitted for a linearizable queue: * * ``` * Thread 1: addLast(1) = true, removeFirstOrNull() = null * Thread 2: addLast(2) = 2 // this operation is concurrent with both operations in the first thread * ``` */ @InternalAPI public class LockFreeMPSCQueue<E : Any> { private val _cur = atomic(Core<E>(Core.INITIAL_CAPACITY)) private val closed = atomic(0) // Note: it is not atomic w.r.t. remove operation (remove can transiently fail when isEmpty is false) public val isEmpty: Boolean get() = _cur.value.isEmpty public val isClosed: Boolean get() = closed.value == 1 public fun close() { try { _cur.loop { cur -> if (cur.close()) return // closed this copy _cur.compareAndSet(cur, cur.next()) // move to next } } finally { if (!closed.compareAndSet(0, 1)) return } } public fun addLast(element: E): Boolean { _cur.loop { cur -> when (cur.addLast(element)) { Core.ADD_SUCCESS -> return true Core.ADD_CLOSED -> return false Core.ADD_FROZEN -> _cur.compareAndSet(cur, cur.next()) // move to next } } } @Suppress("UNCHECKED_CAST") public fun removeFirstOrNull(): E? { _cur.loop { cur -> val result = cur.removeFirstOrNull() if (result !== Core.REMOVE_FROZEN) return result as E? _cur.compareAndSet(cur, cur.next()) } } } /** * Lock-free Multiply-Producer Single-Consumer Queue core. * *Note: This queue is NOT linearizable. It provides only quiescent consistency for its operations.* * * @see LockFreeMPSCQueue */ private class LockFreeMPSCQueueCore<E : Any>(private val capacity: Int) { private val mask = capacity - 1 private val _next = atomic<Core<E>?>(null) private val _state = atomic(0L) private val array = atomicArrayOfNulls<Any?>(capacity) private fun setArrayValueHelper(index: Int, value: Any?) { array[index].value = value } init { check(mask <= MAX_CAPACITY_MASK) check(capacity and mask == 0) } // Note: it is not atomic w.r.t. remove operation (remove can transiently fail when isEmpty is false) val isEmpty: Boolean get() = _state.value.withState { head, tail -> head == tail } fun close(): Boolean { _state.update { state -> if (state and CLOSED_MASK != 0L) return true // ok - already closed if (state and FROZEN_MASK != 0L) return false // frozen -- try next state or CLOSED_MASK // try set closed bit } return true } // ADD_CLOSED | ADD_FROZEN | ADD_SUCCESS fun addLast(element: E): Int { _state.loop { state -> if (state and (FROZEN_MASK or CLOSED_MASK) != 0L) return state.addFailReason() // cannot add state.withState { head, tail -> // there could be one REMOVE element beyond head that we cannot stump up, // so we check for full queue with an extra margin of one element if ((tail + 2) and mask == head and mask) return ADD_FROZEN // overfull, so do freeze & copy val newTail = (tail + 1) and MAX_CAPACITY_MASK if (_state.compareAndSet(state, state.updateTail(newTail))) { // successfully added array[tail and mask].value = element // could have been frozen & copied before this item was set -- correct it by filling placeholder var cur = this while (true) { if (cur._state.value and FROZEN_MASK == 0L) break // all fine -- not frozen yet cur = cur.next().fillPlaceholder(tail, element) ?: break } return ADD_SUCCESS // added successfully } } } } private fun fillPlaceholder(index: Int, element: E): Core<E>? { val old = array[index and mask].value /* * addLast actions: * 1) Commit tail slot * 2) Write element to array slot * 3) Check for array copy * * If copy happened between 2 and 3 then the consumer might have consumed our element, * then another producer might have written its placeholder in our slot, so we should * perform *unique* check that current placeholder is our to avoid overwriting another producer placeholder */ if (old is Placeholder && old.index == index) { array[index and mask].value = element // we've corrected missing element, should check if that propagated to further copies, just in case return this } // it is Ok, no need for further action return null } // SINGLE CONSUMER // REMOVE_FROZEN | null (EMPTY) | E (SUCCESS) fun removeFirstOrNull(): Any? { _state.loop { state -> if (state and FROZEN_MASK != 0L) return REMOVE_FROZEN // frozen -- cannot modify state.withState { head, tail -> if ((tail and mask) == (head and mask)) return null // empty // because queue is Single Consumer, then element == null|Placeholder can only be when add has not finished yet val element = array[head and mask].value ?: return null if (element is Placeholder) return null // same story -- consider it not added yet // we cannot put null into array here, because copying thread could replace it with Placeholder and that is a disaster val newHead = (head + 1) and MAX_CAPACITY_MASK if (_state.compareAndSet(state, state.updateHead(newHead))) { array[head and mask].value = null // now can safely put null (state was updated) return element // successfully removed in fast-path } // Slow-path for remove in case of interference var cur = this while (true) { @Suppress("UNUSED_VALUE") cur = cur.removeSlowPath(head, newHead) ?: return element } } } } private fun removeSlowPath(oldHead: Int, newHead: Int): Core<E>? { _state.loop { state -> state.withState { head, _ -> check(head == oldHead) { "This queue can have only one consumer" } if (state and FROZEN_MASK != 0L) { // state was already frozen, so removed element was copied to next return next() // continue to correct head in next } if (_state.compareAndSet(state, state.updateHead(newHead))) { array[head and mask].value = null // now can safely put null (state was updated) return null } } } } fun next(): LockFreeMPSCQueueCore<E> = allocateOrGetNextCopy(markFrozen()) private fun markFrozen(): Long = _state.updateAndGet { state -> if (state and FROZEN_MASK != 0L) return state // already marked state or FROZEN_MASK } private fun allocateOrGetNextCopy(state: Long): Core<E> { _next.loop { next -> if (next != null) return next // already allocated & copied _next.compareAndSet(null, allocateNextCopy(state)) } } private fun allocateNextCopy(state: Long): Core<E> { val next = LockFreeMPSCQueueCore<E>(capacity * 2) state.withState { head, tail -> var index = head while (index and mask != tail and mask) { // replace nulls with placeholders on copy val value = array[index and mask].value next.setArrayValueHelper(index and next.mask, value ?: Placeholder(index)) index++ } next._state.value = state wo FROZEN_MASK } return next } // Instance of this class is placed into array when we have to copy array, but addLast is in progress -- // it had already reserved a slot in the array (with null) and have not yet put its value there. // Placeholder keeps the actual index (not masked) to distinguish placeholders on different wraparounds of array private class Placeholder(val index: Int) @Suppress("PrivatePropertyName") companion object { internal const val INITIAL_CAPACITY = 8 private const val CAPACITY_BITS = 30 private const val MAX_CAPACITY_MASK = (1 shl CAPACITY_BITS) - 1 private const val HEAD_SHIFT = 0 private const val HEAD_MASK = MAX_CAPACITY_MASK.toLong() shl HEAD_SHIFT private const val TAIL_SHIFT = HEAD_SHIFT + CAPACITY_BITS private const val TAIL_MASK = MAX_CAPACITY_MASK.toLong() shl TAIL_SHIFT private const val FROZEN_SHIFT = TAIL_SHIFT + CAPACITY_BITS private const val FROZEN_MASK = 1L shl FROZEN_SHIFT private const val CLOSED_SHIFT = FROZEN_SHIFT + 1 private const val CLOSED_MASK = 1L shl CLOSED_SHIFT internal val REMOVE_FROZEN = object { override fun toString() = "REMOVE_FROZEN" } internal const val ADD_SUCCESS = 0 internal const val ADD_FROZEN = 1 internal const val ADD_CLOSED = 2 private infix fun Long.wo(other: Long) = this and other.inv() private fun Long.updateHead(newHead: Int) = (this wo HEAD_MASK) or (newHead.toLong() shl HEAD_SHIFT) private fun Long.updateTail(newTail: Int) = (this wo TAIL_MASK) or (newTail.toLong() shl TAIL_SHIFT) private inline fun <T> Long.withState(block: (head: Int, tail: Int) -> T): T { val head = ((this and HEAD_MASK) shr HEAD_SHIFT).toInt() val tail = ((this and TAIL_MASK) shr TAIL_SHIFT).toInt() return block(head, tail) } // FROZEN | CLOSED private fun Long.addFailReason(): Int = if (this and CLOSED_MASK != 0L) ADD_CLOSED else ADD_FROZEN } }
apache-2.0
60ce10dd585046a846e6f4b899eaf990
40.92549
134
0.592087
4.403213
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/bungeecord/BungeeCordProjectConfiguration.kt
1
2344
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.bungeecord import com.demonwav.mcdev.buildsystem.BuildSystem import com.demonwav.mcdev.platform.PlatformType import com.demonwav.mcdev.platform.ProjectConfiguration import com.demonwav.mcdev.util.runWriteTask import com.intellij.ide.util.EditorHelper import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.psi.PsiManager class BungeeCordProjectConfiguration : ProjectConfiguration() { val dependencies = mutableListOf<String>() val softDependencies = mutableListOf<String>() var minecraftVersion = "" init { type = PlatformType.BUNGEECORD } fun hasDependencies() = listContainsAtLeastOne(dependencies) fun setDependencies(string: String) { dependencies.clear() dependencies.addAll(commaSplit(string)) } fun hasSoftDependencies() = listContainsAtLeastOne(softDependencies) fun setSoftDependencies(string: String) { softDependencies.clear() softDependencies.addAll(commaSplit(string)) } override fun create(project: Project, buildSystem: BuildSystem, indicator: ProgressIndicator) { runWriteTask { indicator.text = "Writing main class" // Create plugin main class var file = buildSystem.sourceDirectory val files = mainClass.split(".").toTypedArray() val className = files.last() val packageName = mainClass.substring(0, mainClass.length - className.length - 1) file = getMainClassDirectory(files, file) val mainClassFile = file.findOrCreateChildData(this, className + ".java") BungeeCordTemplate.applyMainClassTemplate(project, mainClassFile, packageName, className) val pluginYml = buildSystem.resourceDirectory.findOrCreateChildData(this, "plugin.yml") BungeeCordTemplate.applyPluginDescriptionFileTemplate(project, pluginYml, this, buildSystem) // Set the editor focus on the main class PsiManager.getInstance(project).findFile(mainClassFile)?.let { mainClassPsi -> EditorHelper.openInEditor(mainClassPsi) } } } }
mit
ffae79aa1a48faee900f9be567187f99
34.515152
104
0.709044
4.987234
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/Node.kt
1
26721
package graphics.scenery import graphics.scenery.geometry.GeometryType import graphics.scenery.attribute.AttributesMap import graphics.scenery.attribute.geometry.Geometry import graphics.scenery.attribute.material.Material import graphics.scenery.attribute.renderable.Renderable import graphics.scenery.attribute.spatial.Spatial import graphics.scenery.utils.MaybeIntersects import net.imglib2.Localizable import net.imglib2.RealLocalizable import org.joml.Matrix4f import org.joml.Quaternionf import org.joml.Vector3f import java.io.Serializable import java.nio.FloatBuffer import java.nio.IntBuffer import java.util.* import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.locks.ReentrantLock import java.util.function.Consumer import kotlin.collections.ArrayList interface Node : Serializable { var name: String var nodeType: String /** Children of the Node. */ var children: CopyOnWriteArrayList<Node> /** Other nodes that have linked transforms. */ var linkedNodes: CopyOnWriteArrayList<Node> /** Parent node of this node. */ var parent: Node? /** Creation timestamp of the node. */ var createdAt: Long /** Modification timestamp of the node. */ var modifiedAt: Long /** Flag to set whether the object is visible or not. */ var visible: Boolean var discoveryBarrier: Boolean /** Hash map used for storing metadata for the Node. */ var metadata: HashMap<String, Any> /** Node update routine, called before updateWorld */ var update: ArrayList<() -> Unit> /** Node update routine, called after updateWorld */ var postUpdate: ArrayList<() -> Unit> /** Whether the object has been initialized. Used by renderers. */ var initialized: Boolean /** State of the Node **/ var state: State /** [ReentrantLock] to be used if the object is being updated and should not be * touched in the meantime. */ var lock: ReentrantLock /** Initialisation function for the object */ fun init(): Boolean val logger: org.slf4j.Logger /** bounding box **/ var boundingBox: OrientedBoundingBox? fun getAttributes(): AttributesMap fun <T, U: T> getAttributeOrNull(attributeType: Class<T>): U? { return getAttributes().get<T, U>(attributeType) } fun <T, U: T> addAttribute(attributeType: Class<T>, attribute: U) { getAttributes().put(attributeType, attribute) } fun <T, U: T> addAttribute(attributeType: Class<T>, attribute: U, block: U.() -> Unit) { attribute.block() addAttribute(attributeType, attribute) } fun <T, U: T> ifHasAttribute(attributeType: Class<T>, block: U.() -> Unit) : U? { val attribute = getAttributeOrNull<T, U>(attributeType) ?: return null attribute.block() return attribute } @Throws(IllegalStateException::class) fun <T, U: T> getAttribute(attributeType: Class<T>, block: U.() -> Unit) : U { val attribute = getAttribute<T, U>(attributeType) attribute.block() return attribute } @Throws(IllegalStateException::class) fun <T, U: T> getAttribute(attributeType: Class<T>) : U { return getAttributeOrNull<T, U>(attributeType) ?: throw IllegalStateException("Node doesn't have attribute named " + attributeType) } fun ifSpatial(block: Spatial.() -> Unit): Spatial? { return ifHasAttribute(Spatial::class.java, block) } fun spatialOrNull(): Spatial? { return ifSpatial {} } fun ifGeometry(block: Geometry.() -> Unit): Geometry? { return ifHasAttribute(Geometry::class.java, block) } fun geometryOrNull(): Geometry? { return ifGeometry {} } fun ifRenderable(block: Renderable.() -> Unit): Renderable? { return ifHasAttribute(Renderable::class.java, block) } fun renderableOrNull(): Renderable? { return ifRenderable {} } fun ifMaterial(block: Material.() -> Unit): Material? { return ifHasAttribute(Material::class.java, block) } fun materialOrNull(): Material? { return ifMaterial {} } fun setMaterial(material: Material) { return addAttribute(Material::class.java, material) } fun setMaterial(material: Material, block: Material.() -> Unit) { return addAttribute(Material::class.java, material, block) } /** Unique ID of the Node */ fun getUuid(): UUID /** * Attaches a child node to this node. * * @param[child] The child to attach to this node. */ fun addChild(child: Node) /** * Removes a given node from the set of children of this node. * * @param[child] The child node to remove. */ fun removeChild(child: Node): Boolean /** * Removes a given node from the set of children of this node. * If possible, use [removeChild] instead. * * @param[name] The name of the child node to remove. */ fun removeChild(name: String): Boolean /** * Returns all children with the given [name]. */ fun getChildrenByName(name: String): List<Node> /** * Returns the [Scene] this Node is ultimately attached to. * Will return null in case the Node is not attached to a [Scene] yet. */ fun getScene(): Scene? /** * Runs an operation recursively on the node itself and all child nodes. * * @param[func] A lambda accepting a [Node], representing this node and its potential children. */ fun runRecursive(func: (Node) -> Unit) /** * Generates an [OrientedBoundingBox] for this [Node]. This will take * geometry information into consideration if this Node implements [Geometry]. * In case a bounding box cannot be determined, the function will return null. */ fun generateBoundingBox(): OrientedBoundingBox? { val geometry = geometryOrNull() if(geometry == null) { logger.warn("$name: Assuming 3rd party BB generation") return boundingBox } else { boundingBox = geometry.generateBoundingBox(children) return boundingBox } } /** * Returns the maximum [OrientedBoundingBox] of this [Node] and all its children. */ fun getMaximumBoundingBox(): OrientedBoundingBox /** * Runs an operation recursively on the node itself and all child nodes. * * @param[func] A Java [Consumer] accepting a [Node], representing this node and its potential children. */ fun runRecursive(func: Consumer<Node>) /** * Returns the [ShaderProperty] given by [name], if it exists and is declared by * this class or a subclass inheriting from [Node]. Returns null if the [name] can * neither be found as a property, or as member of the shaderProperties HashMap the Node * might declare. */ fun getShaderProperty(name: String): Any? companion object NodeHelpers { /** * Depth-first search for elements in a Scene. * * @param[origin] The [Node] to start the search at. * @param[func] A lambda taking a [Node] and returning a Boolean for matching. * @return A list of [Node]s that match [func]. */ @Suppress("unused") fun discover(origin: Node, func: (Node) -> Boolean): ArrayList<Node> { val visited = HashSet<Node>() val matched = ArrayList<Node>() fun discover(current: Node, f: (Node) -> Boolean) { if (!visited.add(current)) return for (v in current.children) { if (f(v)) { matched.add(v) } discover(v, f) } } discover(origin, func) return matched } } @Deprecated(message = "Moved to attribute material(), see AttributesExample for usage details", replaceWith = ReplaceWith("material()")) fun getMaterial(): Material { return this.materialOrNull()!! } @Deprecated(message = "Moved to attribute geometry(), see AttributesExample for usage details", replaceWith = ReplaceWith("geometry().dirty")) var dirty: Boolean get() = this.geometryOrNull()!!.dirty set(value) { this.ifGeometry { dirty = value } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().world")) var world: Matrix4f get() = this.spatialOrNull()!!.world set(value) { this.ifSpatial { world = value } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().iworld")) var iworld: Matrix4f get() = Matrix4f(spatialOrNull()!!.world).invert() set(ignored) {} @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().model")) var model: Matrix4f get() = this.spatialOrNull()!!.model set(value) { this.ifSpatial { model = value } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().imodel")) var imodel: Matrix4f get() = Matrix4f(spatialOrNull()!!.model).invert() set(ignored) {} @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().view")) var view: Matrix4f get() = this.spatialOrNull()!!.view set(value) { this.ifSpatial { view = value } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().iview")) var iview: Matrix4f get() = Matrix4f(spatialOrNull()!!.view).invert() set(ignored) {} @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().projection")) var projection: Matrix4f get() = this.spatialOrNull()!!.projection set(value) { this.ifSpatial { projection = value } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().iprojection")) var iprojection: Matrix4f get() = Matrix4f(spatialOrNull()!!.projection).invert() set(ignored) {} // @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().modelView")) // var modelView: Matrix4f // get() = this.spatial().modelView // set(value) { // this.ifSpatial { // modelView = value // } // } // // @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().imodelView")) // var imodelView: Matrix4f // get() = this.spatial().imodelView // set(value) { // this.ifSpatial { // imodelView = value // } // } // // @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().mvp")) // var mvp: Matrix4f // get() = this.spatial().mvp // set(value) { // this.ifSpatial { // mvp = value // } // } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().position")) var position: Vector3f get() = this.spatialOrNull()!!.position set(value) { this.ifSpatial { position = value } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().scale")) var scale: Vector3f get() = this.spatialOrNull()!!.scale set(value) { this.ifSpatial { scale = value } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().rotation")) var rotation: Quaternionf get() = this.spatialOrNull()!!.rotation set(value) { this.ifSpatial { rotation = value } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().wantsComposeModel")) var wantsComposeModel: Boolean get() = this.spatialOrNull()!!.wantsComposeModel set(value) { this.ifSpatial { wantsComposeModel = value } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().needsUpdate")) var needsUpdate: Boolean get() = this.spatialOrNull()!!.needsUpdate set(value) { this.ifSpatial { needsUpdate = value } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().needsUpdateWorld")) var needsUpdateWorld: Boolean get() = this.spatialOrNull()!!.needsUpdateWorld set(value) { this.ifSpatial { needsUpdateWorld = value } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().updateWorld(recursive, force)")) fun updateWorld(recursive: Boolean, force: Boolean = false) { ifSpatial { updateWorld(recursive, force) } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().composeModel()")) fun composeModel() { ifSpatial { composeModel() } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().centerOn(position)")) fun centerOn(position: Vector3f): Vector3f { return this.spatialOrNull()!!.centerOn(position) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().putAbove(position)")) fun putAbove(position: Vector3f): Vector3f { return this.spatialOrNull()!!.putAbove(position) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().fitInto(sideLength, scaleUp)")) fun fitInto(sideLength: Float, scaleUp: Boolean = false): Vector3f { return this.spatialOrNull()!!.fitInto(sideLength, scaleUp) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().orientBetweenPoints(p1, p2, rescale, reposition)")) fun orientBetweenPoints(p1: Vector3f, p2: Vector3f, rescale: Boolean, reposition: Boolean): Quaternionf { return this.spatialOrNull()!!.orientBetweenPoints(p1, p2, rescale, reposition) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().orientBetweenPoints(p1, p2, rescale)")) fun orientBetweenPoints(p1: Vector3f, p2: Vector3f, rescale: Boolean): Quaternionf { return this.spatialOrNull()!!.orientBetweenPoints(p1, p2, rescale, false) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().orientBetweenPoints(p1, p2)")) fun orientBetweenPoints(p1: Vector3f, p2: Vector3f): Quaternionf { return this.spatialOrNull()!!.orientBetweenPoints(p1, p2, false, false) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().intersects(other)")) fun intersects(other: Node): Boolean { return this.spatialOrNull()!!.intersects(other) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().worldPosition(v)")) fun worldPosition(v: Vector3f? = null): Vector3f { return this.spatialOrNull()!!.worldPosition(v) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().intersectAABB(origin, dir)")) fun intersectAABB(origin: Vector3f, dir: Vector3f): MaybeIntersects { return this.spatialOrNull()!!.intersectAABB(origin, dir) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().localize(position)")) fun localize(position: FloatArray?) { return this.spatialOrNull()!!.localize(position) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().localize(position)")) fun localize(position: DoubleArray?) { return this.spatialOrNull()!!.localize(position) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().getFloatPosition(d)")) fun getFloatPosition(d: Int): Float { return this.spatialOrNull()!!.getFloatPosition(d) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().bck(d)")) fun bck(d: Int) { return this.spatialOrNull()!!.bck(d) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().move(distance, d)")) fun move(distance: Float, d: Int) { return this.spatialOrNull()!!.move(distance, d) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().move(distance, d)")) fun move(distance: Double, d: Int) { return this.spatialOrNull()!!.move(distance, d) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().move(distance)")) fun move(distance: RealLocalizable?) { return this.spatialOrNull()!!.move(distance) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().move(distance)")) fun move(distance: FloatArray?) { return this.spatialOrNull()!!.move(distance) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().move(distance)")) fun move(distance: DoubleArray?) { return this.spatialOrNull()!!.move(distance) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().move(distance, d)")) fun move(distance: Int, d: Int) { return this.spatialOrNull()!!.move(distance, d) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().move(distance, d)")) fun move(distance: Long, d: Int) { return this.spatialOrNull()!!.move(distance, d) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().move(distance)")) fun move(distance: Localizable?) { return this.spatialOrNull()!!.move(distance) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().move(distance)")) fun move(distance: IntArray?) { return this.spatialOrNull()!!.move(distance) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().move(distance)")) fun move(distance: LongArray?) { return this.spatialOrNull()!!.move(distance) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().numDimensions()")) fun numDimensions(): Int { return this.spatialOrNull()!!.numDimensions() } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().fwd(d)")) fun fwd(d: Int) { ifSpatial { fwd(d) } } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().getDoublePosition(d)")) fun getDoublePosition(d: Int): Double { return this.spatialOrNull()!!.getDoublePosition(d) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().setPosition(pos)")) fun setPosition(pos: RealLocalizable) { return this.spatialOrNull()!!.setPosition(pos) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().setPosition(pos)")) fun setPosition(pos: FloatArray?) { return this.spatialOrNull()!!.setPosition(pos) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().setPosition(pos)")) fun setPosition(pos: DoubleArray?) { return this.spatialOrNull()!!.setPosition(pos) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().setPosition(pos, d)")) fun setPosition(pos: Float, d: Int) { return this.spatialOrNull()!!.setPosition(pos, d) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().setPosition(pos, d)")) fun setPosition(pos: Double, d: Int) { return this.spatialOrNull()!!.setPosition(pos, d) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().setPosition(pos)")) fun setPosition(pos: Localizable?) { return this.spatialOrNull()!!.setPosition(pos) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().setPosition(pos)")) fun setPosition(pos: IntArray?) { return this.spatialOrNull()!!.setPosition(pos) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().setPosition(pos)")) fun setPosition(pos: LongArray?) { return this.spatialOrNull()!!.setPosition(pos) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().setPosition(position, d)")) fun setPosition(position: Int, d: Int) { return this.spatialOrNull()!!.setPosition(position, d) } @Deprecated(message = "Moved to attribute spatial(), see AttributesExample for usage details", replaceWith = ReplaceWith("spatial().setPosition(position, d)")) fun setPosition(position: Long, d: Int) { return this.spatialOrNull()!!.setPosition(position, d) } @Deprecated(message = "Moved to attribute geometry(), see AttributesExample for usage details", replaceWith = ReplaceWith("geometry().vertexSize")) var vertexSize: Int get() = this.geometryOrNull()!!.vertexSize set(value) { this.ifGeometry { vertexSize = value } } @Deprecated(message = "Moved to attribute geometry(), see AttributesExample for usage details", replaceWith = ReplaceWith("geometry().texcoordSize")) var texcoordSize: Int get() = this.geometryOrNull()!!.texcoordSize set(value) { this.ifGeometry { texcoordSize = value } } @Deprecated(message = "Moved to attribute geometry(), see AttributesExample for usage details", replaceWith = ReplaceWith("geometry().geometryType")) var geometryType: GeometryType get() = this.geometryOrNull()!!.geometryType set(value) { this.ifGeometry { geometryType = value } } @Deprecated(message = "Moved to attribute geometry(), see AttributesExample for usage details", replaceWith = ReplaceWith("geometry().vertices")) var vertices: FloatBuffer get() = this.geometryOrNull()!!.vertices set(value) { this.ifGeometry { vertices = value } } @Deprecated(message = "Moved to attribute geometry(), see AttributesExample for usage details", replaceWith = ReplaceWith("geometry().normals")) var normals: FloatBuffer get() = this.geometryOrNull()!!.normals set(value) { this.ifGeometry { normals = value } } @Deprecated(message = "Moved to attribute geometry(), see AttributesExample for usage details", replaceWith = ReplaceWith("geometry().texcoords")) var texcoords: FloatBuffer get() = this.geometryOrNull()!!.texcoords set(value) { this.ifGeometry { texcoords = value } } @Deprecated(message = "Moved to attribute geometry(), see AttributesExample for usage details", replaceWith = ReplaceWith("geometry().indices")) var indices: IntBuffer get() = this.geometryOrNull()!!.indices set(value) { this.ifGeometry { indices = value } } @Deprecated(message = "Moved to attribute geometry(), see AttributesExample for usage details", replaceWith = ReplaceWith("geometry().recalculateNormals()")) fun recalculateNormals() { ifGeometry { recalculateNormals() } } }
lgpl-3.0
9d72efb3cf8e0ce6f0c4b02ca1e899ae
39.983129
187
0.650051
4.671503
false
false
false
false
google/android-fhir
engine/src/main/java/com/google/android/fhir/MoreResources.kt
1
2678
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir import java.lang.reflect.InvocationTargetException import org.hl7.fhir.r4.model.Resource import org.hl7.fhir.r4.model.ResourceType /** The HAPI Fhir package prefix for R4 resources. */ internal const val R4_RESOURCE_PACKAGE_PREFIX = "org.hl7.fhir.r4.model." /** * Returns the FHIR resource type. * * @throws IllegalArgumentException if class name cannot be mapped to valid resource type */ fun <R : Resource> getResourceType(clazz: Class<R>): ResourceType { try { return clazz.getConstructor().newInstance().resourceType } catch (e: NoSuchMethodException) { throw IllegalArgumentException("Cannot resolve resource type for " + clazz.name, e) } catch (e: IllegalAccessException) { throw IllegalArgumentException("Cannot resolve resource type for " + clazz.name, e) } catch (e: InstantiationException) { throw IllegalArgumentException("Cannot resolve resource type for " + clazz.name, e) } catch (e: InvocationTargetException) { throw IllegalArgumentException("Cannot resolve resource type for " + clazz.name, e) } } /** Returns the {@link Class} object for the resource type. */ fun <R : Resource> getResourceClass(resourceType: ResourceType): Class<R> = getResourceClass(resourceType.name) /** Returns the {@link Class} object for the resource type. */ fun <R : Resource> getResourceClass(resourceType: String): Class<R> { // Remove any curly brackets in the resource type string. This is to work around an issue with // JSON deserialization in the CQL engine on Android. The resource type string incorrectly // includes namespace prefix in curly brackets, e.g. "{http://hl7.org/fhir}Patient" instead of // "Patient". // TODO: remove this once a fix has been found for the CQL engine on Android. val className = resourceType.replace(Regex("\\{[^}]*\\}"), "") return Class.forName(R4_RESOURCE_PACKAGE_PREFIX + className) as Class<R> } internal val Resource.versionId get() = meta.versionId internal val Resource.lastUpdated get() = if (hasMeta()) meta.lastUpdated?.toInstant() else null
apache-2.0
d6f81a84ea44c647480316f1febd4e10
40.84375
96
0.738237
4.151938
false
false
false
false
Kerooker/rpg-npc-generator
app/src/main/java/me/kerooker/rpgnpcgenerator/repository/model/persistence/admob/AdmobRepository.kt
1
774
package me.kerooker.rpgnpcgenerator.repository.model.persistence.admob import android.content.Context import com.tencent.mmkv.MMKV import java.util.Date class AdmobRepository( context: Context ) { init { MMKV.initialize(context) } private val kv = MMKV.defaultMMKV() private val now = Date().time var stopSuggestingRemovalUntil: Long get() = kv.getLong("stopSuggestingRemovalUntil", now + FIVE_SECONDS_MILLIS) set(value) { kv.putLong("stopSuggestingRemovalUntil", value) } var stopAdsUntil: Long get() = kv.getLong("stopAdsUntil", Date().time) set(value) { kv.putLong("stopAdsUntil", value) } } private const val FIVE_SECONDS_MILLIS = 5_000
apache-2.0
a5afae774236a928004006dd3a83baa0
23.967742
84
0.644703
3.73913
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/readinglist/ReadingListBehaviorsUtil.kt
1
15871
package org.wikipedia.readinglist import android.app.Activity import android.content.DialogInterface import android.icu.text.ListFormatter import android.os.Build import android.text.Spanned import androidx.appcompat.app.AlertDialog import kotlinx.coroutines.* import org.apache.commons.lang3.StringUtils import org.wikipedia.Constants.InvokeSource import org.wikipedia.R import org.wikipedia.analytics.ReadingListsFunnel import org.wikipedia.page.PageTitle import org.wikipedia.readinglist.database.ReadingList import org.wikipedia.readinglist.database.ReadingListDbHelper import org.wikipedia.readinglist.database.ReadingListPage import org.wikipedia.settings.Prefs import org.wikipedia.util.DeviceUtil import org.wikipedia.util.FeedbackUtil import org.wikipedia.util.StringUtil import org.wikipedia.util.log.L import org.wikipedia.views.CircularProgressBar.Companion.MIN_PROGRESS import java.util.* object ReadingListBehaviorsUtil { fun interface SearchCallback { fun onCompleted(lists: MutableList<Any>) } fun interface SnackbarCallback { fun onUndoDeleteClicked() } fun interface AddToDefaultListCallback { fun onMoveClicked(readingListId: Long) } fun interface Callback { fun onCompleted() } private var allReadingLists = listOf<ReadingList>() // Kotlin coroutine private val dispatcher: CoroutineDispatcher = Dispatchers.IO private val scope = CoroutineScope(Dispatchers.Main) private val exceptionHandler = CoroutineExceptionHandler { _, exception -> L.w(exception) } fun getListsContainPage(readingListPage: ReadingListPage) = allReadingLists.filter { list -> list.pages.any { it.displayTitle == readingListPage.displayTitle } } fun savePagesForOffline(activity: Activity, selectedPages: List<ReadingListPage>, callback: Callback) { if (Prefs.isDownloadOnlyOverWiFiEnabled() && !DeviceUtil.isOnWiFi()) { showMobileDataWarningDialog(activity) { _, _ -> savePagesForOffline(activity, selectedPages, true) callback.onCompleted() } } else { savePagesForOffline(activity, selectedPages, !Prefs.isDownloadingReadingListArticlesEnabled()) callback.onCompleted() } } private fun savePagesForOffline(activity: Activity, selectedPages: List<ReadingListPage>, forcedSave: Boolean) { if (selectedPages.isNotEmpty()) { for (page in selectedPages) { resetPageProgress(page) } ReadingListDbHelper.markPagesForOffline(selectedPages, true, forcedSave) showMultiSelectOfflineStateChangeSnackbar(activity, selectedPages, true) } } fun removePagesFromOffline(activity: Activity, selectedPages: List<ReadingListPage>, callback: Callback) { if (selectedPages.isNotEmpty()) { ReadingListDbHelper.markPagesForOffline(selectedPages, false, false) showMultiSelectOfflineStateChangeSnackbar(activity, selectedPages, false) callback.onCompleted() } } fun deleteReadingList(activity: Activity, readingList: ReadingList?, showDialog: Boolean, callback: Callback) { if (readingList == null) { return } if (showDialog) { AlertDialog.Builder(activity) .setMessage(activity.getString(R.string.reading_list_delete_confirm, readingList.title)) .setPositiveButton(R.string.reading_list_delete_dialog_ok_button_text) { _, _ -> ReadingListDbHelper.deleteList(readingList) ReadingListDbHelper.markPagesForDeletion(readingList, readingList.pages, false) callback.onCompleted() } .setNegativeButton(R.string.reading_list_delete_dialog_cancel_button_text, null) .create() .show() } else { ReadingListDbHelper.deleteList(readingList) ReadingListDbHelper.markPagesForDeletion(readingList, readingList.pages, false) callback.onCompleted() } } fun deletePages(activity: Activity, listsContainPage: List<ReadingList>, readingListPage: ReadingListPage, snackbarCallback: SnackbarCallback, callback: Callback) { if (listsContainPage.size > 1) { scope.launch(exceptionHandler) { val pages = withContext(dispatcher) { ReadingListDbHelper.getAllPageOccurrences(ReadingListPage.toPageTitle(readingListPage)) } val lists = withContext(dispatcher) { ReadingListDbHelper.getListsFromPageOccurrences(pages) } RemoveFromReadingListsDialog(lists).deleteOrShowDialog(activity) { list, page -> showDeletePageFromListsUndoSnackbar(activity, list, page, snackbarCallback) callback.onCompleted() } } } else { ReadingListDbHelper.markPagesForDeletion(listsContainPage[0], listOf(readingListPage)) listsContainPage[0].pages.remove(readingListPage) showDeletePagesUndoSnackbar(activity, listsContainPage[0], listOf(readingListPage), snackbarCallback) callback.onCompleted() } } fun renameReadingList(activity: Activity, readingList: ReadingList?, callback: Callback) { if (readingList == null) { return } else if (readingList.isDefault) { L.w("Attempted to rename default list.") return } val tempLists = ReadingListDbHelper.allListsWithoutContents val existingTitles = ArrayList<String>() for (list in tempLists) { existingTitles.add(list.title) } existingTitles.remove(readingList.title) ReadingListTitleDialog.readingListTitleDialog(activity, readingList.title, readingList.description, existingTitles) { text, description -> readingList.dbTitle = text readingList.description = description readingList.dirty = true ReadingListDbHelper.updateList(readingList, true) callback.onCompleted() }.show() } private fun showDeletePageFromListsUndoSnackbar(activity: Activity, lists: List<ReadingList>?, page: ReadingListPage, callback: SnackbarCallback) { if (lists == null) { return } val readingListNames = lists.map { it.title }.run { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { ListFormatter.getInstance().format(this) } else { joinToString(separator = ", ") } } FeedbackUtil.makeSnackbar(activity, activity.getString(R.string.reading_list_item_deleted_from_list, page.displayTitle, readingListNames), FeedbackUtil.LENGTH_DEFAULT) .setAction(R.string.reading_list_item_delete_undo) { ReadingListDbHelper.addPageToLists(lists, page, true) callback.onUndoDeleteClicked() } .show() } fun showDeletePagesUndoSnackbar(activity: Activity, readingList: ReadingList?, pages: List<ReadingListPage>, callback: SnackbarCallback) { if (readingList == null) { return } FeedbackUtil .makeSnackbar(activity, if (pages.size == 1) activity.getString(R.string.reading_list_item_deleted_from_list, pages[0].displayTitle, readingList.title) else activity.resources.getQuantityString(R.plurals.reading_list_articles_deleted_from_list, pages.size, pages.size, readingList.title), FeedbackUtil.LENGTH_DEFAULT) .setAction(R.string.reading_list_item_delete_undo) { val newPages = ArrayList<ReadingListPage>() for (page in pages) { newPages.add(ReadingListPage(ReadingListPage.toPageTitle(page))) } ReadingListDbHelper.addPagesToList(readingList, newPages, true) readingList.pages.addAll(newPages) callback.onUndoDeleteClicked() } .show() } fun showDeleteListUndoSnackbar(activity: Activity, readingList: ReadingList?, callback: SnackbarCallback) { if (readingList == null) { return } FeedbackUtil .makeSnackbar(activity, activity.getString(R.string.reading_list_deleted, readingList.title), FeedbackUtil.LENGTH_DEFAULT) .setAction(R.string.reading_list_item_delete_undo) { val newList = ReadingListDbHelper.createList(readingList.title, readingList.description) val newPages = ArrayList<ReadingListPage>() for (page in readingList.pages) { newPages.add(ReadingListPage(ReadingListPage.toPageTitle(page))) } ReadingListDbHelper.addPagesToList(newList, newPages, true) callback.onUndoDeleteClicked() } .show() } fun togglePageOffline(activity: Activity, page: ReadingListPage?, callback: Callback) { if (page == null) { return } if (page.offline) { scope.launch(exceptionHandler) { val pages = withContext(dispatcher) { ReadingListDbHelper.getAllPageOccurrences(ReadingListPage.toPageTitle(page)) } val lists = withContext(dispatcher) { ReadingListDbHelper.getListsFromPageOccurrences(pages) } if (lists.size > 1) { val dialog = AlertDialog.Builder(activity) .setTitle(R.string.reading_list_confirm_remove_article_from_offline_title) .setMessage(getConfirmToggleOfflineMessage(activity, page, lists)) .setPositiveButton(R.string.reading_list_confirm_remove_article_from_offline) { _, _ -> toggleOffline(activity, page, callback) } .setNegativeButton(R.string.reading_list_remove_from_offline_cancel_button_text, null) .create() dialog.show() } else { toggleOffline(activity, page, callback) } } } else { toggleOffline(activity, page, callback) } } fun toggleOffline(activity: Activity, page: ReadingListPage, callback: Callback) { resetPageProgress(page) if (Prefs.isDownloadOnlyOverWiFiEnabled() && !DeviceUtil.isOnWiFi()) { showMobileDataWarningDialog(activity) { _, _ -> toggleOffline(activity, page, true) callback.onCompleted() } } else { toggleOffline(activity, page, !Prefs.isDownloadingReadingListArticlesEnabled()) callback.onCompleted() } } fun addToDefaultList(activity: Activity, title: PageTitle, invokeSource: InvokeSource, addToDefaultListCallback: AddToDefaultListCallback) { addToDefaultList(activity, title, invokeSource, addToDefaultListCallback, null) } fun addToDefaultList(activity: Activity, title: PageTitle, invokeSource: InvokeSource, addToDefaultListCallback: AddToDefaultListCallback, callback: Callback?) { val defaultList = ReadingListDbHelper.defaultList scope.launch(exceptionHandler) { val addedTitles = withContext(dispatcher) { ReadingListDbHelper.addPagesToListIfNotExist(defaultList, listOf(title)) } if (addedTitles.isNotEmpty()) { ReadingListsFunnel().logAddToList(defaultList, 1, invokeSource) FeedbackUtil.makeSnackbar(activity, activity.getString(R.string.reading_list_article_added_to_default_list, title.displayText), FeedbackUtil.LENGTH_DEFAULT) .setAction(R.string.reading_list_add_to_list_button) { addToDefaultListCallback.onMoveClicked(defaultList.id) }.show() callback?.onCompleted() } } } private fun toggleOffline(activity: Activity, page: ReadingListPage, forcedSave: Boolean) { ReadingListDbHelper.markPageForOffline(page, !page.offline, forcedSave) FeedbackUtil.showMessage(activity, activity.resources.getQuantityString( if (page.offline) R.plurals.reading_list_article_offline_message else R.plurals.reading_list_article_not_offline_message, 1)) } private fun showMobileDataWarningDialog(activity: Activity, listener: DialogInterface.OnClickListener) { AlertDialog.Builder(activity) .setTitle(R.string.dialog_title_download_only_over_wifi) .setMessage(R.string.dialog_text_download_only_over_wifi) .setPositiveButton(R.string.dialog_title_download_only_over_wifi_allow, listener) .setNegativeButton(R.string.reading_list_download_using_mobile_data_cancel_button_text, null) .show() } private fun showMultiSelectOfflineStateChangeSnackbar(activity: Activity, pages: List<ReadingListPage>, offline: Boolean) { FeedbackUtil.showMessage(activity, activity.resources.getQuantityString( if (offline) R.plurals.reading_list_article_offline_message else R.plurals.reading_list_article_not_offline_message, pages.size )) } private fun resetPageProgress(page: ReadingListPage) { if (!page.offline) { page.downloadProgress = MIN_PROGRESS } } private fun getConfirmToggleOfflineMessage(activity: Activity, page: ReadingListPage, lists: List<ReadingList>): Spanned { var result = activity.getString(R.string.reading_list_confirm_remove_article_from_offline_message, "<b>${page.displayTitle}</b>") lists.forEach { result += "<br>&nbsp;&nbsp;<b>&#8226; ${it.title}</b>" } return StringUtil.fromHtml(result) } fun searchListsAndPages(searchQuery: String?, callback: SearchCallback) { scope.launch(exceptionHandler) { allReadingLists = withContext(dispatcher) { ReadingListDbHelper.allLists } val list = withContext(dispatcher) { applySearchQuery(searchQuery, allReadingLists) } if (searchQuery.isNullOrEmpty()) { ReadingList.sortGenericList(list, Prefs.getReadingListSortMode(ReadingList.SORT_BY_NAME_ASC)) } callback.onCompleted(list) } } private fun applySearchQuery(searchQuery: String?, lists: List<ReadingList>): MutableList<Any> { val result = mutableListOf<Any>() if (searchQuery.isNullOrEmpty()) { result.addAll(lists) return result } val normalizedQuery = StringUtils.stripAccents(searchQuery).toLowerCase(Locale.getDefault()) var lastListItemIndex = 0 lists.forEach { list -> if (StringUtils.stripAccents(list.title).toLowerCase(Locale.getDefault()).contains(normalizedQuery)) { result.add(lastListItemIndex++, list) } list.pages.forEach { page -> if (page.displayTitle.toLowerCase(Locale.getDefault()).contains(normalizedQuery)) { var noMatch = true result.forEach checkMatch@{ if (it is ReadingListPage && it.displayTitle == page.displayTitle) { noMatch = false return@checkMatch } } if (noMatch) { result.add(page) } } } } return result } }
apache-2.0
80406154eb00fb1451e349dc6c2f54fe
45.817109
172
0.640224
4.953496
false
false
false
false
securityfirst/Umbrella_android
app/src/main/java/org/secfirst/umbrella/feature/checklist/view/controller/HostChecklistController.kt
1
2743
package org.secfirst.umbrella.feature.checklist.view.controller import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bluelinelabs.conductor.RouterTransaction import kotlinx.android.synthetic.main.host_checklist.* import kotlinx.android.synthetic.main.host_checklist.view.* import org.secfirst.umbrella.R import org.secfirst.umbrella.UmbrellaApplication import org.secfirst.umbrella.data.database.checklist.Checklist import org.secfirst.umbrella.feature.base.view.BaseController import org.secfirst.umbrella.feature.checklist.DaggerChecklistComponent import org.secfirst.umbrella.feature.checklist.interactor.ChecklistBaseInteractor import org.secfirst.umbrella.feature.checklist.presenter.ChecklistBasePresenter import org.secfirst.umbrella.feature.checklist.view.ChecklistView import org.secfirst.umbrella.feature.checklist.view.adapter.HostChecklistAdapter import javax.inject.Inject class HostChecklistController(bundle: Bundle) : BaseController(bundle), ChecklistView { @Inject internal lateinit var presenter: ChecklistBasePresenter<ChecklistView, ChecklistBaseInteractor> private val uriString by lazy { args.getString(EXTRA_ENABLE_DEEP_LINK_CHECKLIST) ?: "" } constructor(uri: String = "") : this(Bundle().apply { putString(EXTRA_ENABLE_DEEP_LINK_CHECKLIST, uri) }) override fun onInject() { DaggerChecklistComponent.builder() .application(UmbrellaApplication.instance) .build() .inject(this) } override fun onAttach(view: View) { hostChecklistPager?.adapter = HostChecklistAdapter(this) hostChecklistTab?.setupWithViewPager(hostChecklistPager) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View { val view = inflater.inflate(R.layout.host_checklist, container, false) presenter.onAttach(this) if (uriString.isNotBlank()) presenter.submitChecklistById(uriString) view.toolbar.let { mainActivity.setSupportActionBar(it) mainActivity.supportActionBar?.title = context.getString(R.string.checklist_title) } mainActivity.navigationPositionToCenter() return view } override fun onDestroyView(view: View) { hostChecklistPager?.adapter = null hostChecklistTab?.setupWithViewPager(null) super.onDestroyView(view) } companion object { private const val EXTRA_ENABLE_DEEP_LINK_CHECKLIST = "deeplink" } override fun getChecklist(checklist: Checklist) { router.pushController(RouterTransaction.with(ChecklistController(checklist.id))) } }
gpl-3.0
2d33f9eae63aa92a2bf5c90d88bad179
38.185714
110
0.752461
4.688889
false
false
false
false
openium/auvergne-webcams-droid
app/src/main/java/fr/openium/auvergnewebcams/ui/main/AdapterMainSections.kt
1
6446
package fr.openium.auvergnewebcams.ui.main import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.PagerSnapHelper import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.leochuan.ScaleLayoutManager import fr.openium.auvergnewebcams.R import fr.openium.auvergnewebcams.custom.CustomScaleLayoutManager import fr.openium.auvergnewebcams.custom.SnapOnScrollListener import fr.openium.auvergnewebcams.ext.attachSnapHelperWithListener import fr.openium.auvergnewebcams.model.entity.Webcam import fr.openium.auvergnewebcams.utils.DateUtils import fr.openium.auvergnewebcams.utils.PreferencesUtils import fr.openium.kotlintools.ext.dip import kotlinx.android.synthetic.main.header_section.view.* import kotlinx.android.synthetic.main.item_section.view.* /** * Created by Openium on 19/02/2019. */ class AdapterMainSections( private val prefUtils: PreferencesUtils, private val dateUtils: DateUtils, private var data: List<Data>, private val onHeaderClicked: ((Pair<Long, String>) -> Unit), private val onItemClicked: ((Webcam) -> Unit) ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { companion object { const val HEADER_VIEW_TYPE = 0 const val ITEM_VIEW_TYPE = 1 } private val viewPool = RecyclerView.RecycledViewPool().apply { setMaxRecycledViews(0, 30) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(parent.context) return when (viewType) { HEADER_VIEW_TYPE -> HeaderHolder(inflater.inflate(R.layout.header_section, parent, false)) ITEM_VIEW_TYPE -> ItemHolder(inflater.inflate(R.layout.item_section, parent, false)) else -> error("Unknown view type $viewType") } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is HeaderHolder -> holder.bindView(data[position].header, onHeaderClicked) is ItemHolder -> holder.bindView(data[position].webcams, onItemClicked, viewPool, prefUtils, dateUtils) else -> { // Nothing to do } } } override fun getItemViewType(position: Int): Int = if (data[position].header != null) HEADER_VIEW_TYPE else ITEM_VIEW_TYPE override fun getItemCount(): Int = data.count() fun refreshData(dataList: List<Data>) { data = dataList notifyDataSetChanged() } class HeaderHolder(view: View) : RecyclerView.ViewHolder(view) { fun bindView(dataHeader: DataHeader?, onHeaderClicked: (Pair<Long, String>) -> Unit) { dataHeader?.let { header -> // Set section title itemView.textViewSectionName.text = header.title // Set the right section icon Glide.with(itemView.context) .load(header.imageId) .transition(DrawableTransitionOptions.withCrossFade()) .into(itemView.imageViewSection) // Set the number of camera to show in the subtitle itemView.textViewSectionNbCameras.text = header.nbWebCamsString // Set on click on Section part itemView.linearLayoutSection.setOnClickListener { onHeaderClicked.invoke(header.sectionId to header.title) } } } } class ItemHolder(view: View) : RecyclerView.ViewHolder(view) { fun bindView( webcamList: List<Webcam>?, onItemClicked: (Webcam) -> Unit, viewPool: RecyclerView.RecycledViewPool, prefUtils: PreferencesUtils, dateUtils: DateUtils ) { webcamList?.let { webcams -> // Create and set adapter only if this is not already done if (itemView.recyclerViewWebcams.adapter == null) { // Applying all settings to the RecyclerView itemView.recyclerViewWebcams.apply { adapter = AdapterMainSectionWebcams(prefUtils, dateUtils, Glide.with(itemView.context), webcams, onItemClicked) layoutManager = CustomScaleLayoutManager(itemView.context, dip(-40f).toInt(), 5f, ScaleLayoutManager.HORIZONTAL).apply { minScale = 0.7f minAlpha = 0.3f maxAlpha = 1f maxVisibleItemCount = 3 infinite = true enableBringCenterToFront = true setItemViewCacheSize(0) recycleChildrenOnDetach = true } // Some optimization setHasFixedSize(true) setRecycledViewPool(viewPool) } } else { itemView.recyclerViewWebcams.also { // Remove all previous listeners it.clearOnScrollListeners() it.onFlingListener = null // Update webcams list (it.adapter as AdapterMainSectionWebcams).refreshData(webcams) } } // This is needed to scroll 1 by 1, and get notified about position changing itemView.recyclerViewWebcams.attachSnapHelperWithListener( PagerSnapHelper(), SnapOnScrollListener.Behavior.NOTIFY_ON_SCROLL, object : SnapOnScrollListener.OnSnapPositionChangeListener { override fun onSnapPositionChange(position: Int) { itemView.textViewWebcamName.text = webcams[position % webcams.count()].title } } ) } } } data class Data( val header: DataHeader? = null, val webcams: List<Webcam>? = null ) data class DataHeader(val sectionId: Long, val title: String, val imageId: Int, val nbWebCamsString: String) }
mit
831dda503d69cf49e69e9cd70b8434ee
40.063694
135
0.601458
5.194198
false
false
false
false
paplorinc/intellij-community
java/debugger/memory-agent/src/com/intellij/debugger/memory/agent/extractor/AgentExtractor.kt
1
1040
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.debugger.memory.agent.extractor import com.intellij.openapi.util.io.FileUtil import org.apache.commons.io.FileUtils import java.io.File import java.io.FileNotFoundException class AgentExtractor { fun extract(agentType: AgentLibraryType, directory: File): File { val file = FileUtil.createTempFile(directory, "${agentType.prefix}memory_agent", agentType.suffix, true) val agentFileName = "${agentType.prefix}memory_agent${agentType.suffix}" val inputStream = AgentExtractor::class.java.classLoader.getResourceAsStream("bin/$agentFileName") if (inputStream == null) throw FileNotFoundException(agentFileName) FileUtils.copyToFile(inputStream, file) return file } enum class AgentLibraryType(val prefix: String, val suffix: String) { WINDOWS32("", "32.dll"), WINDOWS64("", ".dll"), LINUX("lib", ".so"), MACOS("lib", ".dylib") } }
apache-2.0
0e329e3f984a51fef91676b3e5dacc22
40.6
140
0.742308
4.094488
false
false
false
false
paplorinc/intellij-community
plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalUsageCollector.kt
1
3456
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.terminal import com.intellij.internal.statistic.collectors.fus.os.OsVersionUsageCollector import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger import com.intellij.internal.statistic.service.fus.collectors.FUSUsageContext import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfo import com.intellij.util.PathUtil import java.util.* class TerminalUsageTriggerCollector { companion object { @Deprecated("To be removed") @JvmStatic fun trigger(project: Project, featureId: String, context: FUSUsageContext) { FUCounterUsageLogger.getInstance().logEvent(project, GROUP_ID, featureId, FeatureUsageData().addFeatureContext(context)) } @JvmStatic fun triggerSshShellStarted(project: Project) { FUCounterUsageLogger.getInstance().logEvent(project, GROUP_ID, "ssh.exec", FeatureUsageData().addOS()) } @JvmStatic fun triggerLocalShellStarted(project: Project, shellCommand: Array<String>) { val osVersion = OsVersionUsageCollector.parse(SystemInfo.OS_VERSION) FUCounterUsageLogger.getInstance().logEvent(project, GROUP_ID, "local.exec", FeatureUsageData() .addOS() .addData("os-version", if (osVersion == null) "unknown" else osVersion.toCompactString()) .addData("shell", getShellNameForStat(shellCommand.firstOrNull())) ) } @JvmStatic private fun getShellNameForStat(shellName: String?): String { if (shellName == null) return "unspecified" var name = shellName.trimStart() val ind = name.indexOf(" ") name = if (ind < 0) name else name.substring(0, ind) if (SystemInfo.isFileSystemCaseSensitive) { name = name.toLowerCase(Locale.ENGLISH) } name = PathUtil.getFileName(name) name = trimKnownExt(name) return if (KNOWN_SHELLS.contains(name)) name else "other" } private fun trimKnownExt(name: String): String { val ext = PathUtil.getFileExtension(name) return if (ext != null && KNOWN_EXTENSIONS.contains(ext)) name.substring(0, name.length - ext.length - 1) else name } } } private const val GROUP_ID = "terminalShell" private val KNOWN_SHELLS = setOf("activate", "anaconda3", "bash", "cexec", "cmd", "cmder", "cmder_shell", "cygwin", "fish", "git", "git-bash", "git-cmd", "init", "miniconda3", "msys2_shell", "powershell", "pwsh", "sh", "tcsh", "ubuntu", "ubuntu1804", "wsl", "zsh") private val KNOWN_EXTENSIONS = setOf("exe", "bat", "cmd")
apache-2.0
c35f04858fa6d72a8d7308b264207b44
41.146341
140
0.56684
4.88826
false
false
false
false
square/okhttp
okhttp/src/jvmTest/java/okhttp3/RequestTest.kt
2
16712
/* * Copyright (C) 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 okhttp3 import java.io.File import java.io.FileWriter import java.net.URI import java.util.UUID import okhttp3.Headers.Companion.headersOf import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.RequestBody.Companion.toRequestBody import okio.Buffer import okio.ByteString.Companion.encodeUtf8 import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.junit.jupiter.api.Test class RequestTest { @Test fun constructor() { val url = "https://example.com/".toHttpUrl() val body = "hello".toRequestBody() val headers = headersOf("User-Agent", "RequestTest") val method = "PUT" val request = Request( url = url, headers = headers, method = method, body = body ) assertThat(request.url).isEqualTo(url) assertThat(request.headers).isEqualTo(headers) assertThat(request.method).isEqualTo(method) assertThat(request.body).isEqualTo(body) assertThat(request.tags).isEmpty() } @Test fun constructorNoBodyNoMethod() { val url = "https://example.com/".toHttpUrl() val headers = headersOf("User-Agent", "RequestTest") val request = Request( url = url, headers = headers, ) assertThat(request.url).isEqualTo(url) assertThat(request.headers).isEqualTo(headers) assertThat(request.method).isEqualTo("GET") assertThat(request.body).isNull() assertThat(request.tags).isEmpty() } @Test fun constructorNoMethod() { val url = "https://example.com/".toHttpUrl() val body = "hello".toRequestBody() val headers = headersOf("User-Agent", "RequestTest") val request = Request( url = url, headers = headers, body = body ) assertThat(request.url).isEqualTo(url) assertThat(request.headers).isEqualTo(headers) assertThat(request.method).isEqualTo("POST") assertThat(request.body).isEqualTo(body) assertThat(request.tags).isEmpty() } @Test fun constructorNoBody() { val url = "https://example.com/".toHttpUrl() val headers = headersOf("User-Agent", "RequestTest") val method = "DELETE" val request = Request( url = url, headers = headers, method = method, ) assertThat(request.url).isEqualTo(url) assertThat(request.headers).isEqualTo(headers) assertThat(request.method).isEqualTo(method) assertThat(request.body).isNull() assertThat(request.tags).isEmpty() } @Test fun string() { val contentType = "text/plain; charset=utf-8".toMediaType() val body = "abc".toByteArray().toRequestBody(contentType) assertThat(body.contentType()).isEqualTo(contentType) assertThat(body.contentLength()).isEqualTo(3) assertThat(bodyToHex(body)).isEqualTo("616263") assertThat(bodyToHex(body)) .overridingErrorMessage("Retransmit body") .isEqualTo("616263") } @Test fun stringWithDefaultCharsetAdded() { val contentType = "text/plain".toMediaType() val body = "\u0800".toRequestBody(contentType) assertThat(body.contentType()).isEqualTo("text/plain; charset=utf-8".toMediaType()) assertThat(body.contentLength()).isEqualTo(3) assertThat(bodyToHex(body)).isEqualTo("e0a080") } @Test fun stringWithNonDefaultCharsetSpecified() { val contentType = "text/plain; charset=utf-16be".toMediaType() val body = "\u0800".toRequestBody(contentType) assertThat(body.contentType()).isEqualTo(contentType) assertThat(body.contentLength()).isEqualTo(2) assertThat(bodyToHex(body)).isEqualTo("0800") } @Test fun byteArray() { val contentType = "text/plain".toMediaType() val body: RequestBody = "abc".toByteArray().toRequestBody(contentType) assertThat(body.contentType()).isEqualTo(contentType) assertThat(body.contentLength()).isEqualTo(3) assertThat(bodyToHex(body)).isEqualTo("616263") assertThat(bodyToHex(body)) .overridingErrorMessage("Retransmit body") .isEqualTo("616263") } @Test fun byteArrayRange() { val contentType = "text/plain".toMediaType() val body: RequestBody = ".abcd".toByteArray().toRequestBody(contentType, 1, 3) assertThat(body.contentType()).isEqualTo(contentType) assertThat(body.contentLength()).isEqualTo(3) assertThat(bodyToHex(body)).isEqualTo("616263") assertThat(bodyToHex(body)) .overridingErrorMessage("Retransmit body") .isEqualTo("616263") } @Test fun byteString() { val contentType = "text/plain".toMediaType() val body: RequestBody = "Hello".encodeUtf8().toRequestBody(contentType) assertThat(body.contentType()).isEqualTo(contentType) assertThat(body.contentLength()).isEqualTo(5) assertThat(bodyToHex(body)).isEqualTo("48656c6c6f") assertThat(bodyToHex(body)) .overridingErrorMessage("Retransmit body") .isEqualTo("48656c6c6f") } @Test fun file() { val file = File.createTempFile("RequestTest", "tmp") val writer = FileWriter(file) writer.write("abc") writer.close() val contentType = "text/plain".toMediaType() val body: RequestBody = file.asRequestBody(contentType) assertThat(body.contentType()).isEqualTo(contentType) assertThat(body.contentLength()).isEqualTo(3) assertThat(bodyToHex(body)).isEqualTo("616263") assertThat(bodyToHex(body)) .overridingErrorMessage("Retransmit body") .isEqualTo("616263") } /** Common verbs used for apis such as GitHub, AWS, and Google Cloud. */ @Test fun crudVerbs() { val contentType = "application/json".toMediaType() val body = "{}".toRequestBody(contentType) val get = Request.Builder().url("http://localhost/api").get().build() assertThat(get.method).isEqualTo("GET") assertThat(get.body).isNull() val head = Request.Builder().url("http://localhost/api").head().build() assertThat(head.method).isEqualTo("HEAD") assertThat(head.body).isNull() val delete = Request.Builder().url("http://localhost/api").delete().build() assertThat(delete.method).isEqualTo("DELETE") assertThat(delete.body!!.contentLength()).isEqualTo(0L) val post = Request.Builder().url("http://localhost/api").post(body).build() assertThat(post.method).isEqualTo("POST") assertThat(post.body).isEqualTo(body) val put = Request.Builder().url("http://localhost/api").put(body).build() assertThat(put.method).isEqualTo("PUT") assertThat(put.body).isEqualTo(body) val patch = Request.Builder().url("http://localhost/api").patch(body).build() assertThat(patch.method).isEqualTo("PATCH") assertThat(patch.body).isEqualTo(body) } @Test fun uninitializedURI() { val request = Request.Builder().url("http://localhost/api").build() assertThat(request.url.toUri()).isEqualTo(URI("http://localhost/api")) assertThat(request.url).isEqualTo("http://localhost/api".toHttpUrl()) } @Test fun newBuilderUrlResetsUrl() { val requestWithoutCache = Request.Builder().url("http://localhost/api").build() val builtRequestWithoutCache = requestWithoutCache.newBuilder().url("http://localhost/api/foo").build() assertThat(builtRequestWithoutCache.url).isEqualTo( "http://localhost/api/foo".toHttpUrl()) val requestWithCache = Request.Builder() .url("http://localhost/api") .build() // cache url object requestWithCache.url val builtRequestWithCache = requestWithCache.newBuilder() .url("http://localhost/api/foo") .build() assertThat(builtRequestWithCache.url) .isEqualTo("http://localhost/api/foo".toHttpUrl()) } @Test fun cacheControl() { val request = Request.Builder() .cacheControl(CacheControl.Builder().noCache().build()) .url("https://square.com") .build() assertThat(request.headers("Cache-Control")).containsExactly("no-cache") assertThat(request.cacheControl.noCache).isTrue } @Test fun emptyCacheControlClearsAllCacheControlHeaders() { val request = Request.Builder() .header("Cache-Control", "foo") .cacheControl(CacheControl.Builder().build()) .url("https://square.com") .build() assertThat(request.headers("Cache-Control")).isEmpty() } @Test fun headerAcceptsPermittedCharacters() { val builder = Request.Builder() builder.header("AZab09~", "AZab09 ~") builder.addHeader("AZab09~", "AZab09 ~") } @Test fun emptyNameForbidden() { val builder = Request.Builder() try { builder.header("", "Value") fail("") } catch (expected: IllegalArgumentException) { } try { builder.addHeader("", "Value") fail("") } catch (expected: IllegalArgumentException) { } } @Test fun headerAllowsTabOnlyInValues() { val builder = Request.Builder() builder.header("key", "sample\tvalue") try { builder.header("sample\tkey", "value") fail("") } catch (expected: IllegalArgumentException) { } } @Test fun headerForbidsControlCharacters() { assertForbiddenHeader("\u0000") assertForbiddenHeader("\r") assertForbiddenHeader("\n") assertForbiddenHeader("\u001f") assertForbiddenHeader("\u007f") assertForbiddenHeader("\u0080") assertForbiddenHeader("\ud83c\udf69") } private fun assertForbiddenHeader(s: String) { val builder = Request.Builder() try { builder.header(s, "Value") fail("") } catch (expected: IllegalArgumentException) { } try { builder.addHeader(s, "Value") fail("") } catch (expected: IllegalArgumentException) { } try { builder.header("Name", s) fail("") } catch (expected: IllegalArgumentException) { } try { builder.addHeader("Name", s) fail("") } catch (expected: IllegalArgumentException) { } } @Test fun noTag() { val request = Request.Builder() .url("https://square.com") .build() assertThat(request.tag()).isNull() assertThat(request.tag(Any::class.java)).isNull() assertThat(request.tag(UUID::class.java)).isNull() assertThat(request.tag(String::class.java)).isNull() // Alternate access APIs also work. assertThat(request.tag<String>()).isNull() assertThat(request.tag(String::class)).isNull() } @Test fun defaultTag() { val tag = UUID.randomUUID() val request = Request.Builder() .url("https://square.com") .tag(tag) .build() assertThat(request.tag()).isSameAs(tag) assertThat(request.tag(Any::class.java)).isSameAs(tag) assertThat(request.tag(UUID::class.java)).isNull() assertThat(request.tag(String::class.java)).isNull() // Alternate access APIs also work. assertThat(request.tag<Any>()).isSameAs(tag) assertThat(request.tag(Any::class)).isSameAs(tag) } @Test fun nullRemovesTag() { val request = Request.Builder() .url("https://square.com") .tag("a") .tag(null) .build() assertThat(request.tag()).isNull() } @Test fun removeAbsentTag() { val request = Request.Builder() .url("https://square.com") .tag(null) .build() assertThat(request.tag()).isNull() } @Test fun objectTag() { val tag = UUID.randomUUID() val request = Request.Builder() .url("https://square.com") .tag(Any::class.java, tag) .build() assertThat(request.tag()).isSameAs(tag) assertThat(request.tag(Any::class.java)).isSameAs(tag) assertThat(request.tag(UUID::class.java)).isNull() assertThat(request.tag(String::class.java)).isNull() // Alternate access APIs also work. assertThat(request.tag(Any::class)).isSameAs(tag) assertThat(request.tag<Any>()).isSameAs(tag) } @Test fun javaClassTag() { val uuidTag = UUID.randomUUID() val request = Request.Builder() .url("https://square.com") .tag(UUID::class.java, uuidTag) // Use the Class<*> parameter. .build() assertThat(request.tag()).isNull() assertThat(request.tag(Any::class.java)).isNull() assertThat(request.tag(UUID::class.java)).isSameAs(uuidTag) assertThat(request.tag(String::class.java)).isNull() // Alternate access APIs also work. assertThat(request.tag(UUID::class)).isSameAs(uuidTag) assertThat(request.tag<UUID>()).isSameAs(uuidTag) } @Test fun kotlinReifiedTag() { val uuidTag = UUID.randomUUID() val request = Request.Builder() .url("https://square.com") .tag<UUID>(uuidTag) // Use the type parameter. .build() assertThat(request.tag()).isNull() assertThat(request.tag<Any>()).isNull() assertThat(request.tag<UUID>()).isSameAs(uuidTag) assertThat(request.tag<String>()).isNull() // Alternate access APIs also work. assertThat(request.tag(UUID::class.java)).isSameAs(uuidTag) assertThat(request.tag(UUID::class)).isSameAs(uuidTag) } @Test fun kotlinClassTag() { val uuidTag = UUID.randomUUID() val request = Request.Builder() .url("https://square.com") .tag(UUID::class, uuidTag) // Use the KClass<*> parameter. .build() assertThat(request.tag()).isNull() assertThat(request.tag(Any::class)).isNull() assertThat(request.tag(UUID::class)).isSameAs(uuidTag) assertThat(request.tag(String::class)).isNull() // Alternate access APIs also work. assertThat(request.tag(UUID::class.java)).isSameAs(uuidTag) assertThat(request.tag<UUID>()).isSameAs(uuidTag) } @Test fun replaceOnlyTag() { val uuidTag1 = UUID.randomUUID() val uuidTag2 = UUID.randomUUID() val request = Request.Builder() .url("https://square.com") .tag(UUID::class.java, uuidTag1) .tag(UUID::class.java, uuidTag2) .build() assertThat(request.tag(UUID::class.java)).isSameAs(uuidTag2) } @Test fun multipleTags() { val uuidTag = UUID.randomUUID() val stringTag = "dilophosaurus" val longTag = 20170815L as Long? val objectTag = Any() val request = Request.Builder() .url("https://square.com") .tag(Any::class.java, objectTag) .tag(UUID::class.java, uuidTag) .tag(String::class.java, stringTag) .tag(Long::class.javaObjectType, longTag) .build() assertThat(request.tag()).isSameAs(objectTag) assertThat(request.tag(Any::class.java)).isSameAs(objectTag) assertThat(request.tag(UUID::class.java)).isSameAs(uuidTag) assertThat(request.tag(String::class.java)).isSameAs(stringTag) assertThat(request.tag(Long::class.javaObjectType)).isSameAs(longTag) } /** Confirm that we don't accidentally share the backing map between objects. */ @Test fun tagsAreImmutable() { val builder = Request.Builder() .url("https://square.com") val requestA = builder.tag(String::class.java, "a").build() val requestB = builder.tag(String::class.java, "b").build() val requestC = requestA.newBuilder().tag(String::class.java, "c").build() assertThat(requestA.tag(String::class.java)).isSameAs("a") assertThat(requestB.tag(String::class.java)).isSameAs("b") assertThat(requestC.tag(String::class.java)).isSameAs("c") } @Test fun requestToStringRedactsSensitiveHeaders() { val headers = Headers.Builder() .add("content-length", "99") .add("authorization", "peanutbutter") .add("proxy-authorization", "chocolate") .add("cookie", "drink=coffee") .add("set-cookie", "accessory=sugar") .add("user-agent", "OkHttp") .build() val request = Request( "https://square.com".toHttpUrl(), headers ) assertThat(request.toString()).isEqualTo( "Request{method=GET, url=https://square.com/, headers=[" + "content-length:99," + " authorization:██," + " proxy-authorization:██," + " cookie:██," + " set-cookie:██," + " user-agent:OkHttp" + "]}" ) } private fun bodyToHex(body: RequestBody): String { val buffer = Buffer() body.writeTo(buffer) return buffer.readByteString().hex() } }
apache-2.0
94d2a8d54355d8e54d0f6af9cd7f85ca
30.862595
107
0.668663
3.953587
false
true
false
false
JetBrains/intellij-community
plugins/gitlab/src/org/jetbrains/plugins/gitlab/project/GitLabProjectPath.kt
1
1305
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gitlab.project import com.intellij.openapi.util.NlsSafe import com.intellij.util.text.nullize import git4idea.remote.GitRemoteUrlCoordinates import git4idea.remote.hosting.GitHostingUrlUtil import org.jetbrains.plugins.gitlab.api.GitLabServerPath data class GitLabProjectPath(val owner: String, val name: String) { @NlsSafe fun fullPath(): String = "$owner/$name" @NlsSafe override fun toString(): String = "$owner/$name" companion object { fun create(server: GitLabServerPath, remote: GitRemoteUrlCoordinates): GitLabProjectPath? { val serverPath = server.toURI().path val remotePath = GitHostingUrlUtil.getUriFromRemoteUrl(remote.url)?.path ?: return null if (!remotePath.startsWith(serverPath)) return null val repositoryPath = remotePath.removePrefix(serverPath).removePrefix("/") val lastSlashIdx = repositoryPath.lastIndexOf('/') if (lastSlashIdx < 0) return null val name = repositoryPath.substringAfterLast('/', "").nullize() ?: return null val owner = repositoryPath.substringBeforeLast('/', "").nullize() ?: return null return GitLabProjectPath(owner, name) } } }
apache-2.0
4c147946fd0d90430758421a078854b1
38.575758
120
0.742529
4.611307
false
false
false
false
JetBrains/intellij-community
plugins/devkit/devkit-kotlin-tests/testData/inspections/internal/PsiType.kt
1
1517
package com.intellij.psi abstract class PsiType { companion object { //@JvmField val VOID = PsiPrimitiveType() //@JvmField val NULL = PsiPrimitiveType() //@JvmField val EMPTY_ARRAY = arrayOf<PsiType>() } open fun test() { if (EMPTY_ARRAY === EMPTY_ARRAY) {} //if (VOID !== NULL) {} // TODO add @JvmField } } class PsiPrimitiveType : PsiType() { override fun test() { if (this === this) {} if (this !== this) {} val first: PsiPrimitiveType = PsiPrimitiveType() val second: PsiPrimitiveType? = PsiPrimitiveType() if (this === second) {} if (second !== this) {} if (<warning descr="'PsiPrimitiveType' instances should be compared for equality, not identity">first === second</warning>) {} if (<warning descr="'PsiPrimitiveType' instances should be compared for equality, not identity">first !== second</warning>) {} if (<warning descr="'PsiPrimitiveType' instances should be compared for equality, not identity">second === first</warning>) {} if (<warning descr="'PsiPrimitiveType' instances should be compared for equality, not identity">second !== first</warning>) {} val third: MyPsiPrimitiveType = first if (<warning descr="'PsiPrimitiveType' instances should be compared for equality, not identity">third === first</warning>) {} if (<warning descr="'PsiPrimitiveType' instances should be compared for equality, not identity">third !== first</warning>) {} } } typealias MyPsiPrimitiveType = PsiPrimitiveType
apache-2.0
5edaf2405cefb1df38358fbc6bc76c2c
32
130
0.673039
4.785489
false
false
false
false
allotria/intellij-community
python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyDataclassTypeProvider.kt
2
12269
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.jetbrains.python.codeInsight.stdlib import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.containers.isNullOrEmpty import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.* import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyCallExpressionNavigator import com.jetbrains.python.psi.impl.stubs.PyDataclassFieldStubImpl import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.stubs.PyDataclassFieldStub import com.jetbrains.python.psi.types.* import one.util.streamex.StreamEx class PyDataclassTypeProvider : PyTypeProviderBase() { override fun getReferenceExpressionType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? { return getDataclassesReplaceType(referenceExpression, context) } override fun getReferenceType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): Ref<PyType>? { val result = when { referenceTarget is PyClass && anchor is PyCallExpression -> getDataclassTypeForClass(referenceTarget, context) referenceTarget is PyParameter && referenceTarget.isSelf && anchor is PyCallExpression -> { PsiTreeUtil.getParentOfType(referenceTarget, PyFunction::class.java) ?.takeIf { it.modifier == PyFunction.Modifier.CLASSMETHOD } ?.let { it.containingClass?.let { getDataclassTypeForClass(it, context) } } } else -> null } return PyTypeUtil.notNullToRef(result) } override fun getParameterType(param: PyNamedParameter, func: PyFunction, context: TypeEvalContext): Ref<PyType>? { if (!param.isPositionalContainer && !param.isKeywordContainer && param.annotationValue == null && func.name == DUNDER_POST_INIT) { val cls = func.containingClass val name = param.name if (cls != null && name != null && parseStdDataclassParameters(cls, context)?.init == true) { cls .findClassAttribute(name, false, context) // `true` is not used here because ancestor should be a dataclass ?.let { return Ref.create(getTypeForParameter(cls, it, PyDataclassParameters.PredefinedType.STD, context)) } for (ancestor in cls.getAncestorClasses(context)) { if (parseStdDataclassParameters(ancestor, context) != null) { ancestor .findClassAttribute(name, false, context) ?.let { return Ref.create(getTypeForParameter(ancestor, it, PyDataclassParameters.PredefinedType.STD, context)) } } } } } return null } companion object { private fun getDataclassesReplaceType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyCallableType? { val call = PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceExpression) ?: return null val callee = call.callee as? PyReferenceExpression ?: return null val resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context) val resolvedCallee = PyUtil.multiResolveTopPriority(callee.getReference(resolveContext)).singleOrNull() return if (resolvedCallee is PyCallable) getDataclassesReplaceType(resolvedCallee, call, context) else null } private fun getDataclassesReplaceType(resolvedCallee: PyCallable, call: PyCallExpression, context: TypeEvalContext): PyCallableType? { val instanceName = when (resolvedCallee.qualifiedName) { "dataclasses.replace" -> "obj" "attr.assoc", "attr.evolve" -> "inst" else -> return null } val obj = call.getArgument(0, instanceName, PyTypedElement::class.java) ?: return null val objType = context.getType(obj) as? PyClassType ?: return null if (objType.isDefinition) return null val dataclassType = getDataclassTypeForClass(objType.pyClass, context) ?: return null val dataclassParameters = dataclassType.getParameters(context) ?: return null val parameters = mutableListOf<PyCallableParameter>() val elementGenerator = PyElementGenerator.getInstance(resolvedCallee.project) parameters.add(PyCallableParameterImpl.nonPsi(instanceName, objType)) parameters.add(PyCallableParameterImpl.psi(elementGenerator.createSingleStarParameter())) val ellipsis = elementGenerator.createEllipsis() dataclassParameters.mapTo(parameters) { PyCallableParameterImpl.nonPsi(it.name, it.getType(context), ellipsis) } return PyCallableTypeImpl(parameters, dataclassType.getReturnType(context)) } private fun getDataclassTypeForClass(cls: PyClass, context: TypeEvalContext): PyCallableType? { val clsType = (context.getType(cls) as? PyClassLikeType) ?: return null val resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context) val elementGenerator = PyElementGenerator.getInstance(cls.project) val ellipsis = elementGenerator.createEllipsis() val collected = linkedMapOf<String, PyCallableParameter>() var seenInit = false val keywordOnly = linkedSetOf<String>() var seenKeywordOnlyClass = false val seenNames = mutableSetOf<String>() for (currentType in StreamEx.of(clsType).append(cls.getAncestorTypes(context))) { if (currentType == null || !currentType.resolveMember(PyNames.INIT, null, AccessDirection.READ, resolveContext, false).isNullOrEmpty() || !currentType.resolveMember(PyNames.NEW, null, AccessDirection.READ, resolveContext, false).isNullOrEmpty() || currentType !is PyClassType) { if (seenInit) continue else break } val current = currentType.pyClass val parameters = parseDataclassParameters(current, context) if (parameters == null) { if (PyKnownDecoratorUtil.hasUnknownDecorator(current, context)) break else continue } else if (parameters.type.asPredefinedType == null) { break } seenInit = seenInit || parameters.init seenKeywordOnlyClass = seenKeywordOnlyClass || parameters.kwOnly if (seenInit) { current .classAttributes .asReversed() .asSequence() .filterNot { PyTypingTypeProvider.isClassVar(it, context) } .mapNotNull { fieldToParameter(current, it, parameters.type, ellipsis, context) } .filterNot { it.first in seenNames } .forEach { (name, kwOnly, parameter) -> // note: attributes are visited from inheritors to ancestors, in reversed order for every of them if ((seenKeywordOnlyClass || kwOnly) && name !in collected) { keywordOnly += name } if (parameter == null) { seenNames.add(name) } else if (parameters.type.asPredefinedType == PyDataclassParameters.PredefinedType.STD) { // std: attribute that overrides ancestor's attribute does not change the order but updates type collected[name] = collected.remove(name) ?: parameter } else if (!collected.containsKey(name)) { // attrs: attribute that overrides ancestor's attribute changes the order collected[name] = parameter } } } } return if (seenInit) PyCallableTypeImpl(buildParameters(elementGenerator, collected, keywordOnly), clsType.toInstance()) else null } private fun buildParameters(elementGenerator: PyElementGenerator, fields: Map<String, PyCallableParameter>, keywordOnly: Set<String>): List<PyCallableParameter> { if (keywordOnly.isEmpty()) return fields.values.reversed() val positionalOrKeyword = mutableListOf<PyCallableParameter>() val keyword = mutableListOf<PyCallableParameter>() for ((name, value) in fields.entries.reversed()) { if (name !in keywordOnly) { positionalOrKeyword += value } else { keyword += value } } val singleStarParameter = elementGenerator.createSingleStarParameter() return positionalOrKeyword + listOf(PyCallableParameterImpl.psi(singleStarParameter)) + keyword } private fun fieldToParameter(cls: PyClass, field: PyTargetExpression, dataclassType: PyDataclassParameters.Type, ellipsis: PyNoneLiteralExpression, context: TypeEvalContext): Triple<String, Boolean, PyCallableParameter?>? { val fieldName = field.name ?: return null val stub = field.stub val fieldStub = if (stub == null) PyDataclassFieldStubImpl.create(field) else stub.getCustomStub(PyDataclassFieldStub::class.java) if (fieldStub != null && !fieldStub.initValue()) return Triple(fieldName, false, null) if (fieldStub == null && field.annotationValue == null) return null // skip fields that are not annotated val parameterName = fieldName.let { if (dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS && PyUtil.getInitialUnderscores(it) == 1) { it.substring(1) } else it } val parameter = PyCallableParameterImpl.nonPsi( parameterName, getTypeForParameter(cls, field, dataclassType, context), getDefaultValueForParameter(cls, field, fieldStub, dataclassType, ellipsis, context) ) return Triple(parameterName, fieldStub?.kwOnly() == true, parameter) } private fun getTypeForParameter(cls: PyClass, field: PyTargetExpression, dataclassType: PyDataclassParameters.Type, context: TypeEvalContext): PyType? { if (dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS && context.maySwitchToAST(field)) { (field.findAssignedValue() as? PyCallExpression) ?.getKeywordArgument("type") ?.let { PyTypingTypeProvider.getType(it, context) } ?.apply { return get() } } val type = context.getType(field) if (type is PyCollectionType && type.classQName == DATACLASSES_INITVAR_TYPE) { return type.elementTypes.firstOrNull() } if (type == null && dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS) { methodDecoratedAsAttributeDefault(cls, field.name) ?.let { context.getReturnType(it) } ?.let { return PyUnionType.createWeakType(it) } } return type } private fun getDefaultValueForParameter(cls: PyClass, field: PyTargetExpression, fieldStub: PyDataclassFieldStub?, dataclassType: PyDataclassParameters.Type, ellipsis: PyNoneLiteralExpression, context: TypeEvalContext): PyExpression? { return if (fieldStub == null) { when { context.maySwitchToAST(field) -> field.findAssignedValue() field.hasAssignedValue() -> ellipsis else -> null } } else if (fieldStub.hasDefault() || fieldStub.hasDefaultFactory() || dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS && methodDecoratedAsAttributeDefault(cls, field.name) != null) { ellipsis } else null } private fun methodDecoratedAsAttributeDefault(cls: PyClass, attributeName: String?): PyFunction? { if (attributeName == null) return null return cls.methods.firstOrNull { it.decoratorList?.findDecorator("$attributeName.default") != null } } } }
apache-2.0
95639e91a627154e9d498b2f16f19265
43.941392
140
0.666395
5.445628
false
false
false
false
mr-max/learning-spaces
app/src/main/java/de/maxvogler/learningspaces/activities/MainActivity.kt
1
10563
package de.maxvogler.learningspaces.activities import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.os.Bundle import android.support.v4.view.MenuItemCompat import android.support.v7.app.AppCompatActivity import android.support.v7.widget.CardView import android.support.v7.widget.Toolbar import android.view.* import android.view.View.INVISIBLE import android.view.View.VISIBLE import android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator import android.widget.ImageButton import butterknife.bindView import com.sothree.slidinguppanel.SlidingUpPanelLayout import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState.ANCHORED import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState.COLLAPSED import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState.EXPANDED import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState.HIDDEN import com.squareup.otto.Subscribe import de.maxvogler.learningspaces.R import de.maxvogler.learningspaces.events.LocationFocusChangeEvent import de.maxvogler.learningspaces.events.PanelVisibilityChangedEvent import de.maxvogler.learningspaces.events.RequestLocationsEvent import de.maxvogler.learningspaces.events.UpdateLocationsEvent import de.maxvogler.learningspaces.helpers.itemsSequence import de.maxvogler.learningspaces.helpers.tint import de.maxvogler.learningspaces.services.BusProvider import org.jetbrains.anko.browse import org.jetbrains.anko.childrenSequence import org.jetbrains.anko.dip import org.jetbrains.anko.startActivity /** * The main activity. It contains a [SlidingUpPanelLayout], allowing to drag the * [LocationInfoFragment] over the [LocationMapFragment]. On the top of the screen, a [Toolbar] is * shown. Pressing the hamburger menu button on it, reveals all Locations in the [LocationListFragment]. */ public class MainActivity : AppCompatActivity() { private val toolbar: Toolbar by bindView(R.id.toolbar) private val toolbarContainer: CardView by bindView(R.id.container_toolbar) private val slidingPanelLayout: SlidingUpPanelLayout by bindView(R.id.layout) private val dragHandle: View by bindView(R.id.drag_handle) private val listLayout: ViewGroup by bindView(R.id.list) private val infoFragment: View by bindView(R.id.info) private val bus = BusProvider.instance private var refreshMenuItem: MenuItem? = null private val menuButtonPosition: IntArray = intArrayOf(0, 0) @Suppress("DEPRECATED_SYMBOL_WITH_MESSAGE") override fun onCreate(state: Bundle?) { super.onCreate(state) setContentView(R.layout.activity_main) // Initialize the main Toolbar setSupportActionBar(toolbar) supportActionBar.setDisplayHomeAsUpEnabled(true) val menuIcon = resources.getDrawable(R.drawable.ic_menu_white_24dp, theme) menuIcon.tint(resources.getColor(R.color.primary)) supportActionBar.setHomeAsUpIndicator(menuIcon) // Add a proper top margin, if the system supports a translucent status bar if (isTranslucentStatusBar()) { val statusBarHeight = calculateStatusBarHeight() (toolbarContainer.layoutParams as ViewGroup.MarginLayoutParams).topMargin += statusBarHeight (infoFragment.layoutParams as ViewGroup.MarginLayoutParams).topMargin += statusBarHeight toolbarContainer.requestLayout() listLayout.getChildAt(0).requestLayout() infoFragment.requestLayout() } // Initialize the SlidingPanelLayout, containing the LocationMapFragment and LocationInfoFragment slidingPanelLayout.setPanelSlideListener(panelSlideListener) slidingPanelLayout.setDragView(dragHandle) slidingPanelLayout.panelState = HIDDEN slidingPanelLayout.requestLayout() } public fun calculateStatusBarHeight(): Int = resources.getDimensionPixelSize(resources.getIdentifier("status_bar_height", "dimen", "android")) public fun isTranslucentStatusBar(): Boolean = (window.attributes.flags and FLAG_TRANSLUCENT_STATUS) != 0 override fun onResume() { super.onResume() bus.register(this) // Always reload the locations, when (re-)entering the App bus.post(RequestLocationsEvent()) } override fun onPause() { super.onPause() bus.unregister(this) } @Suppress("DEPRECATED_SYMBOL_WITH_MESSAGE") override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) refreshMenuItem = menu.findItem(R.id.refresh) // Tint all menu icons with the primary color val color = resources.getColor(R.color.primary) menu.itemsSequence().forEach { it.icon?.tint(color) } var globalLayoutListener: () -> Unit globalLayoutListener = { // Prevent the InfoFragment from overlapping the Toolbar (infoFragment.layoutParams as ViewGroup.MarginLayoutParams).topMargin += toolbarContainer.height + dip(16) // Save the position of the menu button, to use it as center for the circular reveal val hamburgerMenuIcon = toolbar.childrenSequence().first { it is ImageButton } hamburgerMenuIcon.getLocationOnScreen(menuButtonPosition) menuButtonPosition[0] += hamburgerMenuIcon.width / 2 menuButtonPosition[1] += hamburgerMenuIcon.width / 2 slidingPanelLayout.viewTreeObserver.removeOnGlobalLayoutListener(globalLayoutListener); } slidingPanelLayout.viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.refresh -> bus.post(RequestLocationsEvent()) R.id.open_website -> browse(getString(R.string.website_url)); R.id.open_about -> startActivity<AboutActivity>(); // Pressing the hamburger menu button toggles the LocationListFragment visibility android.R.id.home -> animateListFragmentVisibility(!isListVisible()) else -> return super.onOptionsItemSelected(item) } return true } /** * Sets the visibility of the [LocationListFragment]. A circular reveal animation shows * or hides the list. * * When the [LocationListFragment] is fully visible, the [SlidingUpPanelLayout] and * [LocationMapFragment] are hidden to improve rendering performance. * * @param listVisible */ public fun animateListFragmentVisibility(listVisible: Boolean) { // On quick successive presses, do nothing if (isListVisible() == listVisible) return; val max = Math.max(listLayout.height, listLayout.width).toFloat() if (listVisible) listLayout.visibility = VISIBLE else slidingPanelLayout.visibility = VISIBLE // This should not be necessary, because toggles faster than the animation are prevented listLayout.clearAnimation() // Create a circular reveal animation, centered on the hambuger menu icon val anim = ViewAnimationUtils.createCircularReveal(listLayout, menuButtonPosition[0], menuButtonPosition[1], if (listVisible) 0f else max, if (listVisible) max else 0f ) // Interpolate the animation around the icon smoothly anim.interpolator = if (listVisible) AccelerateInterpolator() else DecelerateInterpolator() anim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { if (!listVisible) listLayout.visibility = INVISIBLE else slidingPanelLayout.visibility = INVISIBLE } }) anim.start() } private fun isListVisible(): Boolean = listLayout.visibility == VISIBLE @Subscribe public fun onReceiveLocations(event: UpdateLocationsEvent) { setRefreshProgressVisible(false) } @Subscribe public fun onLocationsRequested(event: RequestLocationsEvent) { setRefreshProgressVisible(true) } @Subscribe public fun onLocationFocusChange(event: LocationFocusChangeEvent) { if (event.hasSelection()) { // If the user selects a Location in the LocationListFragment, hide it and show the map animateListFragmentVisibility(false) slidingPanelLayout.panelState = COLLAPSED } else { // If the user discards the selected location, hide the LocationInfoFragment slidingPanelLayout.panelState = HIDDEN } } private fun setRefreshProgressVisible(refreshing: Boolean) { if (refreshMenuItem == null) return if (refreshing) { MenuItemCompat.setActionView(refreshMenuItem, R.layout.view_appbar_progress) } else { MenuItemCompat.setActionView(refreshMenuItem, null) } } override fun onBackPressed() { if (isListVisible()) { // Pressing back when viewing the LocationListFragment hides it and shows the map animateListFragmentVisibility(false) } else if (slidingPanelLayout.panelState == EXPANDED || slidingPanelLayout.panelState == ANCHORED) { // Pressing back with the LocationInfoFragment open, minimizes it slidingPanelLayout.panelState = COLLAPSED } else { super.onBackPressed() } } private val panelSlideListener = object : SlidingUpPanelLayout.SimplePanelSlideListener() { override fun onPanelSlide(view: View?, v: Float) { // Legacy code, to fade out the Toolbar when swiping up the SlidingUpPanelLayout //toolbarContainer.setVisibility(if (v < 1f) View.VISIBLE else View.INVISIBLE); //toolbarContainer.setAlpha(1 - v) } override fun onPanelCollapsed(view: View?) = bus.post(PanelVisibilityChangedEvent(false)) override fun onPanelExpanded(view: View?) = bus.post(PanelVisibilityChangedEvent(true)) override fun onPanelAnchored(view: View?) = bus.post(PanelVisibilityChangedEvent(true)) override fun onPanelHidden(view: View?) = bus.post(PanelVisibilityChangedEvent(false)) } }
gpl-2.0
06606b7af865e91e7cf7c59f65c63e3d
38.122222
118
0.708132
4.954503
false
false
false
false
Raizlabs/DBFlow
contentprovider/src/main/kotlin/com/dbflow5/provider/ContentUtils.kt
1
14576
package com.dbflow5.provider import android.annotation.SuppressLint import android.content.ContentResolver import android.content.ContentValues import android.content.Context import android.net.Uri import com.dbflow5.adapter.ModelAdapter import com.dbflow5.config.FlowLog import com.dbflow5.config.modelAdapter import com.dbflow5.contentprovider.annotation.ContentProvider import com.dbflow5.database.DatabaseWrapper import com.dbflow5.database.FlowCursor import com.dbflow5.query.Operator import com.dbflow5.query.OperatorGroup /** * Description: Provides handy wrapper mechanisms for [android.content.ContentProvider] */ object ContentUtils { /** * The default content URI that Android recommends. Not necessary, however. */ const val BASE_CONTENT_URI = "content://" /** * Constructs an Uri with the [.BASE_CONTENT_URI] and authority. Add paths to append to the Uri. * * @param authority The authority for a [ContentProvider] * @param paths The list of paths to append. * @return A complete Uri for a [ContentProvider] */ @JvmStatic fun buildUriWithAuthority(authority: String, vararg paths: String): Uri = buildUri(BASE_CONTENT_URI, authority, *paths) /** * Constructs an Uri with the specified baseContent uri and authority. Add paths to append to the Uri. * * @param baseContentUri The base content URI for a [ContentProvider] * @param authority The authority for a [ContentProvider] * @param paths The list of paths to append. * @return A complete Uri for a [ContentProvider] */ @JvmStatic fun buildUri(baseContentUri: String, authority: String, vararg paths: String): Uri { val builder = Uri.parse(baseContentUri + authority).buildUpon() for (path in paths) { builder.appendPath(path) } return builder.build() } /** * Inserts the model into the [android.content.ContentResolver]. Uses the insertUri to resolve * the reference and the model to convert its data into [android.content.ContentValues] * * @param insertUri A [android.net.Uri] from the [ContentProvider] class definition. * @param model The model to insert. * @return A Uri of the inserted data. */ @JvmStatic fun <TableClass : Any> insert(context: Context, insertUri: Uri, model: TableClass): Uri? = insert(context.contentResolver, insertUri, model) /** * Inserts the model into the [android.content.ContentResolver]. Uses the insertUri to resolve * the reference and the model to convert its data into [android.content.ContentValues] * * @param contentResolver The content resolver to use * @param insertUri A [android.net.Uri] from the [ContentProvider] class definition. * @param model The model to insert. * @return The Uri of the inserted data. */ @JvmStatic fun <TableClass : Any> insert(contentResolver: ContentResolver, insertUri: Uri, model: TableClass): Uri? { val adapter = model.javaClass.modelAdapter val contentValues = ContentValues() adapter.bindToInsertValues(contentValues, model) val uri: Uri? = contentResolver.insert(insertUri, contentValues) uri?.let { adapter.updateAutoIncrement(model, uri.pathSegments[uri.pathSegments.size - 1].toLong()) } return uri } /** * Inserts the list of model into the [ContentResolver]. Binds all of the models to [ContentValues] * and runs the [ContentResolver.bulkInsert] method. Note: if any of these use * autoIncrementing primary keys the ROWID will not be properly updated from this method. If you care * use [.insert] instead. * * @param contentResolver The content resolver to use * @param bulkInsertUri The URI to bulk insert with * @param table The table to insert into * @param models The models to insert. * @return The count of the rows affected by the insert. */ @JvmStatic fun <TableClass : Any> bulkInsert(contentResolver: ContentResolver, bulkInsertUri: Uri, table: Class<TableClass>, models: List<TableClass>?): Int { val contentValues = arrayListOf<ContentValues>() val adapter = table.modelAdapter if (models != null) { for (i in contentValues.indices) { val values = ContentValues() adapter.bindToInsertValues(values, models[i]) contentValues += values } } return contentResolver.bulkInsert(bulkInsertUri, contentValues.toTypedArray()) } /** * Inserts the list of model into the [ContentResolver]. Binds all of the models to [ContentValues] * and runs the [ContentResolver.bulkInsert] method. Note: if any of these use * autoincrement primary keys the ROWID will not be properly updated from this method. If you care * use [.insert] instead. * * @param bulkInsertUri The URI to bulk insert with * @param table The table to insert into * @param models The models to insert. * @return The count of the rows affected by the insert. */ @JvmStatic fun <TableClass : Any> bulkInsert(context: Context, bulkInsertUri: Uri, table: Class<TableClass>, models: List<TableClass>): Int = bulkInsert(context.contentResolver, bulkInsertUri, table, models) /** * Updates the model through the [android.content.ContentResolver]. Uses the updateUri to * resolve the reference and the model to convert its data in [android.content.ContentValues] * * @param updateUri A [android.net.Uri] from the [ContentProvider] * @param model A model to update * @return The number of rows updated. */ @JvmStatic fun <TableClass : Any> update(context: Context, updateUri: Uri, model: TableClass): Int = update(context.contentResolver, updateUri, model) /** * Updates the model through the [android.content.ContentResolver]. Uses the updateUri to * resolve the reference and the model to convert its data in [android.content.ContentValues] * * @param contentResolver The content resolver to use * @param updateUri A [android.net.Uri] from the [ContentProvider] * @param model The model to update * @return The number of rows updated. */ @JvmStatic fun <TableClass : Any> update(contentResolver: ContentResolver, updateUri: Uri, model: TableClass): Int { val adapter = model.javaClass.modelAdapter val contentValues = ContentValues() adapter.bindToContentValues(contentValues, model) val count = contentResolver.update(updateUri, contentValues, adapter.getPrimaryConditionClause(model).query, null) if (count == 0) { FlowLog.log(FlowLog.Level.W, "Updated failed of: " + model.javaClass) } return count } /** * Deletes the specified model through the [android.content.ContentResolver]. Uses the deleteUri * to resolve the reference and the model to [ModelAdapter.getPrimaryConditionClause]} * * @param deleteUri A [android.net.Uri] from the [ContentProvider] * @param model The model to delete * @return The number of rows deleted. */ @JvmStatic fun <TableClass : Any> delete(context: Context, deleteUri: Uri, model: TableClass): Int = delete(context.contentResolver, deleteUri, model) /** * Deletes the specified model through the [android.content.ContentResolver]. Uses the deleteUri * to resolve the reference and the model to [ModelAdapter.getPrimaryConditionClause] * * @param contentResolver The content resolver to use * @param deleteUri A [android.net.Uri] from the [ContentProvider] * @param model The model to delete * @return The number of rows deleted. */ @JvmStatic fun <TableClass : Any> delete(contentResolver: ContentResolver, deleteUri: Uri, model: TableClass): Int { val adapter = model.javaClass.modelAdapter val count = contentResolver.delete(deleteUri, adapter.getPrimaryConditionClause(model).query, null) // reset autoincrement to 0 if (count > 0) { adapter.updateAutoIncrement(model, 0) } else { FlowLog.log(FlowLog.Level.W, "A delete on ${model.javaClass} within the ContentResolver appeared to fail.") } return count } /** * Queries the [android.content.ContentResolver] with the specified query uri. It generates * the correct query and returns a [android.database.Cursor] * * @param contentResolver The content resolver to use * @param queryUri The URI of the query * @param whereConditions The set of [Operator] to query the content provider. * @param orderBy The order by clause without the ORDER BY * @param columns The list of columns to query. * @return A [android.database.Cursor] */ @JvmStatic fun query(contentResolver: ContentResolver, queryUri: Uri, whereConditions: OperatorGroup, orderBy: String?, vararg columns: String?): FlowCursor? = contentResolver.query(queryUri, columns, whereConditions.query, null, orderBy) ?.let { cursor -> FlowCursor.from(cursor) } /** * Queries the [android.content.ContentResolver] with the specified queryUri. It will generate * the correct query and return a list of [TableClass] * * @param queryUri The URI of the query * @param table The table to get from. * @param whereConditions The set of [Operator] to query the content provider. * @param orderBy The order by clause without the ORDER BY * @param columns The list of columns to query. * @return A list of [TableClass] */ @JvmStatic fun <TableClass : Any> queryList(context: Context, queryUri: Uri, table: Class<TableClass>, databaseWrapper: DatabaseWrapper, whereConditions: OperatorGroup, orderBy: String, vararg columns: String): List<TableClass>? = queryList(context.contentResolver, queryUri, table, databaseWrapper, whereConditions, orderBy, *columns) /** * Queries the [android.content.ContentResolver] with the specified queryUri. It will generate * the correct query and return a list of [TableClass] * * @param contentResolver The content resolver to use * @param queryUri The URI of the query * @param table The table to get from. * @param whereConditions The set of [Operator] to query the content provider. * @param orderBy The order by clause without the ORDER BY * @param columns The list of columns to query. * @return A list of [TableClass] */ @SuppressLint("Recycle") @JvmStatic fun <TableClass : Any> queryList(contentResolver: ContentResolver, queryUri: Uri, table: Class<TableClass>, databaseWrapper: DatabaseWrapper, whereConditions: OperatorGroup, orderBy: String, vararg columns: String): List<TableClass>? { val cursor = contentResolver.query(queryUri, columns, whereConditions.query, null, orderBy)?.let { cursor -> FlowCursor.from(cursor) } return cursor.use { c -> table.modelAdapter .listModelLoader .load(c, databaseWrapper) } } /** * Queries the [android.content.ContentResolver] with the specified queryUri. It will generate * the correct query and return a the first item from the list of [TableClass] * * @param queryUri The URI of the query * @param table The table to get from * @param whereConditions The set of [Operator] to query the content provider. * @param orderBy The order by clause without the ORDER BY * @param columns The list of columns to query. * @return The first [TableClass] of the list query from the content provider. */ @JvmStatic fun <TableClass : Any> querySingle(context: Context, queryUri: Uri, table: Class<TableClass>, databaseWrapper: DatabaseWrapper, whereConditions: OperatorGroup, orderBy: String, vararg columns: String): TableClass? = querySingle(context.contentResolver, queryUri, table, databaseWrapper, whereConditions, orderBy, *columns) /** * Queries the [android.content.ContentResolver] with the specified queryUri. It will generate * the correct query and return a the first item from the list of [TableClass] * * @param contentResolver The content resolver to use * @param queryUri The URI of the query * @param table The table to get from * @param whereConditions The set of [Operator] to query the content provider. * @param orderBy The order by clause without the ORDER BY * @param columns The list of columns to query. * @return The first [TableClass] of the list query from the content provider. */ @JvmStatic fun <TableClass : Any> querySingle(contentResolver: ContentResolver, queryUri: Uri, table: Class<TableClass>, databaseWrapper: DatabaseWrapper, whereConditions: OperatorGroup, orderBy: String, vararg columns: String): TableClass? { val list = queryList(contentResolver, queryUri, table, databaseWrapper, whereConditions, orderBy, *columns) return list?.let { if (list.isNotEmpty()) list[0] else null } } }
mit
900eeb44cac1ebb08bcca6fcff872f18
44.55
119
0.62994
4.874916
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/analysis/HProfAnalysis.kt
1
7213
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.analysis import com.google.common.base.Stopwatch import com.intellij.diagnostic.hprof.classstore.HProfMetadata import com.intellij.diagnostic.hprof.histogram.Histogram import com.intellij.diagnostic.hprof.navigator.ObjectNavigator import com.intellij.diagnostic.hprof.parser.HProfEventBasedParser import com.intellij.diagnostic.hprof.util.FileBackedIntList import com.intellij.diagnostic.hprof.util.FileBackedUByteList import com.intellij.diagnostic.hprof.util.HeapReportUtils.sectionHeader import com.intellij.diagnostic.hprof.util.HeapReportUtils.toShortStringAsCount import com.intellij.diagnostic.hprof.util.PartialProgressIndicator import com.intellij.diagnostic.hprof.visitors.RemapIDsVisitor import com.intellij.openapi.progress.ProgressIndicator import org.jetbrains.annotations.TestOnly import java.nio.channels.FileChannel import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption class HProfAnalysis(private val hprofFileChannel: FileChannel, private val tempFilenameSupplier: TempFilenameSupplier) { interface TempFilenameSupplier { fun getTempFilePath(type: String): Path } private data class TempFile( val type: String, val path: Path, val channel: FileChannel ) private val tempFiles = mutableListOf<TempFile>() private var includeMetaInfo = true @TestOnly fun setIncludeMetaInfo(value: Boolean) { includeMetaInfo = value } private fun openTempEmptyFileChannel(type: String): FileChannel { val tempPath = tempFilenameSupplier.getTempFilePath(type) val tempChannel = FileChannel.open(tempPath, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.DELETE_ON_CLOSE) tempFiles.add(TempFile(type, tempPath, tempChannel)) return tempChannel } fun analyze(progress: ProgressIndicator): String { val result = StringBuilder() val totalStopwatch = Stopwatch.createStarted() val prepareFilesStopwatch = Stopwatch.createStarted() val analysisStopwatch = Stopwatch.createUnstarted() progress.text = "Analyze Heap" progress.text2 = "Open heap file" progress.fraction = 0.0 val parser = HProfEventBasedParser(hprofFileChannel) try { progress.text2 = "Create class definition map" progress.fraction = 0.0 val hprofMetadata = HProfMetadata.create(parser) progress.text2 = "Create class histogram" progress.fraction = 0.1 val histogram = Histogram.create(parser, hprofMetadata.classStore) val nominatedClasses = ClassNomination(histogram, 5).nominateClasses() progress.text2 = "Create id mapping file" progress.fraction = 0.2 // Currently, there is a maximum count of supported instances. Produce simplified report // (histogram only), if the count exceeds maximum. if (!isSupported(histogram.instanceCount)) { result.appendln(histogram.prepareReport("All", 50)) return result.toString() } val idMappingChannel = openTempEmptyFileChannel("id-mapping") val remapIDsVisitor = RemapIDsVisitor.createFileBased( idMappingChannel, histogram.instanceCount) parser.accept(remapIDsVisitor, "id mapping") parser.setIdRemappingFunction(remapIDsVisitor.getRemappingFunction()) hprofMetadata.remapIds(remapIDsVisitor.getRemappingFunction()) progress.text2 = "Create object graph files" progress.fraction = 0.3 val navigator = ObjectNavigator.createOnAuxiliaryFiles( parser, openTempEmptyFileChannel("auxOffset"), openTempEmptyFileChannel("aux"), hprofMetadata, histogram.instanceCount ) prepareFilesStopwatch.stop() val parentList = FileBackedIntList.createEmpty(openTempEmptyFileChannel("parents"), navigator.instanceCount + 1) val sizesList = FileBackedIntList.createEmpty(openTempEmptyFileChannel("sizes"), navigator.instanceCount + 1) val visitedList = FileBackedIntList.createEmpty(openTempEmptyFileChannel("visited"), navigator.instanceCount + 1) val refIndexList = FileBackedUByteList.createEmpty(openTempEmptyFileChannel("refIndex"), navigator.instanceCount + 1) analysisStopwatch.start() val nominatedClassNames = nominatedClasses.map { it.classDefinition.name } val analysisConfig = AnalysisConfig(perClassOptions = AnalysisConfig.PerClassOptions(classNames = nominatedClassNames), metaInfoOptions = AnalysisConfig.MetaInfoOptions(include = includeMetaInfo)) val analysisContext = AnalysisContext( navigator, analysisConfig, parentList, sizesList, visitedList, refIndexList, histogram ) val analysisReport = AnalyzeGraph(analysisContext).analyze(PartialProgressIndicator(progress, 0.4, 0.4)) result.appendln(analysisReport) analysisStopwatch.stop() if (includeMetaInfo) { result.appendln(sectionHeader("Analysis information")) result.appendln("Prepare files duration: $prepareFilesStopwatch") result.appendln("Analysis duration: $analysisStopwatch") result.appendln("TOTAL DURATION: $totalStopwatch") result.appendln("Temp files:") result.appendln(" heapdump = ${toShortStringAsCount(hprofFileChannel.size())}") tempFiles.forEach { temp -> val channel = temp.channel if (channel.isOpen) { result.appendln(" ${temp.type} = ${toShortStringAsCount(channel.size())}") } } } } finally { parser.close() closeAndDeleteTemporaryFiles() } return result.toString() } private fun isSupported(instanceCount: Long): Boolean { // Limitation due to FileBackedHashMap in RemapIDsVisitor. Many other components // assume instanceCount <= Int.MAX_VALUE. return RemapIDsVisitor.isSupported(instanceCount) && instanceCount <= Int.MAX_VALUE } private fun closeAndDeleteTemporaryFiles() { tempFiles.forEach { tempFile -> try { tempFile.channel.close() } catch (ignored: Throwable) { } try { tempFile.path.let { Files.deleteIfExists(it) } } catch (ignored: Throwable) { } } tempFiles.clear() } }
apache-2.0
a97808fc94a471d02c9c0e6d3aae5c9e
35.429293
125
0.70567
4.717462
false
false
false
false
smmribeiro/intellij-community
plugins/completion-ml-ranking/src/com/intellij/completion/ml/ranker/local/MLCompletionLocalModelsUtil.kt
11
2542
// 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.completion.ml.ranker.local import com.intellij.internal.ml.DecisionFunction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.registry.Registry import com.intellij.util.concurrency.SequentialTaskExecutor import java.util.concurrent.Future import java.util.zip.ZipFile object MLCompletionLocalModelsUtil { private const val REGISTRY_PATH_KEY = "completion.ml.path.to.zip.model" private val LOG = Logger.getInstance(MLCompletionLocalModelsUtil::class.java) private val executor = SequentialTaskExecutor.createSequentialApplicationPoolExecutor("MLCompletionTxtModelsUtil pool executor") @Volatile private var localModel: LocalModalInfo? = null fun getModel(languageId: String): DecisionFunction? { if (!isPathToTheModelSet()) { localModel = null return null } if (isPathToTheModelChanged()) { scheduleInitModel() return null } val resLocalModel = localModel ?: return null return if (languageId.toLowerCase() in resLocalModel.languages) { resLocalModel.decisionFunction } else { null } } /** * Use this function for asynchronously loading model */ private fun scheduleInitModel(): Future<*> = executor.submit { initModelFromPathToZipSynchronously() } private fun isPathToTheModelSet() = Registry.get(REGISTRY_PATH_KEY).isChangedFromDefault private fun isPathToTheModelChanged() = Registry.stringValue(REGISTRY_PATH_KEY) != localModel?.path private fun initModelFromPathToZipSynchronously() { localModel = null val startTime = System.currentTimeMillis() val pathToZip = Registry.stringValue(REGISTRY_PATH_KEY) localModel = loadModel(pathToZip) val endTime = System.currentTimeMillis() LOG.info("ML Completion local model initialization took: ${endTime - startTime} ms.") } private fun loadModel(pathToZip: String): LocalModalInfo? { try { ZipFile(pathToZip).use { file -> val loader = LocalZipModelProvider.findModelProvider(file) ?: return null val (decisionFunction, languages) = loader.loadModel(file) return LocalModalInfo(decisionFunction, pathToZip, languages.toSet()) } } catch (t: Throwable) { LOG.error(t) return null } } private data class LocalModalInfo(val decisionFunction: DecisionFunction, val path: String, val languages: Set<String>) }
apache-2.0
6dc9d010e043da103cc48a4115c92059
36.382353
140
0.743116
4.390328
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/quickfix/AbstractQuickFixMultiFileTest.kt
2
15504
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.codeInsight.daemon.quickFix.ActionHint import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.impl.CachedIntentions import com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler import com.intellij.codeInspection.InspectionEP import com.intellij.codeInspection.LocalInspectionEP import com.intellij.ide.highlighter.JavaFileType import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.PlainTextFileType import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl import com.intellij.util.ArrayUtil import com.intellij.util.PathUtil import com.intellij.util.ThrowableRunnable import junit.framework.ComparisonFailure import junit.framework.TestCase import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.quickfix.utils.findInspectionFile import org.jetbrains.kotlin.idea.test.DirectiveBasedActionUtils import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.runAll import org.jetbrains.kotlin.idea.test.withCustomCompilerOptions import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.Directives import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.test.TestFiles import java.io.File import java.util.regex.Pattern abstract class AbstractQuickFixMultiFileTest : KotlinLightCodeInsightFixtureTestCase() { protected open fun doTestWithExtraFile(beforeFileName: String) { enableInspections(beforeFileName) if (beforeFileName.endsWith(".test")) { doMultiFileTest(beforeFileName) } else { doTest(beforeFileName) } } private fun enableInspections(beforeFileName: String) { val inspectionFile = findInspectionFile(File(beforeFileName).parentFile) if (inspectionFile != null) { val className = FileUtil.loadFile(inspectionFile).trim { it <= ' ' } val inspectionClass = Class.forName(className) enableInspectionTools(inspectionClass) } } private fun enableInspectionTools(klass: Class<*>) { val eps = mutableListOf<InspectionEP>().apply { addAll(LocalInspectionEP.LOCAL_INSPECTION.extensions) addAll(InspectionEP.GLOBAL_INSPECTION.extensions) } val tool = eps.firstOrNull { it.implementationClass == klass.name }?.instantiateTool() ?: error("Could not find inspection tool for class: $klass") myFixture.enableInspections(tool) } override fun setUp() { super.setUp() CodeInsightSettings.getInstance().EXCLUDED_PACKAGES = arrayOf("excludedPackage", "somePackage.ExcludedClass") } override fun tearDown() { runAll( ThrowableRunnable { CodeInsightSettings.getInstance().EXCLUDED_PACKAGES = ArrayUtil.EMPTY_STRING_ARRAY }, ThrowableRunnable { super.tearDown() } ) } /** * @param subFiles subFiles of multiFile test * * * @param beforeFile will be added last, as subFiles are dependencies of it */ private fun configureMultiFileTest(subFiles: List<TestFile>, beforeFile: TestFile): List<VirtualFile> { val vFiles = subFiles.map(this::createTestFile).toMutableList() val beforeVFile = createTestFile(beforeFile) vFiles.add(beforeVFile) myFixture.configureFromExistingVirtualFile(beforeVFile) TestCase.assertEquals(guessFileType(beforeFile), myFixture.file.virtualFile.fileType) TestCase.assertTrue("\"<caret>\" is probably missing in file \"" + beforeFile.path + "\"", myFixture.editor.caretModel.offset != 0) return vFiles } private fun createTestFile(testFile: TestFile): VirtualFile { return runWriteAction { val vFile = myFixture.tempDirFixture.createFile(testFile.path) vFile.charset = CharsetToolkit.UTF8_CHARSET VfsUtil.saveText(vFile, testFile.content) vFile } } private fun doMultiFileTest(beforeFileName: String) { val multiFileText = FileUtil.loadFile(File(beforeFileName), true) val subFiles = TestFiles.createTestFiles( "single.kt", multiFileText, object : TestFiles.TestFileFactoryNoModules<TestFile>() { override fun create(fileName: String, text: String, directives: Directives): TestFile { val linesWithoutDirectives = text.lines().filter { !it.startsWith("// LANGUAGE_VERSION") && !it.startsWith("// FILE") } return TestFile(fileName, linesWithoutDirectives.joinToString(separator = "\n")) } } ) val afterFile = subFiles.firstOrNull { file -> file.path.contains(".after") } val beforeFile = subFiles.firstOrNull { file -> file.path.contains(".before") }!! subFiles.remove(beforeFile) if (afterFile != null) { subFiles.remove(afterFile) } configureMultiFileTest(subFiles, beforeFile) withCustomCompilerOptions(multiFileText, project, module) { project.executeCommand("") { try { val psiFile = file val actionHint = ActionHint.parse(psiFile, beforeFile.content) val text = actionHint.expectedText val actionShouldBeAvailable = actionHint.shouldPresent() if (psiFile is KtFile) { DirectiveBasedActionUtils.checkForUnexpectedErrors(psiFile) } doAction( text, file, editor, actionShouldBeAvailable, getTestName(false), this::availableActions, myFixture::doHighlighting, ) val actualText = file.text val afterText = StringBuilder(actualText).insert(editor.caretModel.offset, "<caret>").toString() if (actionShouldBeAvailable) { TestCase.assertNotNull(".after file should exist", afterFile) if (afterText != afterFile!!.content) { val actualTestFile = StringBuilder() if (multiFileText.startsWith("// LANGUAGE_VERSION")) { actualTestFile.append(multiFileText.lineSequence().first()) } actualTestFile.append("// FILE: ").append(beforeFile.path).append("\n").append(beforeFile.content) for (file in subFiles) { actualTestFile.append("// FILE: ").append(file.path).append("\n").append(file.content) } actualTestFile.append("// FILE: ").append(afterFile.path).append("\n").append(afterText) KotlinTestUtils.assertEqualsToFile(File(beforeFileName), actualTestFile.toString()) } } else { TestCase.assertNull(".after file should not exist", afterFile) } } catch (e: ComparisonFailure) { throw e } catch (e: AssertionError) { throw e } catch (e: Throwable) { e.printStackTrace() TestCase.fail(getTestName(true)) } } } } private fun doTest(beforeFileName: String) { val mainFile = File(beforeFileName) val originalFileText = FileUtil.loadFile(mainFile, true) val mainFileDir = mainFile.parentFile!! val mainFileName = mainFile.name val extraFiles = mainFileDir.listFiles { _, name -> name.startsWith(extraFileNamePrefix(mainFileName)) && name != mainFileName && PathUtil.getFileExtension(name).let { it == "kt" || it == "java" || it == "groovy" } }!! val testFiles = ArrayList<String>() testFiles.add(mainFile.name) extraFiles.mapTo(testFiles) { file -> file.name } myFixture.configureByFiles(*testFiles.toTypedArray()) withCustomCompilerOptions(originalFileText, project, module) { project.executeCommand("") { try { val psiFile = file val actionHint = ActionHint.parse(psiFile, originalFileText) val text = actionHint.expectedText val actionShouldBeAvailable = actionHint.shouldPresent() if (psiFile is KtFile) { DirectiveBasedActionUtils.checkForUnexpectedErrors(psiFile) } doAction( text, file, editor, actionShouldBeAvailable, beforeFileName, this::availableActions, myFixture::doHighlighting, ) if (actionShouldBeAvailable) { val afterFilePath = beforeFileName.replace(".before.Main.", ".after.") try { myFixture.checkResultByFile(mainFile.name.replace(".before.Main.", ".after.")) } catch (e: ComparisonFailure) { KotlinTestUtils.assertEqualsToFile(File(afterFilePath), editor) } for (file in myFixture.file.containingDirectory.files) { val fileName = file.name if (fileName == myFixture.file.name || !fileName.startsWith( extraFileNamePrefix( myFixture.file .name, ), ) ) continue val extraFileFullPath = beforeFileName.replace(myFixture.file.name, fileName) val afterFile = File(extraFileFullPath.replace(".before.", ".after.")) if (afterFile.exists()) { KotlinTestUtils.assertEqualsToFile(afterFile, file.text) } else { KotlinTestUtils.assertEqualsToFile(File(extraFileFullPath), file.text) } } } } catch (e: ComparisonFailure) { throw e } catch (e: AssertionError) { throw e } catch (e: Throwable) { e.printStackTrace() TestCase.fail(getTestName(true)) } } } } private val availableActions: List<IntentionAction> get() { myFixture.doHighlighting() val intentions = ShowIntentionActionsHandler.calcIntentions(project, editor, file) val cachedIntentions = CachedIntentions.create(project, file, editor, intentions) cachedIntentions.wrapAndUpdateGutters() return cachedIntentions.allActions.map { it.action } } class TestFile internal constructor(val path: String, val content: String) companion object { private fun getActionsTexts(availableActions: List<IntentionAction>): List<String> = availableActions.map(IntentionAction::getText) private fun extraFileNamePrefix(mainFileName: String): String = mainFileName.replace(".Main.kt", ".").replace(".Main.java", ".") protected fun guessFileType(file: TestFile): FileType = when { file.path.contains("." + KotlinFileType.EXTENSION) -> KotlinFileType.INSTANCE file.path.contains("." + JavaFileType.DEFAULT_EXTENSION) -> JavaFileType.INSTANCE else -> PlainTextFileType.INSTANCE } private fun findActionByPattern(pattern: Pattern, availableActions: List<IntentionAction>): IntentionAction? = availableActions.firstOrNull { pattern.matcher(it.text).matches() } fun doAction( text: String, file: PsiFile, editor: Editor, actionShouldBeAvailable: Boolean, testFilePath: String, getAvailableActions: () -> List<IntentionAction>, doHighlighting: () -> List<HighlightInfo>, shouldBeAvailableAfterExecution: Boolean = false ) { val pattern = if (text.startsWith("/")) Pattern.compile(text.substring(1, text.length - 1)) else Pattern.compile(StringUtil.escapeToRegexp(text)) val availableActions = getAvailableActions() val action = findActionByPattern(pattern, availableActions) if (action == null) { if (actionShouldBeAvailable) { val texts = getActionsTexts(availableActions) val infos = doHighlighting() TestCase.fail( "Action with text '" + text + "' is not available in test " + testFilePath + "\n" + "Available actions (" + texts.size + "): \n" + StringUtil.join(texts, "\n") + "\nActions:\n" + StringUtil.join(availableActions, "\n") + "\nInfos:\n" + StringUtil.join(infos, "\n") ) } else { DirectiveBasedActionUtils.checkAvailableActionsAreExpected(file, availableActions) } } else { if (!actionShouldBeAvailable) { TestCase.fail("Action '$text' is available (but must not) in test $testFilePath") } CodeInsightTestFixtureImpl.invokeIntention(action, file, editor) if (!shouldBeAvailableAfterExecution) { val afterAction = findActionByPattern(pattern, getAvailableActions()) if (afterAction != null) { TestCase.fail("Action '$text' is still available after its invocation in test $testFilePath") } } } } } }
apache-2.0
d3f9b3222625f8461ce2c9f405d32481
42.550562
158
0.581076
5.591057
false
true
false
false
smmribeiro/intellij-community
plugins/gradle/java/testSources/importing/AnnotationProcessorConfigImportingTest.kt
2
15894
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.importing import com.intellij.compiler.CompilerConfiguration import com.intellij.compiler.CompilerConfigurationImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.ModuleTypeId import com.intellij.openapi.util.Computable import com.intellij.testFramework.runInEdtAndGet import org.assertj.core.api.BDDAssertions.then import org.jetbrains.jps.model.java.impl.compiler.ProcessorConfigProfileImpl import org.jetbrains.plugins.gradle.GradleManager import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions import org.jetbrains.plugins.gradle.util.GradleConstants import org.junit.Test class AnnotationProcessorConfigImportingTest: GradleImportingTestCase() { @Test @TargetVersions("4.6+") fun `test annotation processor config imported in module per project mode`() { importProjectUsingSingeModulePerGradleProject( createBuildScriptBuilder() .withJavaPlugin() .withMavenCentral() .addPostfix( """ apply plugin: 'java' dependencies { compileOnly 'org.projectlombok:lombok:1.18.8' annotationProcessor 'org.projectlombok:lombok:1.18.8' } """.trimIndent()).generate()); val config = CompilerConfiguration.getInstance(myProject) as CompilerConfigurationImpl val moduleProcessorProfiles = config.moduleProcessorProfiles then(moduleProcessorProfiles) .describedAs("An annotation processor profile should be created for Gradle module") .hasSize(1) with (moduleProcessorProfiles[0]) { then(isEnabled).isTrue() then(isObtainProcessorsFromClasspath).isFalse() then(processorPath).contains("lombok") then(moduleNames).containsExactly("project") } importProjectUsingSingeModulePerGradleProject() val moduleProcessorProfilesAfterReImport = config.moduleProcessorProfiles then(moduleProcessorProfilesAfterReImport) .describedAs("Duplicate annotation processor profile should not appear") .hasSize(1) } @Test @TargetVersions("4.6+") fun `test annotation processor modification`() { importProjectUsingSingeModulePerGradleProject( createBuildScriptBuilder() .withJavaPlugin() .withMavenCentral() .addPostfix( """ apply plugin: 'java' dependencies { compileOnly 'org.projectlombok:lombok:1.18.8' annotationProcessor 'org.projectlombok:lombok:1.18.8' } """.trimIndent()).generate()); val config = CompilerConfiguration.getInstance(myProject) as CompilerConfigurationImpl val moduleProcessorProfiles = config.moduleProcessorProfiles then(moduleProcessorProfiles) .describedAs("An annotation processor profile should be created for Gradle module") .hasSize(1) importProjectUsingSingeModulePerGradleProject( createBuildScriptBuilder() .withJavaPlugin() .withMavenCentral() .addPostfix( """ apply plugin: 'java' dependencies { compileOnly 'com.google.dagger:dagger:2.24' annotationProcessor 'com.google.dagger:dagger-compiler:2.24' } """.trimIndent()).generate()); val modifiedProfiles = config.moduleProcessorProfiles then(modifiedProfiles) .describedAs("An annotation processor should be updated, not added") .hasSize(1) with (modifiedProfiles[0]) { then(isEnabled).isTrue() then(isObtainProcessorsFromClasspath).isFalse() then(processorPath) .describedAs("annotation processor config path should point to new annotation processor") .contains("dagger") then(moduleNames).containsExactly("project") } } @Test @TargetVersions("4.6+") fun `test annotation processor config imported in modules per source set mode`() { importProject( createBuildScriptBuilder() .withJavaPlugin() .withMavenCentral() .addPostfix( """ apply plugin: 'java' dependencies { compileOnly 'org.projectlombok:lombok:1.18.8' annotationProcessor 'org.projectlombok:lombok:1.18.8' } """.trimIndent()).generate()); val config = CompilerConfiguration.getInstance(myProject) as CompilerConfigurationImpl val moduleProcessorProfiles = config.moduleProcessorProfiles then(moduleProcessorProfiles) .describedAs("An annotation processor profile should be created for Gradle module") .hasSize(1) with (moduleProcessorProfiles[0]) { then(isEnabled).isTrue() then(isObtainProcessorsFromClasspath).isFalse() then(processorPath).contains("lombok") then(moduleNames).containsExactly("project.main") } } @Test @TargetVersions("4.6+") fun `test annotation processor config imported correctly for multimodule project`() { createProjectSubFile("settings.gradle", "include 'projectA', 'projectB'") importProject( createBuildScriptBuilder() .addPostfix( """ allprojects { apply plugin: 'java' repositories { maven { url 'https://repo.labs.intellij.net/repo1' } } dependencies { compileOnly 'org.projectlombok:lombok:1.18.8' annotationProcessor 'org.projectlombok:lombok:1.18.8' } } """.trimIndent()).generate()); val config = CompilerConfiguration.getInstance(myProject) as CompilerConfigurationImpl val moduleProcessorProfiles = config.moduleProcessorProfiles then(moduleProcessorProfiles) .describedAs("An annotation processor profile should be created for Gradle module") .hasSize(1) with (moduleProcessorProfiles[0]) { then(isEnabled).isTrue() then(isObtainProcessorsFromClasspath).isFalse() then(processorPath).contains("lombok") then(moduleNames).contains("project.main", "project.projectA.main", "project.projectB.main") } } @Test @TargetVersions("5.2+") fun `test annotation processor output folders imported properly`() { // default location for processor output when building by IDEA val ideaGeneratedDir = "generated" createProjectSubFile("src/main/$ideaGeneratedDir/Generated.java", "public class Generated {}"); // default location for processor output when building by Gradle val gradleGeneratedDir = "build/generated/sources/annotationProcessor/java/main" createProjectSubFile("$gradleGeneratedDir/Generated.java", "public class Generated {}"); val config = createBuildScriptBuilder() .withJavaPlugin() .withMavenCentral() .addPostfix( """ dependencies { annotationProcessor 'org.projectlombok:lombok:1.18.8' } """.trimIndent()).generate() // import with default settings: delegate build to gradle importProject(config); assertSources("project.main", gradleGeneratedDir) assertGeneratedSources("project.main", gradleGeneratedDir) currentExternalProjectSettings.delegatedBuild = false; // import with build by intellij idea importProject(config); assertSources("project.main", ideaGeneratedDir) assertGeneratedSources("project.main", ideaGeneratedDir) // subscribe to build delegation changes in current project (ExternalSystemApiUtil.getManager(GradleConstants.SYSTEM_ID) as GradleManager).runActivity(myProject) // switch delegation to gradle currentExternalProjectSettings.delegatedBuild = true GradleSettings.getInstance(myProject).publisher.onBuildDelegationChange(true, projectPath) assertSources("project.main", gradleGeneratedDir) assertGeneratedSources("project.main", gradleGeneratedDir) // switch delegation to idea currentExternalProjectSettings.delegatedBuild = false GradleSettings.getInstance(myProject).publisher.onBuildDelegationChange(false, projectPath) assertSources("project.main", ideaGeneratedDir) assertGeneratedSources("project.main", ideaGeneratedDir) } @Test @TargetVersions("4.6+") fun `test two different annotation processors`() { createProjectSubFile("settings.gradle", "include 'project1','project2'") importProject( createBuildScriptBuilder() .withMavenCentral() .addPostfix( """ | allprojects { apply plugin: 'java' } | project("project1") { | dependencies { | compileOnly 'org.projectlombok:lombok:1.18.8' | annotationProcessor 'org.projectlombok:lombok:1.18.8' | } | } | | project("project2") { | dependencies { | compileOnly 'com.google.dagger:dagger:2.24' | annotationProcessor 'com.google.dagger:dagger-compiler:2.24' | } | } """.trimMargin()).generate()); val config = CompilerConfiguration.getInstance(myProject) as CompilerConfigurationImpl val moduleProcessorProfiles = config.moduleProcessorProfiles then(moduleProcessorProfiles) .describedAs("Annotation processors profiles should be created correctly") .hasSize(2) .anyMatch { it.isEnabled && !it.isObtainProcessorsFromClasspath && it.processorPath.contains("lombok") && it.moduleNames == setOf("project.project1.main") } .anyMatch { it.isEnabled && !it.isObtainProcessorsFromClasspath && it.processorPath.contains("dagger") && it.moduleNames == setOf("project.project2.main") } } @Test @TargetVersions("4.6+") fun `test change modules included in processor profile`() { createProjectSubFile("settings.gradle", "include 'project1','project2'") importProject( createBuildScriptBuilder() .withMavenCentral() .addPostfix( """ | allprojects { apply plugin: 'java' } | project("project1") { | dependencies { | compileOnly 'org.projectlombok:lombok:1.18.8' | annotationProcessor 'org.projectlombok:lombok:1.18.8' | } | } """.trimMargin()).generate()); then((CompilerConfiguration.getInstance(myProject) as CompilerConfigurationImpl) .moduleProcessorProfiles) .describedAs("Annotation processor profile includes wrong module") .extracting("moduleNames") .containsExactly(setOf("project.project1.main")) importProject( createBuildScriptBuilder() .withMavenCentral() .addPostfix( """ | allprojects { apply plugin: 'java' } | project("project2") { | dependencies { | compileOnly 'org.projectlombok:lombok:1.18.8' | annotationProcessor 'org.projectlombok:lombok:1.18.8' | } | } """.trimMargin()).generate()); then((CompilerConfiguration.getInstance(myProject) as CompilerConfigurationImpl) .moduleProcessorProfiles) .describedAs("Annotation processor profile includes wrong module") .extracting("moduleNames") .containsExactly(setOf("project.project2.main")) } @Test @TargetVersions("4.6+") fun `test annotation processor with transitive deps`() { importProject( createBuildScriptBuilder() .withJavaPlugin() .withMavenCentral() .addPostfix( """ apply plugin: 'java' dependencies { annotationProcessor 'junit:junit:4.12' // this is not an annotation processor, but has transitive deps } """.trimIndent()).generate()); then((CompilerConfiguration.getInstance(myProject) as CompilerConfigurationImpl) .moduleProcessorProfiles[0] .processorPath) .describedAs("Annotation processor path should include junit and hamcrest") .contains("junit", "hamcrest") } @Test @TargetVersions("4.3+") fun `test gradle-apt-plugin settings are imported`() { importProject( createBuildScriptBuilder() .withMavenCentral() .addBuildScriptRepository("maven { url 'https://repo.labs.intellij.net/plugins-gradle-org' }") .addBuildScriptClasspath("net.ltgt.gradle:gradle-apt-plugin:0.21") .addPostfix(""" apply plugin: "net.ltgt.apt" apply plugin: 'java' dependencies { compileOnly("org.immutables:value-annotations:2.7.1") annotationProcessor("org.immutables:value:2.7.1") } """.trimIndent()).generate()); val config = CompilerConfiguration.getInstance(myProject) as CompilerConfigurationImpl val moduleProcessorProfiles = config.moduleProcessorProfiles then(moduleProcessorProfiles) .describedAs("An annotation processor profile should be created for Gradle module") .hasSize(1) with (moduleProcessorProfiles[0]) { then(isEnabled).isTrue() then(isObtainProcessorsFromClasspath).isFalse() then(processorPath).contains("immutables") then(moduleNames).containsExactly("project.main") } } @Test @TargetVersions("3.4+") fun `test custom annotation processor configurations are imported`() { importProject( createBuildScriptBuilder() .withJavaPlugin() .withMavenCentral() .addPostfix(""" apply plugin: 'java' configurations { apt } dependencies { compileOnly("org.immutables:value-annotations:2.7.1") apt("org.immutables:value:2.7.1") } compileJava { options.annotationProcessorPath = configurations.apt } """.trimIndent()).generate()); val config = CompilerConfiguration.getInstance(myProject) as CompilerConfigurationImpl val moduleProcessorProfiles = config.moduleProcessorProfiles then(moduleProcessorProfiles) .describedAs("An annotation processor profile should be created for Gradle module") .hasSize(1) with (moduleProcessorProfiles[0]) { then(isEnabled).isTrue() then(isObtainProcessorsFromClasspath).isFalse() then(processorPath).contains("immutables") then(moduleNames).containsExactly("project.main") } } @Test @TargetVersions("5.2+") fun `test annotation processor profiles of non gradle projects are not removed`() { val nonGradleModule = runInEdtAndGet { ApplicationManager.getApplication().runWriteAction(Computable { ModuleManager.getInstance(myProject).newModule(myProject.basePath!! + "/java_module", ModuleTypeId.JAVA_MODULE) }) } val config = CompilerConfiguration.getInstance(myProject) as CompilerConfigurationImpl val processorConfigProfileImpl = ProcessorConfigProfileImpl("other") processorConfigProfileImpl.addModuleName(nonGradleModule.name) config.addModuleProcessorProfile(processorConfigProfileImpl) importProject( createBuildScriptBuilder() .withJavaLibraryPlugin() .addCompileOnlyDependency("org.projectlombok:lombok:1.18.8") .addDependency("annotationProcessor", "org.projectlombok:lombok:1.18.8") .generate()); val annotationProcessingConfiguration = config.getAnnotationProcessingConfiguration(nonGradleModule) then(annotationProcessingConfiguration.name) .isEqualTo("other") } }
apache-2.0
3f0d7bcf42dea20dc398ef622ec3ac27
34.479911
140
0.676608
4.879951
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/reflect/KotlinCompilationReflection.kt
1
2038
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.gradleTooling.reflect import org.gradle.api.Named import org.jetbrains.kotlin.idea.gradleTooling.getMethodOrNull fun KotlinCompilationReflection(kotlinCompilation: Any): KotlinCompilationReflection = KotlinCompilationReflectionImpl(kotlinCompilation) interface KotlinCompilationReflection { val compilationName: String val gradleCompilation: Named val sourceSets: Collection<Named>? val compilationOutput: KotlinCompilationOutputReflection? val konanTargetName: String? val compileKotlinTaskName: String? } private class KotlinCompilationReflectionImpl(private val instance: Any) : KotlinCompilationReflection { override val gradleCompilation: Named get() = instance as Named override val compilationName: String by lazy { gradleCompilation.name } override val sourceSets: Collection<Named>? by lazy { instance.callReflectiveGetter("getKotlinSourceSets", logger) } override val compilationOutput: KotlinCompilationOutputReflection? by lazy { instance.callReflectiveAnyGetter("getOutput", logger)?.let { gradleOutput -> KotlinCompilationOutputReflection(gradleOutput) } } // Get konanTarget (for native compilations only). override val konanTargetName: String? by lazy { if (instance.javaClass.getMethodOrNull("getKonanTarget") == null) null else instance.callReflectiveAnyGetter("getKonanTarget", logger) ?.callReflectiveGetter("getName", logger) } override val compileKotlinTaskName: String? by lazy { instance.callReflectiveGetter("getCompileKotlinTaskName", logger) } companion object { private val logger: ReflectionLogger = ReflectionLogger(KotlinCompilationReflection::class.java) private const val NATIVE_COMPILATION_CLASS = "org.jetbrains.kotlin.gradle.plugin.mpp.AbstractKotlinNativeCompilation" } }
apache-2.0
e6e28cc64c46913a53aa136ac80bd746
42.382979
134
0.764475
5.293506
false
false
false
false
smmribeiro/intellij-community
python/python-features-trainer/src/com/jetbrains/python/ift/PythonLearningCourse.kt
1
6915
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.ift import com.intellij.openapi.application.ApplicationNamesInfo import com.jetbrains.python.PythonLanguage import com.jetbrains.python.ift.lesson.assistance.PythonEditorCodingAssistanceLesson import com.jetbrains.python.ift.lesson.basic.PythonContextActionsLesson import com.jetbrains.python.ift.lesson.basic.PythonSelectLesson import com.jetbrains.python.ift.lesson.basic.PythonSurroundAndUnwrapLesson import com.jetbrains.python.ift.lesson.completion.* import com.jetbrains.python.ift.lesson.essensial.PythonOnboardingTour import com.jetbrains.python.ift.lesson.navigation.PythonDeclarationAndUsagesLesson import com.jetbrains.python.ift.lesson.navigation.PythonFileStructureLesson import com.jetbrains.python.ift.lesson.navigation.PythonRecentFilesLesson import com.jetbrains.python.ift.lesson.navigation.PythonSearchEverywhereLesson import com.jetbrains.python.ift.lesson.refactorings.PythonInPlaceRefactoringLesson import com.jetbrains.python.ift.lesson.refactorings.PythonQuickFixesRefactoringLesson import com.jetbrains.python.ift.lesson.refactorings.PythonRefactorMenuLesson import com.jetbrains.python.ift.lesson.refactorings.PythonRenameLesson import com.jetbrains.python.ift.lesson.run.PythonDebugLesson import com.jetbrains.python.ift.lesson.run.PythonRunConfigurationLesson import training.dsl.LessonUtil import training.learn.CourseManager import training.learn.LessonsBundle import training.learn.course.LearningCourseBase import training.learn.course.LearningModule import training.learn.course.LessonType import training.learn.lesson.general.* import training.learn.lesson.general.assistance.CodeFormatLesson import training.learn.lesson.general.assistance.LocalHistoryLesson import training.learn.lesson.general.assistance.ParameterInfoLesson import training.learn.lesson.general.assistance.QuickPopupsLesson import training.learn.lesson.general.navigation.FindInFilesLesson import training.learn.lesson.general.refactorings.ExtractMethodCocktailSortLesson import training.learn.lesson.general.refactorings.ExtractVariableFromBubbleLesson class PythonLearningCourse : LearningCourseBase(PythonLanguage.INSTANCE.id) { override fun modules() = onboardingTour() + stableModules() + CourseManager.instance.findCommonModules("Git") private val disableOnboardingLesson get() = ApplicationNamesInfo.getInstance().fullProductNameWithEdition.equals("PyCharm Edu") private fun onboardingTour() = if (!disableOnboardingLesson) listOf( LearningModule(id = "Python.Onboarding", name = PythonLessonsBundle.message("python.onboarding.module.name"), description = PythonLessonsBundle.message("python.onboarding.module.description", LessonUtil.productName), primaryLanguage = langSupport, moduleType = LessonType.PROJECT) { listOf(PythonOnboardingTour()) } ) else emptyList() private fun stableModules() = listOf( LearningModule(id = "Python.EditorBasics", name = LessonsBundle.message("editor.basics.module.name"), description = LessonsBundle.message("editor.basics.module.description"), primaryLanguage = langSupport, moduleType = LessonType.SCRATCH) { fun ls(sampleName: String) = loadSample("EditorBasics/$sampleName") listOf( PythonContextActionsLesson(), GotoActionLesson(ls("Actions.py.sample")), PythonSelectLesson(), SingleLineCommentLesson(ls("Comment.py.sample")), DuplicateLesson(ls("Duplicate.py.sample")), MoveLesson("accelerate", ls("Move.py.sample")), CollapseLesson(ls("Collapse.py.sample")), PythonSurroundAndUnwrapLesson(), MultipleSelectionHtmlLesson(), ) }, LearningModule(id = "Python.CodeCompletion", name = LessonsBundle.message("code.completion.module.name"), description = LessonsBundle.message("code.completion.module.description"), primaryLanguage = langSupport, moduleType = LessonType.SCRATCH) { listOf( PythonBasicCompletionLesson(), PythonTabCompletionLesson(), PythonPostfixCompletionLesson(), PythonSmartCompletionLesson(), FStringCompletionLesson(), ) }, LearningModule(id = "Python.Refactorings", name = LessonsBundle.message("refactorings.module.name"), description = LessonsBundle.message("refactorings.module.description"), primaryLanguage = langSupport, moduleType = LessonType.SCRATCH) { fun ls(sampleName: String) = loadSample("Refactorings/$sampleName") listOf( PythonRefactorMenuLesson(), PythonRenameLesson(), ExtractVariableFromBubbleLesson(ls("ExtractVariable.py.sample")), ExtractMethodCocktailSortLesson(ls("ExtractMethod.py.sample")), PythonQuickFixesRefactoringLesson(), PythonInPlaceRefactoringLesson(), ) }, LearningModule(id = "Python.CodeAssistance", name = LessonsBundle.message("code.assistance.module.name"), description = LessonsBundle.message("code.assistance.module.description"), primaryLanguage = langSupport, moduleType = LessonType.SINGLE_EDITOR) { fun ls(sampleName: String) = loadSample("CodeAssistance/$sampleName") listOf( LocalHistoryLesson(), CodeFormatLesson(ls("CodeFormat.py.sample"), true), ParameterInfoLesson(ls("ParameterInfo.py.sample")), QuickPopupsLesson(ls("QuickPopups.py.sample")), PythonEditorCodingAssistanceLesson(ls("EditorCodingAssistance.py.sample")), ) }, LearningModule(id = "Python.Navigation", name = LessonsBundle.message("navigation.module.name"), description = LessonsBundle.message("navigation.module.description"), primaryLanguage = langSupport, moduleType = LessonType.PROJECT) { listOf( PythonSearchEverywhereLesson(), FindInFilesLesson("src/warehouse/find_in_files_sample.py"), PythonDeclarationAndUsagesLesson(), PythonFileStructureLesson(), PythonRecentFilesLesson(), ) }, LearningModule(id = "Python.RunAndDebug", name = LessonsBundle.message("run.debug.module.name"), description = LessonsBundle.message("run.debug.module.description"), primaryLanguage = langSupport, moduleType = LessonType.SINGLE_EDITOR) { listOf( PythonRunConfigurationLesson(), PythonDebugLesson(), ) }, ) }
apache-2.0
a070f67b84cd5ed2edf8a3a42e432cac
49.115942
140
0.718727
5.183658
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/WorldMapRegion.kt
1
2214
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes.PUTFIELD import org.objectweb.asm.Type.INT_TYPE import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 import java.util.* import kotlin.collections.HashMap class WorldMapRegion : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == Any::class.type } .and { it.instanceFields.count { it.type == HashMap::class.type } == 2 } .and { it.instanceFields.count { it.type == LinkedList::class.type } == 1 } class x : OrderMapper.InConstructor.Field(WorldMapRegion::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class y : OrderMapper.InConstructor.Field(WorldMapRegion::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class iconsList : OrderMapper.InConstructor.Field(WorldMapRegion::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == List::class.type } } class iconsMap : OrderMapper.InConstructor.Field(WorldMapRegion::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == HashMap::class.type } } class fonts : OrderMapper.InConstructor.Field(WorldMapRegion::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == HashMap::class.type } } @MethodParameters() class icons : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.arguments.size in 0..1 } .and { it.returnType == List::class.type } } }
mit
bf8fba60b021e390c799c7a2a1230ce2
46.12766
123
0.724481
4.092421
false
false
false
false
Flank/flank
test_runner/src/main/kotlin/ftl/domain/junit/JUnitTestMerge.kt
1
4260
package ftl.domain.junit import ftl.api.JUnitTest import ftl.run.exception.FlankGeneralError import ftl.util.stripNotNumbers import java.util.Locale fun JUnitTest.Result.mergeTestTimes(other: JUnitTest.Result?): JUnitTest.Result { if (other == null) return this if (this.testsuites == null) this.testsuites = mutableListOf() // newTestResult.mergeTestTimes(oldTestResult) // // for each new JUnitTestSuite, check if it exists on old // if JUnitTestSuite exists on both then merge test times this.testsuites?.forEach { testSuite -> val oldSuite = other.testsuites?.firstOrNull { it.name == testSuite.name } if (oldSuite != null) testSuite.mergeTestTimes(oldSuite) } return this } fun JUnitTest.Result.merge(other: JUnitTest.Result?): JUnitTest.Result { if (other == null) return this if (testsuites == null) testsuites = mutableListOf() other.testsuites?.forEach { testSuite -> val mergeCandidate = this.testsuites?.firstOrNull { it.name == testSuite.name } if (mergeCandidate == null) { this.testsuites?.add(testSuite) } else { mergeCandidate.merge(testSuite) } } return this } fun JUnitTest.Suite.merge(other: JUnitTest.Suite): JUnitTest.Suite { if (this.name != other.name) throw FlankGeneralError("Attempted to merge ${other.name} into ${this.name}") // tests, failures, errors this.tests = mergeInt(this.tests, other.tests) this.failures = mergeInt(this.failures, other.failures) this.errors = mergeInt(this.errors, other.errors) this.skipped = mergeInt(this.skipped, other.skipped) this.time = mergeDouble(this.time, other.time) if (this.testcases == null) this.testcases = mutableListOf() if (other.testcases?.isNotEmpty() == true) { this.testcases?.addAll(other.testcases!!) } return this } fun JUnitTest.Suite.mergeTestTimes(other: JUnitTest.Suite): JUnitTest.Suite { if (this.name != other.name) throw FlankGeneralError("Attempted to merge ${other.name} into ${this.name}") // For each new JUnitTestCase: // * if it failed then pull timing info from old // * remove if not successful in either new or old // if we ran no test cases then don't bother merging old times. if (this.testcases == null) return this val mergedTestCases = mutableListOf<JUnitTest.Case>() var mergedTime = 0.0 this.testcases?.forEach { testcase -> // if test was skipped or empty, then continue to skip it. if (testcase.skipped() || testcase.empty()) return@forEach val testcaseTime = testcase.time.stripNotNumbers() // if the test succeeded, use the new time value if (testcase.successful() && testcase.time != null) { mergedTime += testcaseTime.toDouble() mergedTestCases.add( JUnitTest.Case( name = testcase.name, classname = testcase.classname, time = testcaseTime ) ) return@forEach } // if the test we ran failed, copy timing from the last successful run val lastSuccessfulRun = other.testcases?.firstOrNull { it.successful() && it.name == testcase.name && it.classname == testcase.classname } ?: return@forEach val lastSuccessfulRunTime = lastSuccessfulRun.time.stripNotNumbers() if (lastSuccessfulRun.time != null) mergedTime += lastSuccessfulRunTime.toDouble() mergedTestCases.add( JUnitTest.Case( name = testcase.name, classname = testcase.classname, time = lastSuccessfulRunTime ) ) } this.testcases = mergedTestCases this.tests = mergedTestCases.size.toString() this.failures = "0" this.errors = "0" this.skipped = "0" this.time = mergedTime.toString() return this } private fun mergeInt(a: String?, b: String?): String { return (a.stripNotNumbers().toInt() + b.stripNotNumbers().toInt()).toString() } fun mergeDouble(a: String?, b: String?): String { return "%.3f".format(Locale.ROOT, (a.stripNotNumbers().toDouble() + b.stripNotNumbers().toDouble())) }
apache-2.0
9d1b855621e9b65e35d9bdc2dcf8619a
33.918033
110
0.648357
4.139942
false
true
false
false
gbaldeck/vue.kt
src/kotlin/io/gbaldeck/vuekt/wrapper/VueComponent.kt
1
2164
package io.gbaldeck.vuekt.wrapper import kotlin.reflect.KCallable import kotlin.reflect.KProperty interface VueKtDelegate abstract class VueComponent: VueCommon { abstract val template: dynamic open val elementName: String = _name() @JsName("beforeCreate") open fun beforeCreate(){} @JsName("created") open fun created(){} @JsName("beforeMount") open fun beforeMount(){} @JsName("mounted") open fun mounted(){} @JsName("beforeUpdate") open fun beforeUpdate(){} @JsName("updated") open fun updated(){} @JsName("activated") open fun activated(){} @JsName("deactivated") open fun deactivated(){} @JsName("beforeDestroy") open fun beforeDestroy(){} @JsName("destroyed") open fun destroyed(){} @JsName("errorCaptured") open fun errorCaptured(err: dynamic, vm: dynamic, info: String): Boolean? = undefined class Computed<out T>(private val method: KCallable<T>): VueKtDelegate { operator fun getValue(thisRef: Any?, property: KProperty<*>): T { return Pair(property.name, method.name).asDynamic() } } class Watch<T>(private val method: KCallable<T>): VueKtDelegate { private var value: dynamic = undefined constructor(initialValue: T, method: KCallable<T>): this(method){ value = initialValue } operator fun getValue(thisRef: Any?, property: KProperty<*>): dynamic { return Triple(property.name, value, method.name).asDynamic() } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { this.value = value } } inner class Ref<T>: VueKtDelegate { operator fun getValue(thisRef: Any, property: KProperty<*>): T { return Pair(property.name, { val propertyName = property.name js("this.\$refs[propertyName]") }).asDynamic() } } class Prop<T>: VueKtDelegate { operator fun getValue(thisRef: Any?, property: KProperty<*>): T { return property.name.asDynamic() } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { } } } inline fun <EMITDATA> VueComponent.emit(eventName: String, emitData: EMITDATA){ js("this.\$emit(eventName, emitData)") }
mit
9fa4f36e41438b5706f91595531c86e6
26.392405
87
0.673752
4.153551
false
false
false
false
leafclick/intellij-community
plugins/devkit/devkit-core/src/actions/NewThemeAction.kt
1
6269
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.actions import com.intellij.ide.fileTemplates.FileTemplateManager import com.intellij.ide.fileTemplates.FileTemplateUtil import com.intellij.ide.ui.UIThemeProvider import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtil import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import com.intellij.ui.components.CheckBox import com.intellij.ui.components.JBTextField import com.intellij.ui.layout.* import org.jetbrains.idea.devkit.DevKitBundle import org.jetbrains.idea.devkit.inspections.quickfix.PluginDescriptorChooser import org.jetbrains.idea.devkit.module.PluginModuleType import org.jetbrains.idea.devkit.util.DescriptorUtil import org.jetbrains.idea.devkit.util.PsiUtil import java.util.* import javax.swing.JComponent //TODO better undo support class NewThemeAction: AnAction() { private val THEME_JSON_TEMPLATE = "ThemeJson.json" private val THEME_PROVIDER_EP_NAME = UIThemeProvider.EP_NAME.name @Suppress("UsePropertyAccessSyntax") // IdeView#getOrChooseDirectory is not a getter override fun actionPerformed(e: AnActionEvent) { val view = e.getData(LangDataKeys.IDE_VIEW) ?: return val dir = view.getOrChooseDirectory() ?: return val module = e.getRequiredData(LangDataKeys.MODULE) val project = module.project val dialog = NewThemeDialog(project) dialog.show() if (dialog.exitCode == DialogWrapper.OK_EXIT_CODE) { val file = createThemeJson(dialog.name.text, dialog.isDark.isSelected, project, dir, module) view.selectElement(file) FileEditorManager.getInstance(project).openFile(file.virtualFile, true) registerTheme(dir, file, module) } } override fun update(e: AnActionEvent) { val module = e.getData(LangDataKeys.MODULE) e.presentation.isEnabled = module != null && (PsiUtil.isPluginModule(module) || PluginModuleType.get(module) is PluginModuleType) } private fun createThemeJson(themeName: String, isDark: Boolean, project: Project, dir: PsiDirectory, module: Module): PsiFile { val fileName = getThemeJsonFileName(themeName) val colorSchemeFilename = getThemeColorSchemeFileName(themeName) val template = FileTemplateManager.getInstance(project).getJ2eeTemplate(THEME_JSON_TEMPLATE) val editorSchemeProps = Properties() editorSchemeProps.setProperty("NAME", themeName) editorSchemeProps.setProperty("PARENT_SCHEME", if (isDark) "Darcula" else "Default") val editorSchemeTemplate = FileTemplateManager.getInstance(project).getJ2eeTemplate("ThemeEditorColorScheme.xml") val colorScheme = FileTemplateUtil.createFromTemplate(editorSchemeTemplate, colorSchemeFilename, editorSchemeProps, dir) val props = Properties() props.setProperty("NAME", themeName) props.setProperty("IS_DARK", isDark.toString()) props.setProperty("COLOR_SCHEME_NAME", getSourceRootRelativeLocation(module, colorScheme as PsiFile)) val created = FileTemplateUtil.createFromTemplate(template, fileName, props, dir) assert(created is PsiFile) return created as PsiFile } private fun getThemeJsonFileName(themeName: String): String { return FileUtil.sanitizeFileName(themeName) + ".theme.json" } private fun getThemeColorSchemeFileName(themeName: String): String { return FileUtil.sanitizeFileName(themeName) + ".xml" } private fun registerTheme(dir: PsiDirectory, file: PsiFile, module: Module) { val relativeLocation = getSourceRootRelativeLocation(module, file) ?: return val pluginXml = DevkitActionsUtil.choosePluginModuleDescriptor(dir) ?: return DescriptorUtil.checkPluginXmlsWritable(module.project, pluginXml) val domFileElement = DescriptorUtil.getIdeaPluginFileElement(pluginXml) WriteCommandAction.writeCommandAction(module.project, pluginXml).run<Throwable> { val extensions = PluginDescriptorChooser.findOrCreateExtensionsForEP(domFileElement, THEME_PROVIDER_EP_NAME) val extensionTag = extensions.addExtension(THEME_PROVIDER_EP_NAME).xmlTag extensionTag.setAttribute("id", getRandomId()) extensionTag.setAttribute("path", relativeLocation) } } private fun getSourceRootRelativeLocation(module: Module, file: PsiFile): String? { val rootManager = ModuleRootManager.getInstance(module) val sourceRoots = rootManager.getSourceRoots(false) val virtualFile = file.virtualFile var relativeLocation : String? = null for (sourceRoot in sourceRoots) { if (!VfsUtil.isAncestor(sourceRoot,virtualFile,true)) continue relativeLocation = VfsUtil.getRelativeLocation(virtualFile, sourceRoot) ?: continue break } return "/${relativeLocation}" } private fun getRandomId() = UUID.randomUUID().toString() class NewThemeDialog(project: Project) : DialogWrapper(project) { val name = JBTextField() val isDark = CheckBox(DevKitBundle.message("new.theme.dialog.is.dark.checkbox.text"), true) init { title = DevKitBundle.message("new.theme.dialog.title") init() } override fun createCenterPanel(): JComponent? { return panel { row(DevKitBundle.message("new.theme.dialog.name.text.field.text")) { cell { name(growPolicy = GrowPolicy.MEDIUM_TEXT) .focused() //TODO max name length, maybe some other restrictions? .withErrorOnApplyIf(DevKitBundle.message("new.theme.dialog.name.empty")) { it.text.isBlank() } } } row("") { cell { isDark() } } } } } }
apache-2.0
f0a4eea72dc66d9f1e3ac4d6ca843fd0
41.073826
140
0.742862
4.612951
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/adapters/EntryLinkAdapter.kt
1
1970
package io.github.feelfreelinux.wykopmobilny.ui.adapters import android.view.ViewGroup import io.github.feelfreelinux.wykopmobilny.base.adapter.AdvancedProgressAdapter import io.github.feelfreelinux.wykopmobilny.models.dataclass.EntryLink import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.BlockedViewHolder import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.LinkViewHolder import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.SimpleLinkViewHolder import io.github.feelfreelinux.wykopmobilny.utils.preferences.SettingsPreferencesApi import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi import javax.inject.Inject class EntryLinkAdapter @Inject constructor( val userManagerApi: UserManagerApi, val settingsPreferencesApi: SettingsPreferencesApi ) : AdvancedProgressAdapter<EntryLink>() { companion object { const val ENTRY_VIEWTYPE = 1 const val LINK_VIEWTYPE = 2 const val SIMPLE_LINK_VIEWTYPE = 3 } override fun getItemViewType(position: Int): Int = when { dataset[position] == null -> AdvancedProgressAdapter.VIEWTYPE_PROGRESS dataset[position]!!.entry != null -> ENTRY_VIEWTYPE else -> if (settingsPreferencesApi.linkSimpleList) SIMPLE_LINK_VIEWTYPE else LINK_VIEWTYPE } override fun createViewHolder(viewType: Int, parent: ViewGroup): androidx.recyclerview.widget.RecyclerView.ViewHolder = BlockedViewHolder.inflateView(parent, { notifyItemChanged(it) }) override fun bindHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) { val item = dataset[position]!! if (item.entry != null) { (holder as BlockedViewHolder).bindView(item.entry!!) } else if (item.link != null) { if (holder is SimpleLinkViewHolder) holder.bindView(item.link!!) else (holder as? LinkViewHolder)?.bindView(item.link!!) } } }
mit
79c3da0881bf7a24164ffb016b28e8f0
45.904762
123
0.756853
4.624413
false
false
false
false
siosio/intellij-community
platform/core-impl/src/com/intellij/ide/plugins/PluginSet.kt
1
6900
// 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 import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginId import com.intellij.util.graph.DFSTBuilder import com.intellij.util.lang.Java11Shim import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import java.util.* // if otherwise not specified, `module` in terms of v2 plugin model @ApiStatus.Internal class PluginSet internal constructor( @JvmField val allPlugins: List<IdeaPluginDescriptorImpl>, @JvmField val enabledPlugins: List<IdeaPluginDescriptorImpl>, private val enabledModuleMap: Map<String, PluginContentDescriptor.ModuleItem>, private val enabledPluginAndV1ModuleMap: Map<PluginId, IdeaPluginDescriptorImpl>, ) { companion object { // special case - raw plugin set where everything is enabled and resolved fun createRawPluginSet(plugins: List<IdeaPluginDescriptorImpl>): PluginSet { val java11Shim = Java11Shim.INSTANCE val enabledModuleV2Ids = HashMap<String, PluginContentDescriptor.ModuleItem>() val enabledPluginAndModuleV1Map = HashMap<PluginId, IdeaPluginDescriptorImpl>(plugins.size) for (descriptor in plugins) { addWithV1Modules(enabledPluginAndModuleV1Map, descriptor) for (item in descriptor.content.modules) { enabledModuleV2Ids[item.name] = item } } return PluginSet( allPlugins = plugins, enabledPlugins = plugins, enabledModuleMap = java11Shim.copyOf(enabledModuleV2Ids), enabledPluginAndV1ModuleMap = java11Shim.copyOf(enabledPluginAndModuleV1Map), ) } fun createPluginSet(allPlugins: List<IdeaPluginDescriptorImpl>, enabledPlugins: List<IdeaPluginDescriptorImpl>): PluginSet { val enabledModuleV2Ids = HashMap<String, PluginContentDescriptor.ModuleItem>() val enabledPluginAndModuleV1Map = HashMap<PluginId, IdeaPluginDescriptorImpl>(enabledPlugins.size) val log = PluginManagerCore.getLogger() val isDebugLogEnabled = log.isDebugEnabled || !System.getProperty("plugin.classloader.debug", "").isEmpty() for (descriptor in enabledPlugins) { addWithV1Modules(enabledPluginAndModuleV1Map, descriptor) checkModules(descriptor, enabledPluginAndModuleV1Map, enabledModuleV2Ids, isDebugLogEnabled, log) } val java11Shim = Java11Shim.INSTANCE return PluginSet( allPlugins = java11Shim.copyOf(allPlugins), enabledPlugins = java11Shim.copyOf(enabledPlugins), enabledModuleMap = java11Shim.copyOf(enabledModuleV2Ids), enabledPluginAndV1ModuleMap = java11Shim.copyOf(enabledPluginAndModuleV1Map), ) } fun addWithV1Modules(result: MutableMap<PluginId, IdeaPluginDescriptorImpl>, descriptor: IdeaPluginDescriptorImpl) { result[descriptor.id] = descriptor for (module in descriptor.modules) { result[module] = descriptor } } fun getOnlyEnabledPlugins(sortedAll: Collection<IdeaPluginDescriptorImpl>): List<IdeaPluginDescriptorImpl> { return sortedAll.filterTo(ArrayList(sortedAll.size)) { it.isEnabled } } fun checkModules(descriptor: IdeaPluginDescriptorImpl, enabledPluginIds: Map<PluginId, IdeaPluginDescriptorImpl>, enabledModuleV2Ids: MutableMap<String, PluginContentDescriptor.ModuleItem>, isDebugLogEnabled: Boolean, log: Logger) { m@ for (item in descriptor.content.modules) { for (ref in item.requireDescriptor().dependencies.modules) { if (!enabledModuleV2Ids.containsKey(ref.name)) { if (isDebugLogEnabled) { log.info("Module ${item.name} is not enabled because dependency ${ref.name} is not available") } continue@m } } for (ref in item.requireDescriptor().dependencies.plugins) { if (!enabledPluginIds.containsKey(ref.id)) { if (isDebugLogEnabled) { log.info("Module ${item.name} is not enabled because dependency ${ref.id} is not available") } continue@m } } enabledModuleV2Ids[item.name] = item } } } @TestOnly fun getUnsortedEnabledModules(): Collection<PluginContentDescriptor.ModuleItem> = ArrayList(enabledModuleMap.values) fun isPluginEnabled(id: PluginId) = enabledPluginAndV1ModuleMap.containsKey(id) fun findEnabledPlugin(id: PluginId): IdeaPluginDescriptorImpl? = enabledPluginAndV1ModuleMap[id] fun findEnabledModule(id: String): IdeaPluginDescriptorImpl? = enabledModuleMap[id]?.requireDescriptor() fun isModuleEnabled(id: String) = enabledModuleMap.containsKey(id) fun enablePlugin(descriptor: IdeaPluginDescriptorImpl): PluginSet { // in tests or on install plugin is not in all plugins // linear search is ok here - not a hot method PluginManagerCore.getLogger().assertTrue(!enabledPlugins.contains(descriptor)) return createPluginSet( allPlugins = if (descriptor in allPlugins) allPlugins else sortTopologically(allPlugins + descriptor), enabledPlugins = sortTopologically(enabledPlugins + descriptor), ) } fun sortTopologically( descriptors: List<IdeaPluginDescriptorImpl>, withOptional: Boolean = true, ): List<IdeaPluginDescriptorImpl> { val graph = CachingSemiGraph.createPluginIdGraph(descriptors, pluginSet = this, withOptional) val comparator = DFSTBuilder(graph).comparator() // there is circular reference between core and implementation-detail plugin, as not all such plugins extracted from core, // so, ensure that core plugin is always first (otherwise not possible to register actions - parent group not defined) // don't use sortWith here - avoid loading kotlin stdlib val sortedRequired = descriptors.toTypedArray() Arrays.sort(sortedRequired, Comparator { o1, o2 -> when (PluginManagerCore.CORE_ID) { o1.id -> -1 o2.id -> 1 else -> comparator.compare(o1.id, o2.id) } }) @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog", "UNCHECKED_CAST") return Java11Shim.INSTANCE.listOf(sortedRequired) } fun updateEnabledPlugins(): PluginSet = updateEnabledPlugins(allPlugins) fun removePluginAndUpdateEnabledPlugins(descriptor: IdeaPluginDescriptorImpl): PluginSet { // not just remove from enabledPlugins - maybe another plugins in list also disabled as result of plugin unloading return updateEnabledPlugins(allPlugins - descriptor) } private fun updateEnabledPlugins(allPlugins: List<IdeaPluginDescriptorImpl>): PluginSet { return createPluginSet( allPlugins, enabledPlugins = getOnlyEnabledPlugins(allPlugins), ) } }
apache-2.0
bdf419b911bb50e2e5de3a4788596181
43.522581
158
0.728116
4.771784
false
false
false
false
ReplayMod/ReplayMod
src/main/kotlin/com/replaymod/simplepathing/gui/GuiPathingKt.kt
1
17564
package com.replaymod.simplepathing.gui import com.google.common.util.concurrent.FutureCallback import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.ListenableFuture import com.replaymod.core.ReplayMod import com.replaymod.core.gui.common.UIButton import com.replaymod.core.gui.common.UITexture import com.replaymod.core.gui.common.scrollbar.UITexturedScrollBar import com.replaymod.core.gui.common.timeline.UITimeline import com.replaymod.core.gui.common.timeline.UITimelineTime import com.replaymod.core.gui.utils.* import com.replaymod.core.utils.i18n import com.replaymod.core.versions.MCVer.Keyboard import com.replaymod.pathing.player.RealtimeTimelinePlayer import com.replaymod.render.gui.GuiRenderQueue import com.replaymod.render.gui.GuiRenderSettings import com.replaymod.replay.ReplayHandler import com.replaymod.replaystudio.pathing.change.CombinedChange import com.replaymod.simplepathing.SPTimeline import com.replaymod.simplepathing.SPTimeline.SPPath import com.replaymod.simplepathing.Setting import com.replaymod.simplepathing.gui.panels.UIPositionKeyframePanel import com.replaymod.simplepathing.gui.panels.UIPositionOffsetPanel import com.replaymod.simplepathing.gui.panels.UITimeOffsetPanel import com.replaymod.simplepathing.gui.panels.UITimePanel import de.johni0702.minecraft.gui.popup.GuiInfoPopup import gg.essential.elementa.components.UIContainer import gg.essential.elementa.constraints.* import gg.essential.elementa.dsl.* import gg.essential.elementa.state.State import net.minecraft.client.resource.language.I18n import java.util.concurrent.CancellationException import kotlin.time.Duration class GuiPathingKt( val java: GuiPathing, val replayHandler: ReplayHandler, ) { val state = KeyframeState(java.mod, this) private val overlay = replayHandler.overlay private val mod = java.mod private val core = mod.core private val window = overlay.kt.window private val player = RealtimeTimelinePlayer(replayHandler) private val isCtrlDown = window.pollingState { Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) } private val isShiftDown = window.pollingState { Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) } private val playing = window.pollingState { player.isActive } init { window.onAnimationFrame { state.update() } window.onBoxSelection { components, _ -> state.selection.set(KeyframeState.Selection.EMPTY.mutate { for (keyframe in components.filterIsInstance<UITimelineKeyframes.UIKeyframe>()) { this[keyframe.type.path] += keyframe.time } }) } } private val secondRow by UIContainer().constrain { x = CenterConstraint() y = 30.pixels /* topPanel.bottom */ + 13.pixels width = 100.percent - 20.pixels height = 20.pixels } childOf window private val playPauseButton by UIButton().constrain { width = 20.pixels height = 20.pixels }.texture(ReplayMod.TEXTURE, playing.map { UITexture.TextureData.ofSize(0, if (it) 20 else 0, 20, 20) }).addTooltip { addLine { bindText(playing.zip(isCtrlDown).map { (playing, isCtrlDown) -> when { playing -> "replaymod.gui.ingame.menu.pausepath" isCtrlDown -> "replaymod.gui.ingame.menu.playpathfromstart" else -> "replaymod.gui.ingame.menu.playpath" }.i18n() }) } }.onMouseClick { if (player.isActive) { player.future.cancel(false) } else { val ignoreTimeKeyframes = isShiftDown.get() val timeline = java.preparePathsForPlayback(ignoreTimeKeyframes).okOrElse { err -> GuiInfoPopup.open(overlay, *err) null } ?: return@onMouseClick val timePath = SPTimeline(timeline).timePath timePath.isActive = !ignoreTimeKeyframes // Start from cursor time unless the control key is pressed (then start from beginning) val startTime = if (isCtrlDown.get()) Duration.ZERO else [email protected]() val future: ListenableFuture<Void> = player.start(timeline, startTime.inWholeMilliseconds) overlay.isCloseable = false overlay.isMouseVisible = true core.printInfoToChat("replaymod.chat.pathstarted") Futures.addCallback(future, object : FutureCallback<Void?> { override fun onSuccess(result: Void?) { if (future.isCancelled) { core.printInfoToChat("replaymod.chat.pathinterrupted") } else { core.printInfoToChat("replaymod.chat.pathfinished") } overlay.isCloseable = true } override fun onFailure(t: Throwable) { if (t !is CancellationException) { t.printStackTrace() } overlay.isCloseable = true } //#if MC>=11800 //$$ }, Runnable::run) //#else }) //#endif } } childOf secondRow private val renderButton by UIButton().constrain { x = SiblingConstraint(5f) width = 20.pixels height = 20.pixels }.texture(ReplayMod.TEXTURE, UITexture.TextureData.ofSize(40, 0, 20, 20)) { }.addTooltip { addLine("replaymod.gui.ingame.menu.renderpath".i18n()) }.onMouseClick { abortPathPlayback() val screen = GuiRenderSettings.createBaseScreen() object : GuiRenderQueue(screen, replayHandler, { java.preparePathsForPlayback(false) }) { override fun close() { super.close() minecraft.openScreen(null) } }.open() screen.display() } childOf secondRow private data class PositionButtonType( val type: KeyframeType = KeyframeType.POSITION, val remove: Boolean = false, ) private val positionKeyframeButtonType = window.pollingState(PositionButtonType()) { val keyframe = state.selectedPositionKeyframes.get().values.firstOrNull() PositionButtonType(when { keyframe?.entityId != null -> KeyframeType.SPECTATOR keyframe == null && !replayHandler.isCameraView -> KeyframeType.SPECTATOR else -> KeyframeType.POSITION }, keyframe != null) } private val positionKeyframeButton by UIButton().constrain { x = SiblingConstraint(5f) width = 20.pixels height = 20.pixels }.texture(ReplayMod.TEXTURE, positionKeyframeButtonType.map { (type, remove) -> type.buttonIcon.offset(0, if (remove) 20 else 0) }).addTooltip { addLine { bindText(positionKeyframeButtonType.map { (type, remove) -> type.tooltip(!remove).i18n() + " (" + mod.keyPositionKeyframe.boundKey + ")" }) } }.onMouseClick { toggleKeyframe(positionKeyframeButtonType.get().type) } childOf secondRow private val timeKeyframePresent: State<Boolean> = window.pollingState(false) { val keyframe = state.selectedTimeKeyframes.get().values.firstOrNull() keyframe != null } private val timeKeyframeButton by UIButton().constrain { x = SiblingConstraint(5f) width = 20.pixels height = 20.pixels }.texture(ReplayMod.TEXTURE, timeKeyframePresent.map { present -> KeyframeType.TIME.buttonIcon.offset(0, if (present) 20 else 0) }).addTooltip { addLine { bindText(timeKeyframePresent.map { present -> KeyframeType.TIME.tooltip(!present).i18n() + " (" + mod.keyTimeKeyframe.boundKey + ")" }) } }.onMouseClick { toggleKeyframe(KeyframeType.TIME) } childOf secondRow private val unusedButton by UIContainer().constrain { x = SiblingConstraint(5f) width = 25.pixels height = 20.pixels } childOf secondRow val timeline by UITimeline().constrain { x = SiblingConstraint(5f) width = FillConstraint(false) height = 20.pixels }.apply { enableIndicators() enableZooming() zoom.set(0.1f) length.set(Duration.seconds(core.settingsRegistry.get(Setting.TIMELINE_LENGTH))) content.insertChildBefore(UITimelineKeyframes(state, overlay.timeline), cursor) }.onLeftMouse { mouseX, _ -> val time = getTimeAt(mouseX) cursor.position.set(time) state.selection.set(KeyframeState.Selection.EMPTY) }.onLeftClick { it.stopImmediatePropagation() }.onAnimationFrame { if (player.isActive) { cursor.position.set(Duration.milliseconds(player.timePassed)) cursor.ensureVisibleWithPadding() } } childOf secondRow private val belowTimeline by UIContainer().constrain { x = 0.pixels boundTo timeline y = SiblingConstraint(1f) boundTo timeline width = CopyConstraintFloat() boundTo timeline height = 9.pixels } childOf window private val belowTimelineButtons by UIContainer().constrain { width = ChildBasedSizeConstraint() height = 100.percent } childOf belowTimeline private val scrollbar by UITexturedScrollBar().constrain { x = SiblingConstraint(2f) width = FillConstraint(useSiblings = false) height = 100.percent }.apply { timeline.content.setHorizontalScrollBarComponent(grip) } childOf belowTimeline private val timelineTime by UITimelineTime(timeline).constrain { x = 0.pixels boundTo timeline y = SiblingConstraint(alignOpposite = true) boundTo timeline width = CopyConstraintFloat() boundTo timeline height = 8.pixels } childOf window private val zoomInButton by UIButton().constrain { x = SiblingConstraint(2f) width = 9.pixels height = 9.pixels }.texture(ReplayMod.TEXTURE, UITexture.TextureData.ofSize(40, 20, 9, 9)) { }.addTooltip { addLine("replaymod.gui.ingame.menu.zoomin".i18n()) }.onMouseClick { timeline.zoom.set { it * 2 / 3 } } childOf belowTimelineButtons private val zoomOutButton by UIButton().constrain { x = SiblingConstraint(2f) width = 9.pixels height = 9.pixels }.texture(ReplayMod.TEXTURE, UITexture.TextureData.ofSize(40, 30, 9, 9)) { }.addTooltip { addLine("replaymod.gui.ingame.menu.zoomout".i18n()) }.onMouseClick { timeline.zoom.set { it * 3 / 2 } } childOf belowTimelineButtons private val positionKeyframePanel by UIPositionKeyframePanel(state).apply { overlay.kt.bottomRightPanel.insertChildAt(toggleButton, 0) } hiddenChildOf window private val timePanel by UITimePanel(state).constrain { x = 0.pixels boundTo belowTimeline y = SiblingConstraint(1f) boundTo belowTimeline }.apply { belowTimelineButtons.insertChildAt(toggleButton.constrain { x = SiblingConstraint(2f) }, 0) } hiddenChildOf window private val timeOffsetPanel by UITimeOffsetPanel(state, timePanel).constrain { x = 0.pixels boundTo secondRow y = SiblingConstraint(1f) boundTo belowTimeline width = basicWidthConstraint { timePanel.getLeft() - 5f - it.getLeft() } } hiddenChildOf window val positionOffsetPanel by UIPositionOffsetPanel(window, state).apply { toggleButton.constrain { x = SiblingConstraint(4f) y = 0.pixels(alignOpposite = true) } overlay.kt.bottomLeftPanel.insertChildAt(toggleButton, 0) } hiddenChildOf window init { val speedValue = window.pollingState { overlay.speedSlider.value } val replayTime = window.pollingState { replayHandler.replaySender.currentTimeStamp() } speedValue.zip(replayTime).onSetValue { if (mod.keySyncTime.isAutoActivating && !player.isActive) { syncTimeButtonPressed() } } } fun abortPathPlayback() { if (!player.isActive) { return } val future = player.future if (!future.isDone && !future.isCancelled) { future.cancel(false) } // Tear down of the player might only happen the next tick after it was cancelled player.onTick() } private fun computeSyncTime(cursor: Duration): Duration? { // Current replay time val currentReplayTime = Duration.milliseconds(replayHandler.replaySender.currentTimeStamp()) // Get the last time keyframe before the cursor val (keyframeCursor, keyframe) = state.timeKeyframes.get().entries.findLast { (time, _) -> time <= cursor } ?: return null val keyframeReplayTime = keyframe.replayTime // Replay time passed val replayTimePassed = currentReplayTime - keyframeReplayTime // Speed (set to 1 when shift is held) val speed = if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) 1.0 else overlay.speedSliderValue // Cursor time passed val cursorPassed = replayTimePassed / speed // Return new position return keyframeCursor + cursorPassed } fun syncTimeButtonPressed() { // Position of the cursor var cursor = timeline.cursor.position.get() // Update cursor once cursor = computeSyncTime(cursor) ?: return // no keyframes before cursor, nothing we can do // Repeatedly update until we find a fix point while (true) { // If the cursor has gotten stuck before in front of all keyframes, // let's just use the last value we got, this shouldn't happen with ordinary timelines anyway. val updatedCursor = computeSyncTime(cursor) ?: break if (updatedCursor == cursor) { // Found the fix point, we can stop now break } if (updatedCursor < cursor) { // We've gone backwards, we'll likely get stuck in a loop, so abort the whole thing return } // Found a new position, take it, repeat cursor = updatedCursor } // Move cursor to new position timeline.cursor.position.set(cursor) timeline.cursor.ensureVisibleWithPadding() // Deselect keyframe to allow the user to add a new one right away state.selection.set(KeyframeState.Selection.EMPTY) } @JvmOverloads fun toggleKeyframe(type: KeyframeType, neverSpectator: Boolean = false) { val path = type.path val time = timeline.cursor.position.get() val timeline = mod.currentTimeline if (state.keyframes.values.all { it.get().isEmpty() } && time > Duration.seconds(1)) { val text = I18n.translate("replaymod.gui.ingame.first_keyframe_not_at_start_warning") GuiInfoPopup.open(overlay, *text.split("\\n").toTypedArray()) } val selection = state.selection.get()[path] if (selection.isEmpty()) { // Nothing selected, create new keyframe // If a keyframe is already present at this time, cannot add another one if (time in state[path].get()) { return } when (path) { SPPath.TIME -> { timeline.addTimeKeyframe(time.inWholeMilliseconds, replayHandler.replaySender.currentTimeStamp()) } SPPath.POSITION -> { val camera = replayHandler.cameraEntity var spectatedId = -1 if (!replayHandler.isCameraView && !neverSpectator) { // FIXME preprocessor bug: there are mappings for this //#if MC>=11700 // spectatedId = replayHandler.overlay.minecraft.getCameraEntity()!!.id //#else spectatedId = replayHandler.overlay.minecraft.getCameraEntity()!!.entityId //#endif } timeline.addPositionKeyframe(time.inWholeMilliseconds, camera.x, camera.y, camera.z, camera.yaw, camera.pitch, camera.roll, spectatedId) } } } else { // Keyframe(s) selected, remove them state.selection.set { it.mutate { this[path].clear() } } val changes = selection.map { timeline.removeKeyframe(path, it.inWholeMilliseconds) } timeline.timeline.pushChange(CombinedChange.createFromApplied(*changes.toTypedArray())) } state.update() } fun deleteButtonPressed(): Boolean { val timeline = mod.currentTimeline ?: return false val selection = state.selection.get().toMap() if (selection.all { it.value.isEmpty() }) { return false } state.selection.set(KeyframeState.Selection.EMPTY) val changes = selection.flatMap { (path, keyframes) -> keyframes.map { timeline.removeKeyframe(path, it.inWholeMilliseconds) } } timeline.timeline.pushChange(CombinedChange.createFromApplied(*changes.toTypedArray())) return true } }
gpl-3.0
ba57bc69ae2b6cd8151bdcfa52c292f6
38.295302
117
0.633626
4.500128
false
false
false
false
ncoe/rosetta
Peaceful_chess_queen_armies/Kotlin/src/Peaceful.kt
1
3109
import kotlin.math.abs enum class Piece { Empty, Black, White, } typealias Position = Pair<Int, Int> fun place(m: Int, n: Int, pBlackQueens: MutableList<Position>, pWhiteQueens: MutableList<Position>): Boolean { if (m == 0) { return true } var placingBlack = true for (i in 0 until n) { inner@ for (j in 0 until n) { val pos = Position(i, j) for (queen in pBlackQueens) { if (queen == pos || !placingBlack && isAttacking(queen, pos)) { continue@inner } } for (queen in pWhiteQueens) { if (queen == pos || placingBlack && isAttacking(queen, pos)) { continue@inner } } placingBlack = if (placingBlack) { pBlackQueens.add(pos) false } else { pWhiteQueens.add(pos) if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true } pBlackQueens.removeAt(pBlackQueens.lastIndex) pWhiteQueens.removeAt(pWhiteQueens.lastIndex) true } } } if (!placingBlack) { pBlackQueens.removeAt(pBlackQueens.lastIndex) } return false } fun isAttacking(queen: Position, pos: Position): Boolean { return queen.first == pos.first || queen.second == pos.second || abs(queen.first - pos.first) == abs(queen.second - pos.second) } fun printBoard(n: Int, blackQueens: List<Position>, whiteQueens: List<Position>) { val board = MutableList(n * n) { Piece.Empty } for (queen in blackQueens) { board[queen.first * n + queen.second] = Piece.Black } for (queen in whiteQueens) { board[queen.first * n + queen.second] = Piece.White } for ((i, b) in board.withIndex()) { if (i != 0 && i % n == 0) { println() } if (b == Piece.Black) { print("B ") } else if (b == Piece.White) { print("W ") } else { val j = i / n val k = i - j * n if (j % 2 == k % 2) { print("• ") } else { print("◦ ") } } } println('\n') } fun main() { val nms = listOf( Pair(2, 1), Pair(3, 1), Pair(3, 2), Pair(4, 1), Pair(4, 2), Pair(4, 3), Pair(5, 1), Pair(5, 2), Pair(5, 3), Pair(5, 4), Pair(5, 5), Pair(6, 1), Pair(6, 2), Pair(6, 3), Pair(6, 4), Pair(6, 5), Pair(6, 6), Pair(7, 1), Pair(7, 2), Pair(7, 3), Pair(7, 4), Pair(7, 5), Pair(7, 6), Pair(7, 7) ) for ((n, m) in nms) { println("$m black and $m white queens on a $n x $n board:") val blackQueens = mutableListOf<Position>() val whiteQueens = mutableListOf<Position>() if (place(m, n, blackQueens, whiteQueens)) { printBoard(n, blackQueens, whiteQueens) } else { println("No solution exists.\n") } } }
mit
a769faebcd8d0d6a52d00706d9ddc649
29.145631
110
0.482448
3.469274
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/AbstractNameSuggestionProviderTest.kt
4
1832
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring import com.intellij.codeInsight.TargetElementUtil import com.intellij.psi.PsiElement import com.intellij.refactoring.rename.NameSuggestionProvider import com.intellij.refactoring.rename.PreferrableNameSuggestionProvider import junit.framework.TestCase import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.ProjectDescriptorWithStdlibSources import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils abstract class AbstractNameSuggestionProviderTest : KotlinLightCodeInsightFixtureTestCase() { private fun getSuggestNames(element: PsiElement): List<String> { val names = HashSet<String>() for (provider in NameSuggestionProvider.EP_NAME.extensions) { val info = provider.getSuggestedNames(element, null, names) if (info != null) { if (provider is PreferrableNameSuggestionProvider && !provider.shouldCheckOthers()) break } } return names.sorted() } protected fun doTest(path: String) { val file = myFixture.configureByFile(fileName()) val targetElement = TargetElementUtil.findTargetElement( myFixture.editor, TargetElementUtil.ELEMENT_NAME_ACCEPTED or TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED )!! val expectedNames = InTextDirectivesUtils.findListWithPrefixes(file.text, "// SUGGESTED_NAMES: ") val actualNames = getSuggestNames(targetElement) TestCase.assertEquals(expectedNames, actualNames) } override fun getProjectDescriptor() = ProjectDescriptorWithStdlibSources.INSTANCE }
apache-2.0
187035c17c230614718535eb8a2578be
47.236842
158
0.756004
5.279539
false
true
false
false
hugh114/HPaste
app/src/main/java/com/hugh/paste/HomeActivity.kt
1
1944
package com.hugh.paste import android.content.Intent import android.os.Bundle import android.view.View import com.hugh.paste.app.BaseActivity import com.hugh.paste.utils.HPrefs import kotlinx.android.synthetic.main.activity_home.* import kotlinx.android.synthetic.main.layout_title.* /** * Created by hugh on 2017/9/29. */ class HomeActivity: BaseActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) //start service val intent = Intent(this, HPasteService::class.java) startService(intent) initView() } override fun onResume() { super.onResume() showContent() } override fun onClick(v: View) { if (v.id == R.id.title_iv_right) { HPrefs.clearContent() home_tv.text = "" home_tv_time.text = "" } } private fun initView() { title_tv.text = "HPaste" title_iv_right.setOnClickListener(this) // home_tv.setOnCreateContextMenuListener { menu, v, menuInfo -> // System.out.println("OnCreateContextMenu hugh") // } // home_tv.setOnEditorActionListener { v, actionId, event -> // System.out.println("onAction action:${actionId}") // false // } // home_tv.setOnKeyListener { v, keyCode, event -> // System.out.println("onKey code:${keyCode}") // false // } // home_tv.setOnTouchListener{ v, event -> // System.out.println("onTouch action:${event.action}") // false // } // home_tv.setOnFocusChangeListener { v, hasFocus -> // System.out.println("onFocusChange code:${hasFocus}") // } } private fun showContent() { home_tv.text = HPrefs.getContent() home_tv_time.text = HPrefs.getTime() } }
gpl-3.0
e20609bb568ec4d2181324e1d0dac3e0
28.029851
71
0.600823
4.024845
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/main/kotlin/com/aemtools/completion/htl/provider/HtlElVariableNameCompletionProvider.kt
1
2576
package com.aemtools.completion.htl.provider import com.aemtools.codeinsight.htl.model.DeclarationAttributeType import com.aemtools.codeinsight.htl.model.HtlVariableDeclaration import com.aemtools.common.util.withPriority import com.aemtools.completion.htl.CompletionPriority import com.aemtools.completion.htl.common.FileVariablesResolver import com.aemtools.completion.htl.common.PredefinedVariables import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionProvider import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.lookup.LookupElement import com.intellij.psi.PsiElement import com.intellij.util.ProcessingContext /** * @author Dmytro Troynikov */ object HtlElVariableNameCompletionProvider : CompletionProvider<CompletionParameters>() { override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { val currentPosition = parameters.position val contextObjects = PredefinedVariables.contextObjectsCompletion() .map { it.withPriority(CompletionPriority.CONTEXT_OBJECT) } val fileVariables = FileVariablesResolver.declarationsForPosition(parameters.position, parameters) .filter { it.attributeType != DeclarationAttributeType.DATA_SLY_TEMPLATE } .let { variables -> convertToLookupElements(currentPosition, variables) } result.addAllElements(fileVariables + contextObjects) result.stopHere() } private fun convertToLookupElements( currentPosition: PsiElement, variables: List<HtlVariableDeclaration>): List<LookupElement> { val result = ArrayList<LookupElement>() val outsiders = variables.filter { it.xmlAttribute.textOffset > currentPosition.textOffset } // variables declared after current position should go into the end of the list outsiders.mapTo(result) { it.toLookupElement().withPriority(CompletionPriority.VARIABLE_OUTSIDER) } val varsToPrioritize = variables - outsiders val weightedVars = varsToPrioritize.map { currentPosition.textOffset - it.xmlAttribute.textOffset to it }.sortedBy { it.first } weightedVars.forEachIndexed { index, pair -> val variableDeclaration = pair.second val priority = weightedVars.size - 1 - index result.add(variableDeclaration .toLookupElement() .withPriority(CompletionPriority.VARIABLE_BASE + priority)) } return result } }
gpl-3.0
5f7541a6481bff6ff3a3393237e2d3bb
37.447761
102
0.763199
5.10099
false
false
false
false
androidx/androidx
hilt/hilt-navigation-compose/src/main/java/androidx/hilt/navigation/compose/HiltViewModel.kt
3
2512
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.hilt.navigation.compose import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.hilt.navigation.HiltViewModelFactory import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavBackStackEntry /** * Returns an existing * [HiltViewModel](https://dagger.dev/api/latest/dagger/hilt/android/lifecycle/HiltViewModel) * -annotated [ViewModel] or creates a new one scoped to the current navigation graph present on * the {@link NavController} back stack. * * If no navigation graph is currently present then the current scope will be used, usually, a * fragment or an activity. * * @sample androidx.hilt.navigation.compose.samples.NavComposable * @sample androidx.hilt.navigation.compose.samples.NestedNavComposable */ @Composable inline fun <reified VM : ViewModel> hiltViewModel( viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) { "No ViewModelStoreOwner was provided via LocalViewModelStoreOwner" }, key: String? = null ): VM { val factory = createHiltViewModelFactory(viewModelStoreOwner) return viewModel(viewModelStoreOwner, key, factory = factory) } @Composable @PublishedApi internal fun createHiltViewModelFactory( viewModelStoreOwner: ViewModelStoreOwner ): ViewModelProvider.Factory? = if (viewModelStoreOwner is NavBackStackEntry) { HiltViewModelFactory( context = LocalContext.current, navBackStackEntry = viewModelStoreOwner ) } else { // Use the default factory provided by the ViewModelStoreOwner // and assume it is an @AndroidEntryPoint annotated fragment or activity null }
apache-2.0
74e353e8f3b7c223af3cf343af0d4297
37.661538
96
0.783041
4.766603
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionWithDemorgansLawIntention.kt
2
9263
// 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.intentions import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.codeinsight.utils.NegatedBinaryExpressionSimplificationUtils import org.jetbrains.kotlin.idea.inspections.ReplaceNegatedIsEmptyWithIsNotEmptyInspection.Companion.invertSelectorFunction import org.jetbrains.kotlin.idea.inspections.collections.isCalling import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.psi2ir.deparenthesize import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.isBoolean import org.jetbrains.kotlin.utils.addToStdlib.safeAs sealed class ConvertFunctionWithDemorgansLawIntention( intentionName: () -> String, conversions: List<Conversion>, ) : SelfTargetingRangeIntention<KtCallExpression>( KtCallExpression::class.java, intentionName ) { @SafeFieldForPreview private val conversions = conversions.associateBy { it.fromFunctionName } override fun applicabilityRange(element: KtCallExpression): TextRange? { val callee = element.calleeExpression ?: return null val (fromFunctionName, toFunctionName, _, _) = conversions[callee.text] ?: return null val fqNames = functions[fromFunctionName] ?: return null val lambda = element.singleLambdaArgumentExpression() ?: return null val lambdaBody = lambda.bodyExpression ?: return null val lastStatement = lambdaBody.statements.lastOrNull() ?: return null if (lambdaBody.anyDescendantOfType<KtReturnExpression> { it != lastStatement }) return null val context = element.analyze(BodyResolveMode.PARTIAL) if (element.getResolvedCall(context)?.resultingDescriptor?.fqNameOrNull() !in fqNames) return null val predicate = when (lastStatement) { is KtReturnExpression -> { val targetFunctionDescriptor = lastStatement.getTargetFunctionDescriptor(context) val lambdaDescriptor = context[BindingContext.FUNCTION, lambda.functionLiteral] if (targetFunctionDescriptor == lambdaDescriptor) lastStatement.returnedExpression else null } else -> lastStatement } ?: return null if (predicate.getType(context)?.isBoolean() != true) return null setTextGetter(KotlinBundle.lazyMessage("replace.0.with.1", fromFunctionName, toFunctionName)) return callee.textRange } override fun applyTo(element: KtCallExpression, editor: Editor?) { val (_, toFunctionName, negateCall, negatePredicate) = conversions[element.calleeExpression?.text] ?: return val lambda = element.singleLambdaArgumentExpression() ?: return val lastStatement = lambda.bodyExpression?.statements?.lastOrNull() ?: return val returnExpression = lastStatement.safeAs<KtReturnExpression>() val predicate = returnExpression?.returnedExpression ?: lastStatement if (negatePredicate) negate(predicate) val psiFactory = KtPsiFactory(element) if (returnExpression?.getLabelName() == element.calleeExpression?.text) { returnExpression?.labelQualifier?.replace(psiFactory.createLabelQualifier(toFunctionName)) } val callOrQualified = element.getQualifiedExpressionForSelectorOrThis() val parentNegatedExpression = callOrQualified.parentNegatedExpression() psiFactory.buildExpression { val addNegation = negateCall && parentNegatedExpression == null if (addNegation && callOrQualified !is KtSafeQualifiedExpression) { appendFixedText("!") } appendCallOrQualifiedExpression(element, toFunctionName) if (addNegation && callOrQualified is KtSafeQualifiedExpression) { appendFixedText("?.not()") } }.let { (parentNegatedExpression ?: callOrQualified).replaced(it) } } private fun negate(predicate: KtExpression) { val exclPrefixExpression = predicate.asExclPrefixExpression() if (exclPrefixExpression != null) { val replaced = exclPrefixExpression.baseExpression?.let { predicate.replaced(it) } replaced.removeUnnecessaryParentheses() return } val replaced = predicate.replaced(KtPsiFactory(predicate).createExpressionByPattern("!($0)", predicate)) as KtPrefixExpression replaced.baseExpression.removeUnnecessaryParentheses() when (val baseExpression = replaced.baseExpression?.deparenthesize()) { is KtBinaryExpression -> { val operationToken = baseExpression.operationToken if (operationToken == KtTokens.ANDAND || operationToken == KtTokens.OROR) { ConvertBinaryExpressionWithDemorgansLawIntention.convertIfPossible(baseExpression) } else { NegatedBinaryExpressionSimplificationUtils.simplifyNegatedBinaryExpressionIfNeeded(replaced) } } is KtQualifiedExpression -> { baseExpression.invertSelectorFunction()?.let { replaced.replace(it) } } } } private fun KtExpression.parentNegatedExpression(): KtExpression? { val parent = parents.dropWhile { it is KtParenthesizedExpression }.firstOrNull() ?: return null return parent.asExclPrefixExpression() ?: parent.asQualifiedExpressionWithNotCall() } private fun PsiElement.asExclPrefixExpression(): KtPrefixExpression? { return safeAs<KtPrefixExpression>()?.takeIf { it.operationToken == KtTokens.EXCL && it.baseExpression != null } } private fun PsiElement.asQualifiedExpressionWithNotCall(): KtQualifiedExpression? { return safeAs<KtQualifiedExpression>()?.takeIf { it.callExpression?.isCalling(FqName("kotlin.Boolean.not")) == true } } private fun KtExpression?.removeUnnecessaryParentheses() { if (this !is KtParenthesizedExpression) return val innerExpression = this.expression ?: return if (KtPsiUtil.areParenthesesUseless(this)) { this.replace(innerExpression) } } private fun KtPsiFactory.createLabelQualifier(labelName: String): KtContainerNode { return (createExpression("return@$labelName 1") as KtReturnExpression).labelQualifier!! } companion object { private val collectionFunctions = listOf("all", "any", "none", "filter", "filterNot", "filterTo", "filterNotTo").associateWith { listOf(FqName("kotlin.collections.$it"), FqName("kotlin.sequences.$it")) } private val standardFunctions = listOf("takeIf", "takeUnless").associateWith { listOf(FqName("kotlin.$it")) } private val functions = collectionFunctions + standardFunctions } } private data class Conversion( val fromFunctionName: String, val toFunctionName: String, val negateCall: Boolean, val negatePredicate: Boolean ) class ConvertCallToOppositeIntention : ConvertFunctionWithDemorgansLawIntention( KotlinBundle.lazyMessage("replace.function.call.with.the.opposite"), listOf( Conversion("all", "none", false, true), Conversion("none", "all", false, true), Conversion("filter", "filterNot", false, true), Conversion("filterNot", "filter", false, true), Conversion("filterTo", "filterNotTo", false, true), Conversion("filterNotTo", "filterTo", false, true), Conversion("takeIf", "takeUnless", false, true), Conversion("takeUnless", "takeIf", false, true) ) ) class ConvertAnyToAllAndViceVersaIntention : ConvertFunctionWithDemorgansLawIntention( KotlinBundle.lazyMessage("replace.0.with.1.and.vice.versa", "any", "all"), listOf( Conversion("any", "all", true, true), Conversion("all", "any", true, true) ) ) class ConvertAnyToNoneAndViceVersaIntention : ConvertFunctionWithDemorgansLawIntention( KotlinBundle.lazyMessage("replace.0.with.1.and.vice.versa", "any", "none"), listOf( Conversion("any", "none", true, false), Conversion("none", "any", true, false) ) )
apache-2.0
e3b7f3d0d964c61c8b0b7da379365bed
47.497382
136
0.720501
5.338905
false
false
false
false
GunoH/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/modules/IdeJavaModuleResolver.kt
3
5468
// 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.modules import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiJavaModule import com.intellij.psi.impl.light.LightJavaModule import org.jetbrains.kotlin.idea.base.facet.implementedModules import org.jetbrains.kotlin.idea.base.facet.implementingModules import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.load.java.structure.JavaAnnotation import org.jetbrains.kotlin.load.java.structure.impl.JavaAnnotationImpl import org.jetbrains.kotlin.load.java.structure.impl.convert import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.resolve.jvm.modules.JavaModuleResolver import java.util.concurrent.ConcurrentHashMap class IdeJavaModuleResolver(private val project: Project) : JavaModuleResolver { private val virtualFileFinder by lazy { VirtualFileFinder.getInstance(project) } private val modulesAnnotationCache = ConcurrentHashMap<ClassId, List<JavaAnnotation>>() override fun getAnnotationsForModuleOwnerOfClass(classId: ClassId): List<JavaAnnotation>? { if (modulesAnnotationCache.containsKey(classId)) { return modulesAnnotationCache[classId] } val virtualFile = virtualFileFinder.findVirtualFileWithHeader(classId) ?: return null val moduleAnnotations = findJavaModule(virtualFile)?.annotations?.convert(::JavaAnnotationImpl) if (moduleAnnotations != null && moduleAnnotations.size < MODULE_ANNOTATIONS_CACHE_SIZE) { modulesAnnotationCache[classId] = moduleAnnotations } return moduleAnnotations } private fun findJavaModule(file: VirtualFile): PsiJavaModule? = JavaModuleGraphUtil.findDescriptorByFile(file, project) override fun checkAccessibility( fileFromOurModule: VirtualFile?, referencedFile: VirtualFile, referencedPackage: FqName? ): JavaModuleResolver.AccessError? { val ourModule = fileFromOurModule?.let(::findJavaModule)?.also { if (it is LightJavaModule) return null } val theirModule = findJvmModule(referencedFile) if (ourModule?.name == theirModule?.name) return null if (theirModule == null) { return JavaModuleResolver.AccessError.ModuleDoesNotReadUnnamedModule } if (ourModule != null && !JavaModuleGraphUtil.reads(ourModule, theirModule)) { return JavaModuleResolver.AccessError.ModuleDoesNotReadModule(theirModule.name) } // In the IDE, we allow unnamed module to access unexported package of the named module. The reason is that the compiler // will use classpath, not the module path, when compilation of this module is launched from the IDE (because the module has // no module-info). All of its dependencies will also land on the classpath, and everything is visible in the classpath, // even non-exported packages of artifacts which would otherwise be loaded as named modules, if they were on the module path. // So, no error will be reported from the compiler. Moreover, a run configuration of something from this unnamed module will also // use classpath, not the module path, and in the same way everything will work at runtime as well. if (ourModule != null) { val fqName = referencedPackage?.asString() ?: return null if (theirModule.name != PsiJavaModule.JAVA_BASE && !exports(theirModule, fqName, ourModule)) { return JavaModuleResolver.AccessError.ModuleDoesNotExportPackage(theirModule.name) } } return null } private fun findJvmModule(referencedFile: VirtualFile): PsiJavaModule? { val referencedModuleForJvm = findJavaModule(referencedFile) if (referencedModuleForJvm != null) return referencedModuleForJvm val index = ProjectFileIndex.getInstance(project) if (index.isInLibrary(referencedFile)) return null val referencedModule = index.getModuleForFile(referencedFile) ?: return null val implementingModules = referencedModule.implementingModules val jvmModule = implementingModules.find { it.platform.isJvm() } ?: return null val inTestSourceContent = index.isInTestSourceContent(referencedFile) val jvmModuleDescriptor = JavaModuleGraphUtil.findDescriptorByModule(jvmModule, inTestSourceContent) if (jvmModuleDescriptor != null) return jvmModuleDescriptor val implementedJvmModule = jvmModule.implementedModules.find { it.platform.isJvm() } return JavaModuleGraphUtil.findDescriptorByModule(implementedJvmModule, inTestSourceContent) } // Returns whether or not [source] exports [packageName] to [target] private fun exports(source: PsiJavaModule, packageName: String, target: PsiJavaModule): Boolean = source is LightJavaModule || JavaModuleGraphUtil.exports(source, packageName, target) companion object { private const val MODULE_ANNOTATIONS_CACHE_SIZE = 10000 } }
apache-2.0
17c0b69dfeeb31c29b358eda2afcb035
51.07619
158
0.754206
4.957389
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/data/source/online/italian/MangaedenIT.kt
1
2948
/* * This file is part of TachiyomiEX. * * TachiyomiEX 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. * * TachiyomiEX 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 TachiyomiEX. If not, see <http://www.gnu.org/licenses/>. */ package eu.kanade.tachiyomi.data.source.online.italian import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.source.IT import eu.kanade.tachiyomi.data.source.Language import eu.kanade.tachiyomi.data.source.Sources import eu.kanade.tachiyomi.data.source.online.multi.Mangaeden import org.jsoup.nodes.* import java.text.SimpleDateFormat import java.util.* class MangaedenIT(override val source: Sources) : Mangaeden(){ override val lang: Language = IT override val langcode = lang.code.toLowerCase() override fun popularMangaNextPageSelector() = "div.pagination.pagination_bottom > a:has(span:contains(Avanti))" override fun searchMangaNextPageSelector() = "div.pagination.pagination_bottom > a:has(span:contains(Avanti))" override fun mangaDetailsParse(document: Document, manga: Manga) { val ielement = document.select("div#mangaPage") val info = getInfoList(ielement.select("div#rightContent").first().childNode(3).childNodes()) manga.thumbnail_url = "http:" + ielement.select("div#rightContent div.mangaImage2 > img").attr("src") manga.author = info[info.indexOf("Autore") + 1] manga.artist = info[info.indexOf("Artista") + 1] val s = StringBuilder() for (i in info.indexOf("Genere") + 1 .. info.indexOf("Tipo") - 1) { s.append(info[i]) } manga.genre = s.toString() manga.status = info[info.indexOf("Stato") + 1].let { parseStatus(it) } manga.description = ielement.select("h2#mangaDescription").text() } override fun parseStatus(status: String) = when { status.contains("En curso") -> Manga.ONGOING status.contains("Completado") -> Manga.COMPLETED else -> Manga.UNKNOWN } override fun chapterFromElement(element: Element, chapter: Chapter) { val urlElement = element.select("td > a.chapterLink") chapter.setUrlWithoutDomain(urlElement.attr("href")) chapter.name = urlElement.select("b").text() chapter.date_upload = element.select("td.chapterDate").text()?.let { SimpleDateFormat("dd MMM yyyy", Locale(langcode)).parse(it).time } ?: 0 } }
gpl-3.0
8645d70fe47e60422d79d8755e01b0a2
40.521127
115
0.701493
4.021828
false
false
false
false
GunoH/intellij-community
plugins/kotlin/completion/impl-k1/src/org/jetbrains/kotlin/idea/completion/BasicLookupElementFactory.kt
4
16391
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.completion import com.intellij.codeInsight.lookup.* import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinDescriptorIconProvider import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.completion.handlers.BaseDeclarationInsertHandler import org.jetbrains.kotlin.idea.completion.handlers.KotlinClassifierInsertHandler import org.jetbrains.kotlin.idea.completion.handlers.KotlinFunctionCompositeDeclarativeInsertHandler import org.jetbrains.kotlin.idea.completion.handlers.KotlinFunctionInsertHandler import org.jetbrains.kotlin.idea.core.completion.DescriptorBasedDeclarationLookupObject import org.jetbrains.kotlin.idea.core.completion.PackageLookupObject import org.jetbrains.kotlin.idea.core.unwrapIfFakeOverride import org.jetbrains.kotlin.idea.highlighter.dsl.DslKotlinHighlightingVisitorExtension import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.synthetic.SamAdapterExtensionFunctionDescriptor import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import java.awt.Font import javax.swing.Icon class BasicLookupElementFactory( private val project: Project, val insertHandlerProvider: InsertHandlerProvider ) { companion object { // we skip parameter names in functional types in most of the cases for shortness val SHORT_NAMES_RENDERER = DescriptorRenderer.SHORT_NAMES_IN_TYPES.withOptions { enhancedTypes = true parameterNamesInFunctionalTypes = false } private fun getIcon(lookupObject: DescriptorBasedDeclarationLookupObject, descriptor: DeclarationDescriptor, flags: Int): Icon? { // KotlinDescriptorIconProvider does not use declaration if it is KtElement, // so, do not try to look up psiElement for known Kotlin descriptors as it could be a heavy deserialization (e.g. from kotlin libs) val declaration = when (descriptor) { is DeserializedDescriptor, is ReceiverParameterDescriptor -> null else -> { lookupObject.psiElement } } return KotlinDescriptorIconProvider.getIcon(descriptor, declaration, flags) } } fun createLookupElement( descriptor: DeclarationDescriptor, qualifyNestedClasses: Boolean = false, includeClassTypeArguments: Boolean = true, parametersAndTypeGrayed: Boolean = false ): LookupElement { return createLookupElementUnwrappedDescriptor( descriptor.unwrapIfFakeOverride(), qualifyNestedClasses, includeClassTypeArguments, parametersAndTypeGrayed ) } fun createLookupElementForJavaClass( psiClass: PsiClass, qualifyNestedClasses: Boolean = false, includeClassTypeArguments: Boolean = true ): LookupElement { val lookupObject = PsiClassLookupObject(psiClass) var element = LookupElementBuilder.create(lookupObject, psiClass.name!!).withInsertHandler(KotlinClassifierInsertHandler) val typeParams = psiClass.typeParameters if (includeClassTypeArguments && typeParams.isNotEmpty()) { element = element.appendTailText(typeParams.map { it.name }.joinToString(", ", "<", ">"), true) } val qualifiedName = psiClass.qualifiedName!! var containerName = qualifiedName.substringBeforeLast('.', FqName.ROOT.toString()) if (qualifyNestedClasses) { val nestLevel = psiClass.parents.takeWhile { it is PsiClass }.count() if (nestLevel > 0) { var itemText = psiClass.name for (i in 1..nestLevel) { val outerClassName = containerName.substringAfterLast('.') element = element.withLookupString(outerClassName) itemText = "$outerClassName.$itemText" containerName = containerName.substringBeforeLast('.', FqName.ROOT.toString()) } element = element.withPresentableText(itemText!!) } } element = element.appendTailText(" ($containerName)", true) if (lookupObject.isDeprecated) { element = element.withStrikeoutness(true) } return element.withIconFromLookupObject() } fun createLookupElementForPackage(name: FqName): LookupElement { var element = LookupElementBuilder.create(PackageLookupObject(name), name.shortName().asString()) element = element.withInsertHandler(BaseDeclarationInsertHandler()) if (!name.parent().isRoot) { element = element.appendTailText(" (${name.asString()})", true) } return element.withIconFromLookupObject() } private fun createLookupElementUnwrappedDescriptor( descriptor: DeclarationDescriptor, qualifyNestedClasses: Boolean, includeClassTypeArguments: Boolean, parametersAndTypeGrayed: Boolean ): LookupElement { if (descriptor is JavaClassDescriptor) { val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) if (declaration is PsiClass && declaration !is KtLightClass) { // for java classes we create special lookup elements // because they must be equal to ones created in TypesCompletion // otherwise we may have duplicates return createLookupElementForJavaClass(declaration, qualifyNestedClasses, includeClassTypeArguments) } } if (descriptor is PackageViewDescriptor) { return createLookupElementForPackage(descriptor.fqName) } if (descriptor is PackageFragmentDescriptor) { return createLookupElementForPackage(descriptor.fqName) } val lookupObject: DescriptorBasedDeclarationLookupObject val name: String = when (descriptor) { is ConstructorDescriptor -> { // for constructor use name and icon of containing class val classifierDescriptor = descriptor.containingDeclaration lookupObject = object : DeclarationLookupObjectImpl(descriptor) { override val psiElement by lazy { DescriptorToSourceUtilsIde.getAnyDeclaration(project, classifierDescriptor) } override fun getIcon(flags: Int): Icon? = getIcon(this, classifierDescriptor, flags) } classifierDescriptor.name.asString() } is SyntheticJavaPropertyDescriptor -> { lookupObject = object : DeclarationLookupObjectImpl(descriptor) { override val psiElement by lazy { DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor.getMethod) } override fun getIcon(flags: Int) = KotlinDescriptorIconProvider.getIcon(descriptor, null, flags) } descriptor.name.asString() } else -> { lookupObject = object : DeclarationLookupObjectImpl(descriptor) { override val psiElement by lazy { DescriptorToSourceUtils.getSourceFromDescriptor(descriptor) ?: DescriptorToSourceUtilsIde.getAnyDeclaration( project, descriptor ) } override fun getIcon(flags: Int): Icon? = getIcon(this, descriptor, flags) } descriptor.name.asString() } } var element = LookupElementBuilder.create(lookupObject, name) val insertHandler = insertHandlerProvider.insertHandler(descriptor) element = element.withInsertHandler(insertHandler) when (descriptor) { is FunctionDescriptor -> { val returnType = descriptor.returnType element = element.withTypeText( if (returnType != null) SHORT_NAMES_RENDERER.renderType(returnType) else "", parametersAndTypeGrayed ) val insertsLambda = when (insertHandler) { is KotlinFunctionInsertHandler.Normal -> insertHandler.lambdaInfo != null is KotlinFunctionCompositeDeclarativeInsertHandler -> insertHandler.isLambda else -> false } if (insertsLambda) { element = element.appendTailText(" {...} ", parametersAndTypeGrayed) } element = element.appendTailText( SHORT_NAMES_RENDERER.renderFunctionParameters(descriptor), parametersAndTypeGrayed || insertsLambda ) } is VariableDescriptor -> { element = element.withTypeText(SHORT_NAMES_RENDERER.renderType(descriptor.type), parametersAndTypeGrayed) } is ClassifierDescriptorWithTypeParameters -> { val typeParams = descriptor.declaredTypeParameters if (includeClassTypeArguments && typeParams.isNotEmpty()) { element = element.appendTailText(typeParams.joinToString(", ", "<", ">") { it.name.asString() }, true) } var container = descriptor.containingDeclaration if (descriptor.isArtificialImportAliasedDescriptor) { container = descriptor.original // we show original descriptor instead of container for import aliased descriptors } else if (qualifyNestedClasses) { element = element.withPresentableText(SHORT_NAMES_RENDERER.renderClassifierName(descriptor)) while (container is ClassDescriptor) { val containerName = container.name if (!containerName.isSpecial) { element = element.withLookupString(containerName.asString()) } container = container.containingDeclaration } } if (container is PackageFragmentDescriptor || container is ClassifierDescriptor) { element = element.appendTailText(" (" + DescriptorUtils.getFqName(container) + ")", true) } if (descriptor is TypeAliasDescriptor) { // here we render with DescriptorRenderer.SHORT_NAMES_IN_TYPES to include parameter names in functional types element = element.withTypeText(DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(descriptor.underlyingType), false) } } else -> { element = element.withTypeText(SHORT_NAMES_RENDERER.render(descriptor), parametersAndTypeGrayed) } } var isMarkedAsDsl = false if (descriptor is CallableDescriptor) { appendContainerAndReceiverInformation(descriptor) { element = element.appendTailText(it, true) } val dslTextAttributes = DslKotlinHighlightingVisitorExtension.dslCustomTextStyle(descriptor)?.let { EditorColorsManager.getInstance().globalScheme.getAttributes(it) } if (dslTextAttributes != null) { isMarkedAsDsl = true element = element.withBoldness(dslTextAttributes.fontType == Font.BOLD) dslTextAttributes.foregroundColor?.let { element = element.withItemTextForeground(it) } } } if (descriptor is PropertyDescriptor) { val getterName = JvmAbi.getterName(name) if (getterName != name) { element = element.withLookupString(getterName) } if (descriptor.isVar) { element = element.withLookupString(JvmAbi.setterName(name)) } } if (lookupObject.isDeprecated) { element = element.withStrikeoutness(true) } if ((insertHandler as? KotlinFunctionInsertHandler.Normal)?.lambdaInfo != null) { element.putUserData(KotlinCompletionCharFilter.ACCEPT_OPENING_BRACE, Unit) } val result = element.withIconFromLookupObject() result.isDslMember = isMarkedAsDsl return result } fun appendContainerAndReceiverInformation(descriptor: CallableDescriptor, appendTailText: (String) -> Unit) { val information = CompletionInformationProvider.EP_NAME.extensions.firstNotNullOfOrNull { it.getContainerAndReceiverInformation(descriptor) } if (information != null) { appendTailText(information) return } val extensionReceiver = descriptor.original.extensionReceiverParameter if (extensionReceiver != null) { when (descriptor) { is SamAdapterExtensionFunctionDescriptor -> { // no need to show them as extensions return } is SyntheticJavaPropertyDescriptor -> { var from = descriptor.getMethod.name.asString() + "()" descriptor.setMethod?.let { from += "/" + it.name.asString() + "()" } appendTailText(KotlinIdeaCompletionBundle.message("presentation.tail.from.0", from)) return } else -> { val receiverPresentation = SHORT_NAMES_RENDERER.renderType(extensionReceiver.type) appendTailText(KotlinIdeaCompletionBundle.message("presentation.tail.for.0", receiverPresentation)) } } } val containerPresentation = containerPresentation(descriptor) if (containerPresentation != null) { appendTailText(" ") appendTailText(containerPresentation) } } private fun containerPresentation(descriptor: DeclarationDescriptor): String? { when { descriptor.isArtificialImportAliasedDescriptor -> { return "(${DescriptorUtils.getFqName(descriptor.original)})" } descriptor.isExtension -> { val containerPresentation = when (val container = descriptor.containingDeclaration) { is ClassDescriptor -> DescriptorUtils.getFqNameFromTopLevelClass(container).toString() is PackageFragmentDescriptor -> container.fqName.toString() else -> return null } return KotlinIdeaCompletionBundle.message("presentation.tail.in.0", containerPresentation) } else -> { val container = descriptor.containingDeclaration as? PackageFragmentDescriptor // we show container only for global functions and properties ?: return null //TODO: it would be probably better to show it also for static declarations which are not from the current class (imported) return "(${container.fqName})" } } } // add icon in renderElement only to pass presentation.isReal() private fun LookupElement.withIconFromLookupObject(): LookupElement = object : LookupElementDecorator<LookupElement>(this) { override fun renderElement(presentation: LookupElementPresentation) { super.renderElement(presentation) presentation.icon = DefaultLookupItemRenderer.getRawIcon(this@withIconFromLookupObject) } } }
apache-2.0
1bf0c0ab6456da734ede3ebd74836990
44.913165
143
0.643768
6.021675
false
false
false
false
Fotoapparat/Fotoapparat
fotoapparat/src/test/java/io/fotoapparat/selector/AspectRatioSelectorsTest.kt
1
6103
package io.fotoapparat.selector import io.fotoapparat.parameter.Resolution import org.junit.Before import org.junit.Test import kotlin.test.assertEquals class AspectRatioSelectorsTest { var receivedResolutions: Iterable<Resolution>? = null @Before fun setUp() { receivedResolutions = null } @Test fun `Filter standard ratios`() { // Given val sizeSelector: Iterable<Resolution>.() -> Resolution = { receivedResolutions = this Resolution(4, 3) } // When val result = standardRatio(selector = sizeSelector)(listOf( Resolution(4, 3), Resolution(8, 6), Resolution(10, 10) )) // Then assertEquals( expected = Resolution(4, 3), actual = result ) assertEquals( expected = listOf( Resolution(4, 3), Resolution(8, 6) ), actual = receivedResolutions ) } @Test fun `Filter standard ratios with tolerance`() { // Given val sizeSelector: Iterable<Resolution>.() -> Resolution = { receivedResolutions = this Resolution(400, 300) } // When val result = standardRatio( selector = sizeSelector, tolerance = 0.1 )(listOf( Resolution(400, 300), Resolution(410, 300), Resolution(800, 600), Resolution(790, 600), Resolution(100, 100), Resolution(160, 90) )) // Then assertEquals( expected = Resolution(400, 300), actual = result ) assertEquals( expected = listOf( Resolution(400, 300), Resolution(410, 300), Resolution(800, 600), Resolution(790, 600) ), actual = receivedResolutions ) } @Test fun `Filter wide ratios`() { // Given val sizeSelector: Iterable<Resolution>.() -> Resolution = { receivedResolutions = this Resolution(16, 9) } // When val result = wideRatio(selector = sizeSelector)(listOf( Resolution(16, 9), Resolution(32, 18), Resolution(10, 10) )) // Then assertEquals( expected = Resolution(16, 9), actual = result ) assertEquals( expected = listOf( Resolution(16, 9), Resolution(32, 18) ), actual = receivedResolutions ) } @Test fun `Filter wide ratios with tolerance`() { // Given val sizeSelector: Iterable<Resolution>.() -> Resolution = { receivedResolutions = this Resolution(16, 9) } // When val result = wideRatio( selector = sizeSelector, tolerance = 0.1 )(listOf( Resolution(16, 9), Resolution(16, 10), Resolution(32, 18), Resolution(32, 20), Resolution(10, 10) )) // Then assertEquals( expected = Resolution(16, 9), actual = result ) assertEquals( expected = listOf( Resolution(16, 9), Resolution(16, 10), Resolution(32, 18), Resolution(32, 20) ), actual = receivedResolutions ) } @Test fun `Filter custom aspect ratio with tolerance`() { // Given val sizeSelector: Iterable<Resolution>.() -> Resolution = { receivedResolutions = this Resolution(110, 100) } // When val result = aspectRatio( aspectRatio = 1.0f, selector = sizeSelector, tolerance = 0.1 )(listOf( Resolution(16, 9), Resolution(110, 100), Resolution(105, 100), Resolution(95, 100), Resolution(90, 100), Resolution(4, 3), Resolution(20, 10) )) // Then assertEquals( expected = Resolution(110, 100), actual = result ) assertEquals( expected = listOf( Resolution(110, 100), Resolution(105, 100), Resolution(95, 100), Resolution(90, 100) ), actual = receivedResolutions ) } @Test(expected = IllegalArgumentException::class) fun `Custom Ratio with tolerance less than 0 should throw exception`() { // Given val sizeSelector: Iterable<Resolution>.() -> Resolution = { Resolution(16, 9) } // When aspectRatio( aspectRatio = 1.0f, selector = sizeSelector, tolerance = -0.1 )(listOf( Resolution(16, 9), Resolution(16, 10) )) // Then exception is thrown } @Test(expected = IllegalArgumentException::class) fun `Custom ratio with tolerance above 1 should throw exception`() { // Given val sizeSelector: Iterable<Resolution>.() -> Resolution = { Resolution(16, 9) } // When aspectRatio( aspectRatio = 1.0f, selector = sizeSelector, tolerance = 1.1 )(listOf( Resolution(16, 9), Resolution(16, 10) )) // Then exception is thrown } }
apache-2.0
6a2b22d00d1e9103f42bc962094a15ae
25.419913
76
0.451417
5.483378
false
false
false
false
smmribeiro/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/editors/PackageVersionTableCellEditor.kt
2
2725
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.editors import com.intellij.ui.table.JBTable import com.intellij.util.ui.AbstractTableCellEditor import com.jetbrains.packagesearch.intellij.plugin.ui.components.ComboBoxTableCellEditorComponent import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.colors import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers.PopupMenuListItemCellRenderer import java.awt.Component import javax.swing.JTable internal class PackageVersionTableCellEditor : AbstractTableCellEditor() { private var lastEditor: ComboBoxTableCellEditorComponent<*>? = null private var onlyStable = false fun updateData(onlyStable: Boolean) { this.onlyStable = onlyStable } override fun getCellEditorValue(): Any? = lastEditor?.value override fun getTableCellEditorComponent(table: JTable, value: Any, isSelected: Boolean, row: Int, column: Int): Component { val viewModel = value as UiPackageModel<*> val versionViewModels = when (viewModel) { is UiPackageModel.Installed -> viewModel.sortedVersions.map { viewModel.copy(selectedVersion = it) } is UiPackageModel.SearchResult -> viewModel.sortedVersions.map { viewModel.copy(selectedVersion = it) } } val editor = createComboBoxEditor(table, versionViewModels, viewModel.selectedVersion.originalVersion) .apply { table.colors.applyTo(this, isSelected = true) setCell(row, column) } lastEditor = editor return editor } @Suppress("DuplicatedCode") private fun createComboBoxEditor( table: JTable, versionViewModels: List<UiPackageModel<*>>, selectedVersion: PackageVersion ): ComboBoxTableCellEditorComponent<*> { require(table is JBTable) { "The packages list table is expected to be a JBTable, but was a ${table::class.qualifiedName}" } val selectedViewModel = versionViewModels.find { it.selectedVersion == selectedVersion } val cellRenderer = PopupMenuListItemCellRenderer(selectedViewModel, table.colors) { it.selectedVersion.displayName } return ComboBoxTableCellEditorComponent(table, cellRenderer).apply { isShowBelowCell = false isForcePopupMatchCellWidth = false options = versionViewModels value = selectedViewModel } } }
apache-2.0
dcfc6aed2c0fba9521e86f5f6c7fd9a2
43.672131
139
0.738716
5.210325
false
false
false
false
ItsPriyesh/HexaTime
app/src/main/kotlin/com/priyesh/hexatime/core/Clock.kt
1
4938
/* * 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.core import android.content.Context import android.content.SharedPreferences import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Typeface import android.preference.PreferenceManager import com.priyesh.hexatime.* import java.util.Calendar import kotlin.properties.Delegates public class Clock(context: Context) : PreferenceDelegate { private val context = context private var enable24Hour = false private var enableNumberSign = true private var dividerStyle = 0 private var enableHexFormat = false private var positionX = 50 private var positionY = 50 private val HOUR = Calendar.HOUR private val HOUR_24 = Calendar.HOUR_OF_DAY private val MINUTE = Calendar.MINUTE private val SECOND = Calendar.SECOND private var calendar = Calendar.getInstance() private var paint = Paint() private var canvasDimensions: Pair<Int, Int> by Delegates.notNull() private fun hour() = if (enable24Hour) calendar.get(HOUR_24) else if (calendar.get(HOUR) == 0) 12 else calendar.get(HOUR) private fun minute() = calendar.get(MINUTE) private fun second() = calendar.get(SECOND) private fun numberSign() = if (enableNumberSign) "#" else "" private fun divider() = when (dividerStyle) { 0 -> "" 1 -> "." 2 -> ":" 3 -> " " 4 -> "|" 5 -> "/" else -> "" } init { paint.isAntiAlias = true paint.textAlign = Paint.Align.CENTER paint.color = Color.WHITE initializeFromPrefs(PreferenceManager.getDefaultSharedPreferences(context)) } override fun initializeFromPrefs(prefs: SharedPreferences) { val keys = arrayOf(KEY_ENABLE_24_HOUR, KEY_ENABLE_NUMBER_SIGN, KEY_CLOCK_DIVIDER, KEY_ENABLE_HEX_FORMAT, KEY_CLOCK_POSITION_X, KEY_CLOCK_POSITION_Y, KEY_CLOCK_SIZE, KEY_CLOCK_FONT) for (key in keys) onPreferenceChange(prefs, key) } override fun onPreferenceChange(prefs: SharedPreferences, key: String) { when (key) { KEY_ENABLE_24_HOUR -> enable24Hour = prefs.getBoolean(key, false) KEY_ENABLE_NUMBER_SIGN -> enableNumberSign = prefs.getBoolean(key, true) KEY_CLOCK_DIVIDER -> dividerStyle = prefs.getString(key, "0").toInt() KEY_ENABLE_HEX_FORMAT -> enableHexFormat = prefs.getBoolean(key, false) KEY_CLOCK_SIZE -> paint.textSize = context.getPixels(prefs.getString(key, "50").toInt()) KEY_CLOCK_POSITION_X -> positionX = prefs.getInt(key, 50) KEY_CLOCK_POSITION_Y -> positionY = prefs.getInt(key, 50) KEY_CLOCK_FONT -> paint.setTypeface(createFont(prefs.getString(key, "Lato"))) } } private fun getSecondOfDay() = calendar.get(Calendar.HOUR_OF_DAY) * 3600 + calendar.get(Calendar.MINUTE) * 60 + calendar.get(Calendar.SECOND) public fun getColor(): Int = Color.parseColor(getHexString()) public fun getHue(): Float = getSecondOfDay() / 240f public fun getHexString(): String = "#${formatTwoDigit(hour())}${formatTwoDigit(minute())}${formatTwoDigit(second())}" public fun getTime(): String { updateCalendar() fun formatter(i: Int) = if (enableHexFormat) convertToHex(i) else formatTwoDigit(i) return "${numberSign()}${formatter(hour())}${divider()}${formatter(minute())}${divider()}${formatter(second())}" } private fun convertToHex(num: Int): String = Integer.toHexString(formatTwoDigit(num).toInt()) private fun formatTwoDigit(num: Int): String = java.lang.String.format("%02d", num) private fun createFont(name: String) = Typeface.createFromAsset(context.assets, "$name.ttf") public fun updateCalendar() { calendar = Calendar.getInstance() } public fun getPaint(): Paint = paint public fun getX(): Float = (canvasDimensions.first * (positionX / 100.0)).toFloat() public fun getY(): Float = ((canvasDimensions.second - (paint.descent() + paint.ascent()) / 2) * ((100 - positionY) / 100.0)).toFloat() public fun updateDimensions(dimens: Pair<Int, Int>) { canvasDimensions = dimens } public fun getContext(): Context = context }
apache-2.0
b1b5972df059a331724a839d9528fa84
35.585185
120
0.666869
4.170608
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/misc/deeplink/DeepLinkViewModel.kt
1
4916
package ch.rmy.android.http_shortcuts.activities.misc.deeplink import android.app.Application import android.net.Uri import androidx.core.net.toUri import androidx.lifecycle.viewModelScope import ch.rmy.android.framework.utils.localization.Localizable import ch.rmy.android.framework.utils.localization.StringResLocalizable import ch.rmy.android.framework.viewmodel.BaseViewModel import ch.rmy.android.framework.viewmodel.WithDialog import ch.rmy.android.framework.viewmodel.viewstate.DialogState import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.activities.ExecuteActivity import ch.rmy.android.http_shortcuts.activities.main.MainActivity import ch.rmy.android.http_shortcuts.dagger.getApplicationComponent import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutNameOrId import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutRepository import ch.rmy.android.http_shortcuts.data.domains.variables.VariableKey import ch.rmy.android.http_shortcuts.extensions.createDialogState import ch.rmy.android.http_shortcuts.utils.HTMLUtil import com.afollestad.materialdialogs.callbacks.onCancel import kotlinx.coroutines.launch import javax.inject.Inject class DeepLinkViewModel(application: Application) : BaseViewModel<DeepLinkViewModel.InitData, DeepLinkViewState>(application), WithDialog { @Inject lateinit var shortcutRepository: ShortcutRepository init { getApplicationComponent().inject(this) } override fun initViewState() = DeepLinkViewState() override var dialogState: DialogState? get() = currentViewState?.dialogState set(value) { updateViewState { copy(dialogState = value) } } override fun onInitializationStarted(data: InitData) { finalizeInitialization(silent = true) } private fun showMessageDialog(message: Localizable) { dialogState = createDialogState { message(message) .positive(R.string.dialog_ok) { onMessageDialogCanceled() } .build() .onCancel { onMessageDialogCanceled() } } } private fun onMessageDialogCanceled() { finish(skipAnimation = true) } override fun onInitialized() { val deepLinkUrl = initData.url if (deepLinkUrl == null) { showMessageDialog( Localizable.create { context -> HTMLUtil.format(context.getString(R.string.instructions_deep_linking, EXAMPLE_URL)) } ) return } if (deepLinkUrl.isCancelExecutions()) { openActivity( MainActivity.IntentBuilder() .cancelPendingExecutions() ) finish(skipAnimation = true) return } val importUrl = deepLinkUrl.getImportUrl() if (importUrl != null) { openActivity( MainActivity.IntentBuilder() .importUrl(importUrl) ) finish(skipAnimation = true) return } val shortcutIdOrName = deepLinkUrl.getShortcutNameOrId() viewModelScope.launch { try { val shortcut = shortcutRepository.getShortcutByNameOrId(shortcutIdOrName) executeShortcut(shortcut.id, deepLinkUrl.getVariableValues()) } catch (e: NoSuchElementException) { showMessageDialog(StringResLocalizable(R.string.error_shortcut_not_found_for_deep_link, shortcutIdOrName)) } } } private fun executeShortcut(shortcutId: ShortcutId, variableValues: Map<VariableKey, String>) { openActivity( ExecuteActivity.IntentBuilder(shortcutId) .variableValues(variableValues) ) finish(skipAnimation = true) } private fun Uri.isCancelExecutions() = host == "cancel-executions" && path?.trimEnd('/').isNullOrEmpty() private fun Uri.getImportUrl(): Uri? = takeIf { host == "import" && path?.trimEnd('/').isNullOrEmpty() } ?.getQueryParameter("url") ?.toUri() private fun Uri.getShortcutNameOrId(): ShortcutNameOrId = host ?.takeUnless { it == "deep-link" } ?: lastPathSegment ?: "" private fun Uri.getVariableValues(): Map<VariableKey, String> = queryParameterNames .filterNot { it.isEmpty() } .associateWith { key -> getQueryParameter(key) ?: "" } data class InitData( val url: Uri?, ) companion object { private const val EXAMPLE_URL = "http-shortcuts://<b>&lt;Name/ID of Shortcut&gt;</b>" } }
mit
3b886a3f5edaaa1f116d602bc5ff8bad
33.377622
139
0.64463
4.925852
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/extensions/Extensions.kt
1
2977
package ch.rmy.android.framework.extensions import android.app.Activity import android.content.Context import android.graphics.drawable.Drawable import androidx.annotation.CheckResult import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.DimenRes import androidx.annotation.DrawableRes import androidx.appcompat.content.res.AppCompatResources import androidx.core.content.ContextCompat import androidx.core.util.Predicate @ColorInt fun color(context: Context, @ColorRes colorRes: Int): Int = ContextCompat.getColor(context, colorRes) fun drawable(context: Context, @DrawableRes drawableRes: Int): Drawable? = AppCompatResources.getDrawable(context, drawableRes) fun Activity.dimen(@DimenRes dimenRes: Int) = dimen(this, dimenRes) fun dimen(context: Context, @DimenRes dimenRes: Int) = context.resources.getDimensionPixelSize(dimenRes) inline fun consume(f: () -> Unit): Boolean { f() return true } inline fun <T> T.applyIf(predicate: Boolean, block: T.() -> Unit): T = if (predicate) apply(block) else this inline fun <T, U> T.applyIfNotNull(item: U?, block: T.(U) -> Unit): T = if (item != null) apply { block(item) } else this inline fun <T> T.runIf(predicate: Boolean, block: T.() -> T): T = if (predicate) block(this) else this inline fun <T, U> T.runIfNotNull(item: U?, block: T.(U) -> T): T = if (item != null) block(this, item) else this inline fun <T, U> T.runFor(iterable: Iterable<U>, block: T.(U) -> T): T { val iterator = iterable.iterator() var item = this while (iterator.hasNext()) { item = block.invoke(item, iterator.next()) } return item } fun <T> Map<String, T>.getCaseInsensitive(key: String): T? = entries.firstOrNull { it.key.equals(key, ignoreCase = true) }?.value fun <T> MutableCollection<T>.safeRemoveIf(predicate: Predicate<T>) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { removeIf(predicate::test) } else { val iterator = iterator() while (iterator.hasNext()) { val item = iterator.next() if (predicate.test(item)) { iterator.remove() } } } } fun <T> T.takeUnlessEmpty(): T? where T : Collection<*> = takeUnless { it.isEmpty() } @CheckResult fun <T, ID : Any> List<T>.swapped(id1: ID, id2: ID, getId: T.() -> ID?): List<T> { val oldPosition = indexOfFirstOrNull { it.getId() == id1 } ?: return this val newPosition = indexOfFirstOrNull { it.getId() == id2 } ?: return this return toMutableList() .also { list -> list.add(newPosition, list.removeAt(oldPosition)) } } fun <T> MutableCollection<T>.addOrRemove(item: T, add: Boolean) { if (add) { add(item) } else { remove(item) } } inline fun <T> Collection<T>.indexOfFirstOrNull(predicate: (T) -> Boolean): Int? = indexOfFirst(predicate).takeUnless { it == -1 }
mit
2563d4068c503d0105a380aee901b73e
31.010753
82
0.664763
3.643819
false
false
false
false
sg26565/hott-transmitter-config
MdlViewer/src/main/kotlin/de/treichels/hott/mdlviewer/javafx/SelectFromMemory.kt
1
3194
/** * HoTT Transmitter Config Copyright (C) 2013 Oliver Treichel * * 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:></http:>//www.gnu.org/licenses/>. */ package de.treichels.hott.mdlviewer.javafx import de.treichels.hott.decoder.HoTTTransmitter import de.treichels.hott.model.enums.ModelType import de.treichels.hott.serial.ModelInfo import javafx.beans.binding.BooleanBinding import javafx.concurrent.Task import javafx.scene.control.ListCell import javafx.scene.control.ListView import javafx.scene.control.SelectionMode import javafx.util.Callback import tornadofx.* /** * @author Oliver Treichel &lt;[email protected]&gt; */ class SelectFromMemory : SelectFromTransmitter() { private var listView by singleAssign<ListView<ModelInfo>>() // dialog is ready when the user selects an item from the list override fun isReady(): BooleanBinding = listView.selectionModel.selectedItemProperty().isNotNull // load the selected item as Model override fun getResult(): Task<Model>? { val modelInfo = listView.selectionModel.selectedItem val serialPort = this.transmitter return if (modelInfo != null && serialPort != null) { runAsync { Model.loadModel(modelInfo, serialPort) } } else null } init { title = messages["select_from_memory_title"] // add to UI root.center { listView = listview { selectionModel.selectionMode = SelectionMode.SINGLE setOnMouseClicked { handleDoubleClick(it) } cellFactory = Callback { ModelInfoListCell() } } } } /** * Refresh a [ListView] with a list of all models from the transmitter memory using the [HoTTTransmitter] from parent. */ override fun refreshUITask(): Task<*> { // add temporary placeholder listView.items = observableListOf() // fill list in background return listView.runAsyncWithOverlay { transmitter?.allModelInfos?.filter { it.modelType != ModelType.Unknown } ?: listOf() }.success { list -> listView.items = list.asObservable() } } private inner class ModelInfoListCell : ListCell<ModelInfo>() { override fun updateItem(item: ModelInfo?, empty: Boolean) { super.updateItem(item, empty) if (!empty) { text = if (item == null) { messages["loading"] } else { String.format("%02d: %c%s.mdl", item.modelNumber + 1, item.modelType.char, item.modelName) } } } } }
lgpl-3.0
5fa8adab3dd02ba84bd7aaf7a6ee2a9b
35.712644
160
0.662805
4.717873
false
false
false
false
aosp-mirror/platform_frameworks_support
core/ktx/src/main/java/androidx/core/util/LongSparseArray.kt
1
3842
/* * 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 public API. package androidx.core.util import android.util.LongSparseArray import androidx.annotation.RequiresApi /** Returns the number of key/value pairs in the collection. */ @get:RequiresApi(16) inline val <T> LongSparseArray<T>.size get() = size() /** Returns true if the collection contains [key]. */ @RequiresApi(16) inline operator fun <T> LongSparseArray<T>.contains(key: Long) = indexOfKey(key) >= 0 /** Allows the use of the index operator for storing values in the collection. */ @RequiresApi(16) inline operator fun <T> LongSparseArray<T>.set(key: Long, value: T) = put(key, value) /** Creates a new collection by adding or replacing entries from [other]. */ @RequiresApi(16) operator fun <T> LongSparseArray<T>.plus(other: LongSparseArray<T>): LongSparseArray<T> { val new = LongSparseArray<T>(size() + other.size()) new.putAll(this) new.putAll(other) return new } /** Returns true if the collection contains [key]. */ @RequiresApi(16) inline fun <T> LongSparseArray<T>.containsKey(key: Long) = indexOfKey(key) >= 0 /** Returns true if the collection contains [value]. */ @RequiresApi(16) inline fun <T> LongSparseArray<T>.containsValue(value: T) = indexOfValue(value) != -1 /** Return the value corresponding to [key], or [defaultValue] when not present. */ @RequiresApi(16) inline fun <T> LongSparseArray<T>.getOrDefault(key: Long, defaultValue: T) = get(key) ?: defaultValue /** Return the value corresponding to [key], or from [defaultValue] when not present. */ @RequiresApi(16) inline fun <T> LongSparseArray<T>.getOrElse(key: Long, defaultValue: () -> T) = get(key) ?: defaultValue() /** Return true when the collection contains no elements. */ @RequiresApi(16) inline fun <T> LongSparseArray<T>.isEmpty() = size() == 0 /** Return true when the collection contains elements. */ @RequiresApi(16) inline fun <T> LongSparseArray<T>.isNotEmpty() = size() != 0 /** Removes the entry for [key] only if it is mapped to [value]. */ @RequiresApi(16) fun <T> LongSparseArray<T>.remove(key: Long, value: T): Boolean { val index = indexOfKey(key) if (index != -1 && value == valueAt(index)) { removeAt(index) return true } return false } /** Update this collection by adding or replacing entries from [other]. */ @RequiresApi(16) fun <T> LongSparseArray<T>.putAll(other: LongSparseArray<T>) = other.forEach(::put) /** Performs the given [action] for each key/value entry. */ @RequiresApi(16) inline fun <T> LongSparseArray<T>.forEach(action: (key: Long, value: T) -> Unit) { for (index in 0 until size()) { action(keyAt(index), valueAt(index)) } } /** Return an iterator over the collection's keys. */ @RequiresApi(16) fun <T> LongSparseArray<T>.keyIterator(): LongIterator = object : LongIterator() { var index = 0 override fun hasNext() = index < size() override fun nextLong() = keyAt(index++) } /** Return an iterator over the collection's values. */ @RequiresApi(16) fun <T> LongSparseArray<T>.valueIterator(): Iterator<T> = object : Iterator<T> { var index = 0 override fun hasNext() = index < size() override fun next() = valueAt(index++) }
apache-2.0
4a701b186c203b40486cd143fbfba1c3
34.574074
89
0.698855
3.788955
false
false
false
false
seventhroot/elysium
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/set/CharacterSetDescriptionCommand.kt
1
6691
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.characters.bukkit.command.character.set import com.rpkit.characters.bukkit.RPKCharactersBukkit import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.conversations.* import org.bukkit.entity.Player /** * Character set description command. * Sets character's description state. */ class CharacterSetDescriptionCommand(private val plugin: RPKCharactersBukkit): CommandExecutor { private val conversationFactory: ConversationFactory init { conversationFactory = ConversationFactory(plugin) .withModality(true) .withFirstPrompt(DescriptionPrompt()) .withEscapeSequence("cancel") .thatExcludesNonPlayersWithMessage(plugin.messages["not-from-console"]) .addConversationAbandonedListener { event -> if (!event.gracefulExit()) { val conversable = event.context.forWhom if (conversable is Player) { conversable.sendMessage(plugin.messages["operation-cancelled"]) } } } } override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (sender is Player) { if (sender.hasPermission("rpkit.characters.command.character.set.description")) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (minecraftProfile != null) { val character = characterProvider.getActiveCharacter(minecraftProfile) if (character != null) { if (args.isNotEmpty()) { val descriptionBuilder = StringBuilder() for (i in 0 until args.size - 1) { descriptionBuilder.append(args[i]).append(" ") } descriptionBuilder.append(args[args.size - 1]) character.description = descriptionBuilder.toString() characterProvider.updateCharacter(character) sender.sendMessage(plugin.messages["character-set-description-valid"]) character.showCharacterCard(minecraftProfile) } else { conversationFactory.buildConversation(sender).begin() } } else { sender.sendMessage(plugin.messages["no-character"]) } } else { sender.sendMessage(plugin.messages["no-minecraft-profile"]) } } else { sender.sendMessage(plugin.messages["no-permission-character-set-description"]) } } else { sender.sendMessage(plugin.messages["not-from-console"]) } return true } private inner class DescriptionPrompt: StringPrompt() { override fun getPromptText(context: ConversationContext): String { return plugin.messages["character-set-description-prompt"] } override fun acceptInput(context: ConversationContext, input: String?): Prompt { if (context.getSessionData("description") == null) { context.setSessionData("description", "") } if (input.equals("end", ignoreCase = true)) { val conversable = context.forWhom if (conversable is Player) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(conversable) if (minecraftProfile != null) { val character = characterProvider.getActiveCharacter(minecraftProfile) if (character != null) { character.description = context.getSessionData("description") as String characterProvider.updateCharacter(character) } } } return DescriptionSetPrompt() } else { val previousDescription = context.getSessionData("description") as String context.setSessionData("description", "$previousDescription $input") return DescriptionPrompt() } } } private inner class DescriptionSetPrompt: MessagePrompt() { override fun getNextPrompt(context: ConversationContext): Prompt? { val conversable = context.forWhom if (conversable is Player) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(context.forWhom as Player) if (minecraftProfile != null) { characterProvider.getActiveCharacter(minecraftProfile)?.showCharacterCard(minecraftProfile) } } return Prompt.END_OF_CONVERSATION } override fun getPromptText(context: ConversationContext): String { return plugin.messages["character-set-description-valid"] } } }
apache-2.0
a4a71373810162e030d8042c256b49af
46.119718
132
0.620236
5.916004
false
false
false
false
Adven27/Exam
exam-core/src/main/java/io/github/adven27/concordion/extensions/exam/core/utils/JsonPrettyPrinter.kt
1
4784
package io.github.adven27.concordion.extensions.exam.core.utils import io.github.adven27.concordion.extensions.exam.core.utils.JsonPrettyPrinter.State.ARRAY import io.github.adven27.concordion.extensions.exam.core.utils.JsonPrettyPrinter.State.OBJECT import io.github.adven27.concordion.extensions.exam.core.utils.JsonPrettyPrinter.State.UNKNOWN import java.util.Scanner import java.util.Stack private const val ESCAPE_CHARACTER = "\\" class JsonPrettyPrinter { fun prettyPrint(json: String?): String { return if (json == null) "" else Parser().parse(json) } private enum class State { UNKNOWN, OBJECT, ARRAY } private class Parser { private var indent = 0 private var newLine = false private val state = Stack<State>() private var token: String? = null @Suppress("ComplexMethod", "LoopWithTooManyJumpStatements") fun parse(json: String): String { state.push(UNKNOWN) Scanner(json).useDelimiter("").use { scanner -> return buildString { while (scanner.hasToken()) { if (scanner.nextTokenIs("{")) { consumeToken() if (!scanner.nextTokenIs("}")) { growIndent() append("{") state.push(OBJECT) } else { append("{}") consumeToken() } continue } if (scanner.nextTokenIs("}")) shrinkIndent() if (scanner.nextTokenIs("[")) state.push(ARRAY) if (scanner.nextTokenIs("]")) state.leave() if (scanner.nextTokenIs(",")) { append(",") if (state.eq(OBJECT)) { newLine = true } else if (state.eq(ARRAY)) { append(" ") } consumeToken() continue } if (scanner.nextTokenIs(":")) { append(": ") consumeToken() continue } if (newLine) { append("\n") indent(indent) newLine = false } if (scanner.nextTokenIs("\"")) { append("\"") append(scanner.eatUnit("\"")) consumeToken() continue } if (scanner.nextTokenIs("'")) { append("'") append(scanner.eatUnit("'")) consumeToken() continue } append(token) consumeToken() } } } } private fun Stack<State>.eq(testState: State) = peek() == testState private fun Stack<State>.leave() = if (isEmpty()) UNKNOWN else pop() private fun StringBuilder.indent(i: Int) = append(" ".repeat(i)) private fun Scanner.nextTokenIs(testToken: String) = hasToken() && testToken == token private fun Scanner.eatUnit(desiredToken: String): String { var prev = "" var sb = "" while (hasNext()) { val x = next() sb += x if (x == desiredToken && prev != ESCAPE_CHARACTER) { break } prev = x } return sb } private fun shrinkIndent() { indent-- if (state.leave() == OBJECT) { newLine = true } } private fun growIndent() { indent++ newLine = true } @Suppress("ReturnCount") private fun Scanner.hasToken(): Boolean { if (token != null) { return true } while (hasNext()) { token = next().trim() if (token!!.isEmpty()) { continue } return true } return false } private fun consumeToken() { token = null } } }
mit
55e6ec854d092720021c1c9b7d299a43
32.222222
94
0.40092
6.164948
false
false
false
false
jmiecz/YelpBusinessExample
dal/src/main/java/net/mieczkowski/dal/services/locationService/LocationService.kt
1
2819
package net.mieczkowski.dal.services.locationService import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageManager import android.location.Location import android.support.v4.content.ContextCompat import com.google.android.gms.location.* import io.reactivex.Observable import io.reactivex.Single import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.PublishSubject /** * Created by Josh Mieczkowski on 9/12/2018. */ class LocationService(context: Context) { class MissingFineLocationError : Throwable("Missing Coarse Location Permission") private val locationClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context) private var obsCount = 0 private val locationSubject: BehaviorSubject<Location> = BehaviorSubject.create() private var locationRequest = LocationRequest().apply { interval = 10000 fastestInterval = 0 priority = LocationRequest.PRIORITY_LOW_POWER } private val defaultLocation = Location("Default").apply { latitude = 39.7392 longitude = 104.9903 } private var locationCallBack: LocationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult?) { locationResult ?: return locationResult.locations.forEach { locationSubject.onNext(it) } } } init { locationSubject.onNext(defaultLocation) } fun configureLocationSettings(settings: LocationRequest.() -> Unit): LocationService { settings(locationRequest) return this } fun getLocation(): Single<Location> = getLocationObserver().take(1).toList().map { it[0] } @SuppressLint("MissingPermission") fun getLocationObserver(): Observable<Location> { return if (ContextCompat.checkSelfPermission(locationClient.applicationContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { Observable.error(MissingFineLocationError()) } else { locationSubject.subscribeOn(Schedulers.io()) .doOnSubscribe { if (obsCount == 0) locationClient.requestLocationUpdates(locationRequest, locationCallBack, null) obsCount++ } .doOnDispose { obsCount-- if (obsCount == 0) locationClient.removeLocationUpdates(locationCallBack) } .doOnError { it.printStackTrace() } } } }
apache-2.0
71781b550b7aee84d2a90b2a08886595
33.390244
118
0.656971
5.549213
false
false
false
false
cloudbearings/contentful-management.java
src/test/kotlin/com/contentful/java/cma/AndroidTests.kt
1
2026
package com.contentful.java.cma import android.app.Activity import android.content.Intent import android.os.Bundle import android.os.Looper import com.contentful.java.cma.lib.TestUtils import com.contentful.java.cma.model.CMAArray import com.contentful.java.cma.model.CMAAsset import com.squareup.okhttp.mockwebserver.MockResponse import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import kotlin.test.assertEquals import org.junit.Test as test @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE) class AndroidTests : BaseTest() { test fun testCallbackExecutesOnMainThread() { val responseBody = TestUtils.fileToString("asset_fetch_all_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val activity = Robolectric.buildActivity(javaClass<TestActivity>()) .withIntent(Intent().putExtra("EXTRA_URL", server!!.getUrl("/").toString())) .create() .get() while (activity.callbackLooper == null) { Thread.sleep(1000) } assertEquals(activity.mainThreadLooper, activity.callbackLooper) } class TestActivity : Activity() { val mainThreadLooper = Looper.getMainLooper() var callbackLooper: Looper? = null override fun onCreate(savedInstanceState: Bundle?) { super<Activity>.onCreate(savedInstanceState) val cb = object : CMACallback<CMAArray<CMAAsset>>() { override fun onSuccess(result: CMAArray<CMAAsset>?) { callbackLooper = Looper.myLooper() } } val androidClient = CMAClient.Builder() .setAccessToken("token") .setEndpoint(getIntent().getStringExtra("EXTRA_URL")) .build() androidClient.assets().async().fetchAll("space-id", cb) } } }
apache-2.0
f9fe3459544c2c7a51e6c232f21be504
34.561404
92
0.668312
4.858513
false
true
false
false
evant/silent-support
silent-support/src/test/kotlin/me/tatarka/silentsupport/SilentSupportProcessorTest.kt
1
6932
package me.tatarka.silentsupport import android.app.Activity import android.content.Context import android.graphics.drawable.Drawable import android.net.ConnectivityManager import android.support.v4.content.ContextCompat import android.support.v4.net.ConnectivityManagerCompat import android.support.v4.view.ViewCompat import android.view.View import me.tatarka.assertk.assert import me.tatarka.assertk.assertions.isEqualTo import me.tatarka.assertk.assertions.isNotNull import me.tatarka.assertk.assertions.isTrue import me.tatarka.assertk.assertions.isZero import org.junit.After import org.junit.Before import org.junit.Test import org.mockito.Mockito.* import java.io.File import java.util.function.Function @Suppress("UNCHECKED_CAST") class SilentSupportProcessorTest { @Before fun setup() { ContextCompat.reset() ViewCompat.reset() ConnectivityManagerCompat.reset() } private fun processor(apiLevel: Int): SilentSupportProcessor { val classpath = listOf(File("test-libs/android-25.jar"), File("test-libs/support-compat-25.3.0.aar")) val outputDir = File("build/resources/test") val supportCompat = SupportCompat.fromClasspath(classpath)!! val supportMetadataProcessor = SupportMetadataProcessor(supportCompat, outputDir) supportMetadataProcessor.process() return SilentSupportProcessor( classpath, supportMetadataProcessor.metadataFile, apiLevel, outputDir) } @After fun teardown() { validateMockitoUsage() } @Test fun `context#getDrawable to ContextCompat#getDrawable because api level is not high enough`() { val inputClassFile = compile("TestGetDrawable", """public class TestGetDrawable implements java.util.function.Function<android.content.Context, android.graphics.drawable.Drawable> { public android.graphics.drawable.Drawable apply(android.content.Context context) { return context.getDrawable(4); } }""") val processedClass = processor(14).process(inputClassFile.classFile()) inputClassFile.replaceWith(processedClass) val testClass: Function<Context, Drawable?> = inputClassFile.load().newInstance() as Function<Context, Drawable?> val result = testClass.apply(mock(Context::class.java)) assert(result).isNotNull() assert(ContextCompat.record_getDrawable_id).isEqualTo(4) } @Test fun `context#getDrawable not converted because api level is high enough`() { val inputClassFile = compile("TestGetDrawable2", """public class TestGetDrawable2 implements java.util.function.Function<android.content.Context, android.graphics.drawable.Drawable> { public android.graphics.drawable.Drawable apply(android.content.Context context) { return context.getDrawable(4); } }""") val processedClass = processor(21).process(inputClassFile.classFile()) inputClassFile.replaceWith(processedClass) val testClass: Function<Context, Drawable?> = inputClassFile.load().newInstance() as Function<Context, Drawable?> val contextMock = mock(Context::class.java) testClass.apply(contextMock) assert(ContextCompat.record_getDrawable_id).isZero() verify(contextMock).getDrawable(eq(4)) } @Test fun `context#createConfigurationContext not converted because it does not exist in ContextCompat`() { val inputClassFile = compile("TestCreateConfigurationContext", """public class TestCreateConfigurationContext implements java.util.function.Function<android.content.Context, android.content.Context> { public android.content.Context apply(android.content.Context context) { return context.createConfigurationContext(null); } }""") val processedClass = processor(16).process(inputClassFile.classFile()) inputClassFile.replaceWith(processedClass) val testClass: Function<Context, Context> = inputClassFile.load().newInstance() as Function<Context, Context> val contextMock = mock(Context::class.java) testClass.apply(contextMock) verify(contextMock).createConfigurationContext(any()) } @Test fun `activity#getDrawable to ContextCompat#getDrawable because it extends Context and is in ContextCompat`() { val inputClassFile = compile("TestActivityGetDrawable", """public class TestActivityGetDrawable implements java.util.function.Function<android.app.Activity, android.graphics.drawable.Drawable> { public android.graphics.drawable.Drawable apply(android.app.Activity activity) { return activity.getDrawable(4); } }""") val processedClass = processor(14).process(inputClassFile.classFile()) inputClassFile.replaceWith(processedClass) val testClass: Function<Activity, Drawable?> = inputClassFile.load().newInstance() as Function<Activity, Drawable?> val result = testClass.apply(mock(Activity::class.java)) assert(result).isNotNull() assert(ContextCompat.record_getDrawable_id).isEqualTo(4) } @Test fun `view#getX to ViewCompat#getX because api level is not high enough`() { val inputClassFile = compile("TestGetX", """public class TestGetX implements java.util.function.Function<android.view.View, Float> { public Float apply(android.view.View view) { return view.getX(); } }""") val processedClass = processor(10).process(inputClassFile.classFile()) inputClassFile.replaceWith(processedClass) val testClass: Function<View, Float> = inputClassFile.load().newInstance() as Function<View, Float> val result = testClass.apply(mock(View::class.java)) assert(result).isNotNull() assert(ViewCompat.record_getX).isTrue() } @Test fun `conMan#isActiveNetworkMonitored to ConnectivityManagerCompat#isActiveNetworkMonitored because api level is not high enough`() { val inputClassFile = compile("TestIsActiveNetwork", """public class TestIsActiveNetwork implements java.util.function.Function<android.net.ConnectivityManager, Boolean> { public Boolean apply(android.net.ConnectivityManager conMan) { return conMan.isActiveNetworkMetered(); } }""") val processedClass = processor(14).process(inputClassFile.classFile()) inputClassFile.replaceWith(processedClass) val testClass: Function<ConnectivityManager, Boolean> = inputClassFile.load().newInstance() as Function<ConnectivityManager, Boolean> val result = testClass.apply(mock(ConnectivityManager::class.java)) assert(result).isNotNull() assert(ConnectivityManagerCompat.record_isActiveNetworkMetered).isTrue() } }
apache-2.0
c2f13a89bcfdcee65a518c93f5010e0d
46.486301
208
0.710329
4.857744
false
true
false
false
tmarsteel/kotlin-prolog
core/src/test/kotlin/com/github/prologdb/runtime/expression/ListUnificationTest.kt
1
2374
package com.github.prologdb.runtime.expression import com.github.prologdb.runtime.shouldNotUnifyWith import com.github.prologdb.runtime.shouldUnifyWith import com.github.prologdb.runtime.suchThat import com.github.prologdb.runtime.term.Atom import com.github.prologdb.runtime.term.PrologList import com.github.prologdb.runtime.term.Variable import io.kotest.core.spec.style.FreeSpec class ListUnificationTest : FreeSpec() {init { val a = Atom("a") val b = Atom("b") val X = Variable("X") val H = Variable("H") val T = Variable("T") "[a] = [a]" { PrologList(listOf(a)) shouldUnifyWith PrologList(listOf(a)) } "[a] \\== a" { PrologList(listOf(a)) shouldNotUnifyWith a } "a \\== [a]" { a shouldNotUnifyWith PrologList(listOf(a)) } "[a] = [X]" { PrologList(listOf(a)) shouldUnifyWith PrologList(listOf(X)) suchThat { it.variableValues[X] == a } } "[H|T] = [a]" { PrologList(listOf(H), T) shouldUnifyWith PrologList(listOf(a)) suchThat { it.variableValues[H] == a && it.variableValues[T] == PrologList(emptyList()) } } "[a] = [H|T]" { PrologList(listOf(a)) shouldUnifyWith PrologList(listOf(H), T) suchThat { it.variableValues[H] == a && it.variableValues[T] == PrologList(emptyList()) } } "[H|T] = [a,b]" { PrologList(listOf(H), T) shouldUnifyWith PrologList(listOf(a,b)) suchThat { it.variableValues[H] == a && it.variableValues[T] == PrologList(listOf(b)) } } "[a] \\== [b]" { PrologList(listOf(a)) shouldNotUnifyWith PrologList(listOf(b)) } "[a|T] \\== [b,b]" { PrologList(listOf(a), T) shouldNotUnifyWith PrologList(listOf(b, b)) } "[H,H] \\== [a,b]" { PrologList(listOf(H, H)) shouldNotUnifyWith PrologList(listOf(a, b)) } "[H|H] \\== [[a],b]" { PrologList(listOf(H), H) shouldNotUnifyWith PrologList(listOf(PrologList(listOf(a)), b)) } "[T1,T2,x|T1] \\== [[a],[b],x|T2]." { val T1 = Variable("T1") val T2 = Variable("T2") val x = Atom("x") PrologList(listOf(T1, T2, x), T1) shouldNotUnifyWith PrologList(listOf(PrologList(listOf(a)), PrologList(listOf(b)), x), T2) } }}
mit
84d25bad9b0975cf9a6a1dc91ce81e33
27.614458
132
0.573715
3.315642
false
false
false
false
VerifAPS/verifaps-lib
geteta/src/main/kotlin/edu/kit/iti/formal/automation/testtables/smtconcrete/SmtModel.kt
1
1864
package edu.kit.iti.formal.automation.testtables.smtconcrete import edu.kit.iti.formal.automation.datatypes.AnyDt import edu.kit.iti.formal.automation.rvt.translators.DefaultTypeTranslator import edu.kit.iti.formal.automation.rvt.translators.TypeTranslator import edu.kit.iti.formal.automation.smt.DefaultS2SFunctionTranslator import edu.kit.iti.formal.automation.smt.DefaultS2STranslator import edu.kit.iti.formal.automation.smt.S2SDataTypeTranslator import edu.kit.iti.formal.automation.smt.S2SFunctionTranslator import edu.kit.iti.formal.smt.SExpr import edu.kit.iti.formal.smt.SExprFacade.sexpr import edu.kit.iti.formal.smt.SInteger import edu.kit.iti.formal.smt.SList import edu.kit.iti.formal.smt.SSymbol class SmtModel { val file: MutableList<SExpr> = ArrayList() var fnTranslator: S2SFunctionTranslator = DefaultS2SFunctionTranslator() var dtTranslator: S2SDataTypeTranslator = DefaultS2STranslator() var typeTranslator: TypeTranslator = DefaultTypeTranslator() fun declare(name: String, dataType: SExpr) { val e = sexpr("declare-const", name, dataType) file.add(e) } fun declare(name: String, dataType: AnyDt) { declare(name, dtTranslator.translate(typeTranslator.translate(dataType))) } fun assert(constr: SExpr) { file.add(sexpr("assert", constr)) } fun bvOf(lower: Int, bitLength: Int) = SList(SList(SSymbol("_"), SSymbol("int2bv"), SInteger(bitLength)), SInteger(lower)) val sexp: MutableCollection<SmtStatement> = arrayListOf() val asSexp: String get() = sexp.joinToString("\n") { it.toString() } } sealed class SmtStatement { //abstract val asSexp: Sexp } data class SmtConstDeclaration(val name: String, val type: String) : SmtStatement() { override fun toString(): String = "(declare-const $name $type)" }
gpl-3.0
04c091d6f7d4854548b0ee2a470fef0a
32.909091
95
0.737661
3.503759
false
false
false
false
VerifAPS/verifaps-lib
lang/src/main/kotlin/edu/kit/iti/formal/automation/analysis/TranslateFbdToSt.kt
1
763
package edu.kit.iti.formal.automation.analysis import edu.kit.iti.formal.automation.IEC61131Facade import edu.kit.iti.formal.automation.st.ast.HasFbBody import edu.kit.iti.formal.automation.st.ast.HasStBody import edu.kit.iti.formal.automation.st.util.AstVisitorWithScope import edu.kit.iti.formal.util.CodeWriter /** * * @author Alexander Weigl * @version 1 (10.07.19) */ object TranslateFbdToSt : AstVisitorWithScope<Unit>() { override fun defaultVisit(obj: Any) { val st = (obj as? HasStBody) val body = (obj as? HasFbBody)?.fbBody if(st!= null && body!=null) { val out = CodeWriter() body.asStructuredText(out) st.stBody = IEC61131Facade.statements(out.stream.toString()) } } }
gpl-3.0
9d1872bdf2bc3526079a2e6b3d8824eb
30.833333
72
0.686763
3.391111
false
false
false
false
jonnyzzz/TeamCity.Node
agent/src/main/java/com/jonnyzzz/teamcity/plugins/node/agent/npm/NPMServiceFactory.kt
1
5984
/* * Copyright 2013-2015 Eugene Petrenko * * 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.jonnyzzz.teamcity.plugins.node.agent.npm import com.jonnyzzz.teamcity.plugins.node.agent.processes.Execution import com.jonnyzzz.teamcity.plugins.node.agent.processes.ScriptWrappingCommandLineGenerator import com.jonnyzzz.teamcity.plugins.node.common.NPMBean import com.jonnyzzz.teamcity.plugins.node.common.fetchArguments import com.jonnyzzz.teamcity.plugins.node.common.isEmptyOrSpaces import com.jonnyzzz.teamcity.plugins.node.common.splitHonorQuotes import jetbrains.buildServer.BuildProblemData import jetbrains.buildServer.BuildProblemTypes import jetbrains.buildServer.agent.* import jetbrains.buildServer.agent.runner.* import jetbrains.buildServer.serverSide.BuildTypeOptions import org.apache.log4j.Logger /** * Created by Eugene Petrenko ([email protected]) * Date: 15.01.13 22:55 */ class NPMServiceFactory : MultiCommandBuildSessionFactory { val bean = NPMBean() override fun createSession(p0: BuildRunnerContext): MultiCommandBuildSession = NPMSession(p0) override fun getBuildRunnerInfo(): AgentBuildRunnerInfo = object : AgentBuildRunnerInfo{ override fun getType(): String = bean.runTypeName override fun canRun(agentConfiguration: BuildAgentConfiguration): Boolean = true } } class NPMSession(val runner : BuildRunnerContext) : MultiCommandBuildSession { private val bean = NPMBean() private var iterator : Iterator<NPMCommandExecution> = listOf<NPMCommandExecution>().iterator() private var previousStatus = BuildFinishedStatus.FINISHED_SUCCESS private val logger = runner.build.buildLogger.getFlowLogger(FlowGenerator.generateNewFlow()) private fun resolveNpmExecutable() : String { val path = runner.runnerParameters[bean.toolPathKey] if (path == null || path.isEmptyOrSpaces()) return "npm" return path.trim() } override fun sessionStarted() { logger.startFlow() val extra = runner.runnerParameters[bean.commandLineParameterKey].fetchArguments() val checkExitCode = runner.build.getBuildTypeOptionValue(BuildTypeOptions.BT_FAIL_ON_EXIT_CODE) ?: true val npm = resolveNpmExecutable() iterator = bean.parseCommands(runner.runnerParameters[bean.npmCommandsKey]) .map{ NPMCommandExecution( logger, "npm $it", runner, Execution(npm, extra + it.splitHonorQuotes())){ exitCode -> previousStatus = when { exitCode == 0 && checkExitCode -> BuildFinishedStatus.FINISHED_SUCCESS else -> BuildFinishedStatus.FINISHED_WITH_PROBLEMS } } }.iterator() } override fun getNextCommand(): CommandExecution? = when { previousStatus != BuildFinishedStatus.FINISHED_SUCCESS -> null iterator.hasNext() -> iterator.next() else -> null } override fun sessionFinished(): BuildFinishedStatus { logger.disposeFlow() return previousStatus } } class NPMCommandExecution(val logger : BuildProgressLogger, val blockName : String, val runner : BuildRunnerContext, val cmd : Execution, val onFinished : (Int) -> Unit) : LoggingProcessListener(logger), CommandExecution { private val bean = NPMBean() private val OUT_LOG : Logger? = Logger.getLogger("teamcity.out") private val disposables = arrayListOf<() -> Unit>() override fun makeProgramCommandLine(): ProgramCommandLine = object:ScriptWrappingCommandLineGenerator<ProgramCommandLine>(runner) { override fun execute(executable: String, args: List<String>): ProgramCommandLine = SimpleProgramCommandLine(build, executable, args) override fun disposeLater(action: () -> Unit) { disposables.add(action) } }.generate(cmd.program, cmd.arguments) override fun beforeProcessStarted() { logger.activityStarted(blockName, "npm"); } override fun onStandardOutput(text: String) { if (text.contains("npm ERR!")){ logger.error(text) OUT_LOG?.warn(text) return } super.onStandardOutput(text) } override fun onErrorOutput(text: String) { if (text.contains("npm ERR!")){ logger.error(text) OUT_LOG?.warn(text) return } super.onErrorOutput(text) } override fun processFinished(exitCode: Int) { super.processFinished(exitCode) if (exitCode != 0) { logger.logBuildProblem(createExitCodeBuildProblem(exitCode)) } logger.activityFinished(blockName, "npm"); disposables.forEach { it() } onFinished(exitCode) } // copy of jetbrains.buildServer.agent.runner.CommandLineBuildService.createExitCodeBuildProblem for backward compatibility private fun createExitCodeBuildProblem(exitCode: Int): BuildProblemData { return BuildProblemData.createBuildProblem( bean.runTypeName + exitCode, BuildProblemTypes.TC_EXIT_CODE_TYPE, "Process exited with code " + exitCode, "teamcity.process.flow.id=" + logger.flowId) } override fun interruptRequested(): TerminationAction = TerminationAction.KILL_PROCESS_TREE override fun isCommandLineLoggingEnabled(): Boolean = true }
apache-2.0
cf87d96691dc75bb529484607b76ede1
36.63522
125
0.694686
4.726698
false
false
false
false
cketti/k-9
mail/common/src/main/java/com/fsck/k9/mail/ServerSettings.kt
1
1053
package com.fsck.k9.mail /** * Container for incoming or outgoing server settings */ data class ServerSettings @JvmOverloads constructor( @JvmField val type: String, @JvmField val host: String?, @JvmField val port: Int, @JvmField val connectionSecurity: ConnectionSecurity, @JvmField val authenticationType: AuthType, @JvmField val username: String, @JvmField val password: String?, @JvmField val clientCertificateAlias: String?, val extra: Map<String, String?> = emptyMap() ) { val isMissingCredentials: Boolean = when (authenticationType) { AuthType.EXTERNAL -> clientCertificateAlias == null else -> username.isNotBlank() && password == null } init { require(type == type.lowercase()) { "type must be all lower case" } } fun newPassword(newPassword: String?): ServerSettings { return this.copy(password = newPassword) } fun newAuthenticationType(authType: AuthType): ServerSettings { return this.copy(authenticationType = authType) } }
apache-2.0
760ca101aa7c1bdf2ee3ea562c84b4e8
30.909091
75
0.687559
4.68
false
false
false
false
chillcoding-at-the-beach/my-cute-heart
MyCuteHeart/app/src/main/java/com/chillcoding/ilove/view/dialog/LevelDialog.kt
1
1696
package com.chillcoding.ilove.view.dialog import android.app.AlertDialog import android.app.Dialog import android.app.DialogFragment import android.os.Bundle import android.view.LayoutInflater import com.chillcoding.ilove.App import com.chillcoding.ilove.MainActivity import com.chillcoding.ilove.R import com.chillcoding.ilove.view.activity.PurchaseActivity import kotlinx.android.synthetic.main.dialog_level.view.* import org.jetbrains.anko.share import org.jetbrains.anko.startActivity class LevelDialog : DialogFragment() { private val mLoveQuoteArray: Array<String> by lazy { resources.getStringArray(R.array.text_love) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val activity = (activity as MainActivity) val builder = AlertDialog.Builder(activity) val dialogLevelView = (LayoutInflater.from(activity)).inflate(R.layout.dialog_level, null) val level = arguments.getInt(App.BUNDLE_GAME_LEVEL) //draw the UI dialogLevelView.levelNumber.text = "${getString(R.string.word_level)} ${level}" dialogLevelView.levelQuote.text = mLoveQuoteArray[(level - 2) % mLoveQuoteArray.size] builder.setView(dialogLevelView) .setPositiveButton(R.string.action_continue, null) if (activity.isPremium || activity.isUnlimitedQuotes) builder.setNeutralButton(R.string.action_share, { _, _ -> share("${dialogLevelView.levelQuote.text} \n${getString(R.string.text_from)} ${getString(R.string.url_app)}", "I Love") }) else builder.setNeutralButton(R.string.action_more, { _, _ -> startActivity<PurchaseActivity>() }) return builder.create() } }
gpl-3.0
97db0b39cf0e7661a169461a32f818c2
42.512821
193
0.731132
3.944186
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/economy/broker/BrokerBuyStockExecutor.kt
1
5385
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.broker import net.perfectdreams.loritta.cinnamon.emotes.Emotes import net.perfectdreams.loritta.common.utils.LorittaBovespaBrokerUtils import net.perfectdreams.loritta.i18n.I18nKeysData import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.declarations.BrokerCommand import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled import net.perfectdreams.loritta.cinnamon.discord.utils.NumberUtils import net.perfectdreams.loritta.cinnamon.discord.utils.SonhosUtils import net.perfectdreams.loritta.cinnamon.discord.utils.SonhosUtils.appendUserHaventGotDailyTodayOrUpsellSonhosBundles import net.perfectdreams.loritta.cinnamon.pudding.data.UserId import net.perfectdreams.loritta.cinnamon.pudding.services.BovespaBrokerService class BrokerBuyStockExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) { inner class Options : LocalizedApplicationCommandOptions(loritta) { val ticker = string("ticker", BrokerCommand.I18N_PREFIX.Buy.Options.Ticker.Text) { autocomplete(BrokerBuyStockAutocompleteExecutor(loritta)) } val quantity = optionalString("quantity", BrokerCommand.I18N_PREFIX.Buy.Options.Quantity.Text) { autocomplete(BrokerStockQuantityAutocompleteExecutor(loritta, ticker)) } } override val options = Options() override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) { context.deferChannelMessageEphemerally() val tickerId = args[options.ticker].uppercase() val quantityAsString = args[options.quantity] ?: "1" // This should *never* happen because the values are validated on Discord side BUT who knows if (tickerId !in LorittaBovespaBrokerUtils.validStocksCodes) context.failEphemerally(context.i18nContext.get(BrokerCommand.I18N_PREFIX.ThatIsNotAnValidStockTicker(loritta.commandMentions.brokerInfo))) val quantity = NumberUtils.convertShortenedNumberToLong(context.i18nContext, quantityAsString) ?: context.failEphemerally( context.i18nContext.get( I18nKeysData.Commands.InvalidNumber(quantityAsString) ) ) val (_, boughtQuantity, value) = try { context.loritta.pudding.bovespaBroker.buyStockShares( context.user.id.value.toLong(), tickerId, quantity ) } catch (e: BovespaBrokerService.TransactionActionWithLessThanOneShareException) { context.failEphemerally( context.i18nContext.get( when (quantity) { 0L -> BrokerCommand.I18N_PREFIX.Buy.TryingToBuyZeroShares else -> BrokerCommand.I18N_PREFIX.Buy.TryingToBuyLessThanZeroShares } ) ) } catch (e: BovespaBrokerService.StaleTickerDataException) { context.failEphemerally(context.i18nContext.get(BrokerCommand.I18N_PREFIX.StaleTickerData)) } catch (e: BovespaBrokerService.OutOfSessionException) { context.failEphemerally( context.i18nContext.get( BrokerCommand.I18N_PREFIX.StockMarketClosed( LorittaBovespaBrokerUtils.TIME_OPEN_DISCORD_TIMESTAMP, LorittaBovespaBrokerUtils.TIME_CLOSING_DISCORD_TIMESTAMP ) ) ) } catch (e: BovespaBrokerService.NotEnoughSonhosException) { context.failEphemerally { styled( context.i18nContext.get(SonhosUtils.insufficientSonhos(e.userSonhos, e.howMuch)), Emotes.LoriSob ) appendUserHaventGotDailyTodayOrUpsellSonhosBundles( context.loritta, context.i18nContext, UserId(context.user.id.value), "lori-broker", "buy-shares-not-enough-sonhos" ) } } catch (e: BovespaBrokerService.TooManySharesException) { context.failEphemerally( context.i18nContext.get( BrokerCommand.I18N_PREFIX.Buy.TooManyShares( LorittaBovespaBrokerUtils.MAX_STOCK_SHARES_PER_USER ) ) ) } context.sendEphemeralReply( context.i18nContext.get( BrokerCommand.I18N_PREFIX.Buy.SuccessfullyBought( sharesCount = boughtQuantity, ticker = tickerId, price = value, brokerPortfolioCommandMention = loritta.commandMentions.brokerPortfolio ) ), Emotes.LoriRich ) } }
agpl-3.0
2147e96a405e4d14e78973a630c248c9
47.522523
151
0.672609
5.202899
false
false
false
false