content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright 2021 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.grip
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.grip.mirrors.getMethodType
import io.michaelrocks.grip.mirrors.getObjectTypeByInternalName
import io.michaelrocks.grip.mirrors.getType
import org.junit.Test
class TypeMatchersTest {
private val void = Type.Primitive.Void
private val string = getType<String>()
private val array = getType("[I")
private val method = getMethodType(Type.Primitive.Int, getType<Any>())
@Test
fun testTypeEqualsTrue() = string.assertMatcher(true, equalsTo(getObjectTypeByInternalName("java/lang/String")))
@Test
fun testTypeEqualsFalse() = string.assertMatcher(false, equalsTo(getObjectTypeByInternalName("java/lang/Object")))
@Test
fun testIsPrimitiveTrue() = void.assertMatcher(true, isPrimitive())
@Test
fun testIsPrimitiveFalse() = string.assertMatcher(false, isPrimitive())
@Test
fun testIsArrayTrue() = array.assertMatcher(true, isArray())
@Test
fun testIsArrayFalse() = void.assertMatcher(false, isArray())
@Test
fun testIsObjectTrue() = string.assertMatcher(true, isObject())
@Test
fun testIsObjectFalse() = void.assertMatcher(false, isObject())
@Test
fun testIsVoidTrue() = void.assertMatcher(true, isVoid())
@Test
fun testIsVoidFalse() = array.assertMatcher(false, isVoid())
@Test
fun testReturnsTrue() = method.assertMatcher(true, returns(Type.Primitive.Int))
@Test
fun testReturnsFalse() = method.assertMatcher(false, returns(Type.Primitive.Void))
}
| library/src/test/java/io/michaelrocks/grip/TypeMatchersTest.kt | 532298677 |
/*
* MIT License
*
* Copyright (c) 2017 Frederik Ar. Mikkelsen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package fredboat.audio.queue
interface ITrackProvider {
/**
* @return a list of all tracks in the queue in regular (unshuffled) order
*/
val asList: List<AudioTrackContext>
/**
* @return true if there are no tracks in the queue
*/
val isEmpty: Boolean
/**
* @return duration of all tracks
*/
val durationMillis: Long
/**
* @return the track that a call to provideAudioTrack() would return
*/
fun peek(): AudioTrackContext?
/**
* @return the next track, or null if empty
*/
fun provideAudioTrack(): AudioTrackContext?
/**
* Call this when the current track is skipped by the user to let the provider know about it
*/
fun skipped()
/**
* When restoring a guild player this allows us to set a potentially currently playing track
*/
fun setLastTrack(lastTrack: AudioTrackContext)
/**
* @return amount of tracks in the queue
*/
fun size(): Int
/**
* @param track add a track to the queue
*/
fun add(track: AudioTrackContext)
/**
* @param tracks add several tracks to the queue
*/
fun addAll(tracks: Collection<AudioTrackContext>)
/**
* Add track to the front of the queue
*
* @param track track to be added
*/
fun addFirst(track: AudioTrackContext)
/**
* Add a collection of tracks to the front of the queue
*
* @param tracks collection of tracks to be added
*/
fun addAllFirst(tracks: Collection<AudioTrackContext>)
/**
* empty the queue
*/
fun clear()
/**
* remove a track from the queue
*
* @param atc the track to be removed
* @return true if the track part of the queue, false if not
*/
fun remove(atc: AudioTrackContext): Boolean
/**
* @param tracks tracks to be removed from the queue
*/
fun removeAll(tracks: Collection<AudioTrackContext>)
/**
* @param trackIds tracks to be removed from the queue
*/
fun removeAllById(trackIds: Collection<Long>)
/**
* @param index the index of the requested track in playing order
* @return the track at the given index
*/
fun getTrack(index: Int): AudioTrackContext
/**
* Returns all songs from one index till another in a non-bitching way.
* That means we will look from the inclusive lower one of the provided two indices to the exclusive higher one.
* If an index is lower 0 the range will start at 0, and if an index is over the max size of the track list
* the range will end at the max size of the track list
*
* @param startIndex inclusive starting index
* @param endIndex exclusive ending index
* @return the tracks in the given range
*/
fun getTracksInRange(startIndex: Int, endIndex: Int): List<AudioTrackContext>
/**
* @return amount of live streams
*/
fun streamsCount(): Int
/**
* @return false if any of the provided tracks was added by user that is not the provided userId
*/
fun isUserTrackOwner(userId: Long, trackIds: Collection<Long>): Boolean
}
| FredBoat/src/main/java/fredboat/audio/queue/ITrackProvider.kt | 2409168773 |
package elmdroid.elmdroid.example1.hello
import elmdroid.elmdroid.example1.ExampleHelloWorldActivity
import kotlinx.android.synthetic.main.activity_helloworld.*
import saffih.elmdroid.ElmChild
/**
* Copyright Joseph Hartal (Saffi)
* Created by saffi on 9/05/17.
*/
// POJO
enum class ESpeed {
sleep,
slow,
fast,
rocket;
fun step(by: Int) = if (ordIn(ordinal + by)) ESpeed.values()[ordinal + by] else this
fun next() = step(1)
fun prev() = step(-1)
fun cnext() = cycle(ordinal + 1)
fun cprev() = cycle(ordinal - 1)
companion object {
fun ordIn(i: Int) = (i >= 0 && i < ESpeed.values().size)
fun cycle(i: Int) = ESpeed.values()[i % ESpeed.values().size]
}
}
// MODEL
data class Model(val speed: MSpeed = MSpeed(), val ui: MUIMode = MUIMode())
data class MSpeed(val speed: ESpeed = ESpeed.slow)
data class MUIMode(val faster: Boolean = true)
// MSG
sealed class Msg {
class Init : Msg()
sealed class ChangeSpeed : Msg() {
class Increase : ChangeSpeed()
class Decrease : ChangeSpeed()
class CycleUp : ChangeSpeed()
class Night : ChangeSpeed()
}
sealed class UI : Msg() {
class ToggleClicked : UI()
class NextSpeedClicked : UI()
}
}
abstract class Turtle(val me: ExampleHelloWorldActivity) :
ElmChild<Model, Msg>() {
override fun init(): Model{
dispatch( Msg.Init())
return Model()
}
private fun update(msg: Msg.Init, model: MSpeed): MSpeed{
return model
}
private fun update(msg: Msg.ChangeSpeed, model: MSpeed): MSpeed{
return when (msg) {
is Msg.ChangeSpeed.Increase -> model.copy(speed = model.speed.next())
is Msg.ChangeSpeed.Decrease -> model.copy(speed = model.speed.prev())
is Msg.ChangeSpeed.CycleUp -> model.copy(speed = model.speed.cnext())
is Msg.ChangeSpeed.Night -> model.copy(speed = ESpeed.sleep)
}
}
override fun update(msg: Msg, model: Model) : Model{
return when (msg) {
is Msg.Init -> {
val m = update(msg, model.speed)
val mu = update(msg, model.ui)
model.copy(speed = m, ui = mu)
}
is Msg.ChangeSpeed -> {
val m = update(msg, model.speed)
model.copy(speed = m)
}
is Msg.UI -> {
val m = update(msg, model.ui)
model.copy(ui = m)
}
}
}
private fun update(msg: Msg.UI, model: MUIMode) : MUIMode{
// return model)
return when (msg) {
is Msg.UI.ToggleClicked -> model.copy(faster = !model.faster)
is Msg.UI.NextSpeedClicked -> {
dispatch ( if (model.faster) Msg.ChangeSpeed.Increase() else Msg.ChangeSpeed.Decrease())
model
}
}
}
private fun update(msg: Msg.Init, model: MUIMode) : MUIMode{
return model
}
override fun view(model: Model, pre: Model?) {
val setup = {}
checkView(setup, model, pre) {
view(model.speed, pre?.speed)
view(model.ui, pre?.ui)
}
}
private fun view(model: MUIMode, pre: MUIMode?) {
val setup = {}
checkView(setup, model, pre) {
val mode = me.turtleFaster
mode.text = if (model.faster) "faster" else "slower"
mode.setOnClickListener { dispatch(Msg.UI.ToggleClicked()) }
}
}
private fun view(model: MSpeed, pre: MSpeed?) {
val setup = {}
checkView(setup, model, pre) {
val v = me.turtleSpeed
v.text = model.speed.name
v.setOnClickListener { dispatch(Msg.UI.NextSpeedClicked()) }
}
}
}
| app/src/main/java/elmdroid/elmdroid/example1/hello/Turtle.kt | 1688020716 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.updateSettings.impl
import com.intellij.diagnostic.IdeErrorsDialog
import com.intellij.externalDependencies.DependencyOnPlugin
import com.intellij.externalDependencies.ExternalDependenciesManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.externalComponents.ExternalComponentManager
import com.intellij.ide.plugins.*
import com.intellij.ide.util.PropertiesComponent
import com.intellij.internal.statistic.service.fus.collectors.FUSApplicationUsageTrigger
import com.intellij.notification.*
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.LogUtil
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.ActionCallback
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.Url
import com.intellij.util.Urls
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.MultiMap
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.URLUtil
import com.intellij.util.loadElement
import com.intellij.util.ui.UIUtil
import com.intellij.xml.util.XmlStringUtil
import gnu.trove.THashMap
import org.jdom.JDOMException
import java.io.File
import java.io.IOException
import java.util.*
import kotlin.collections.HashSet
import kotlin.collections.set
/**
* See XML file by [ApplicationInfoEx.getUpdateUrls] for reference.
*/
object UpdateChecker {
private val LOG = Logger.getInstance("#com.intellij.openapi.updateSettings.impl.UpdateChecker")
@JvmField val NOTIFICATIONS: NotificationGroup = NotificationGroup(IdeBundle.message("update.notifications.title"), NotificationDisplayType.STICKY_BALLOON, true)
private const val DISABLED_UPDATE = "disabled_update.txt"
private enum class NotificationUniqueType { PLATFORM, PLUGINS, EXTERNAL }
private var ourDisabledToUpdatePlugins: MutableSet<String>? = null
private val ourAdditionalRequestOptions = THashMap<String, String>()
private val ourUpdatedPlugins = hashMapOf<String, PluginDownloader>()
private val ourShownNotifications = MultiMap<NotificationUniqueType, Notification>()
/**
* Adding a plugin ID to this collection allows to exclude a plugin from a regular update check.
* Has no effect on non-bundled or "essential" (i.e. required for one of open projects) plugins.
*/
@Suppress("MemberVisibilityCanBePrivate")
val excludedFromUpdateCheckPlugins: HashSet<String> = hashSetOf()
private val updateUrl: String
get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls.checkingUrl
/**
* For scheduled update checks.
*/
@JvmStatic
fun updateAndShowResult(): ActionCallback {
val callback = ActionCallback()
ApplicationManager.getApplication().executeOnPooledThread {
doUpdateAndShowResult(null, true, false, UpdateSettings.getInstance(), null, callback)
}
return callback
}
/**
* For manual update checks (Help | Check for Updates, Settings | Updates | Check Now)
* (the latter action may pass customised update settings).
*/
@JvmStatic
fun updateAndShowResult(project: Project?, customSettings: UpdateSettings?) {
val settings = customSettings ?: UpdateSettings.getInstance()
val fromSettings = customSettings != null
ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) {
override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult(getProject(), fromSettings, true, settings, indicator, null)
override fun isConditionalModal(): Boolean = fromSettings
override fun shouldStartInBackground(): Boolean = !fromSettings
})
}
/**
* An immediate check for plugin updates for use from a command line (read "Toolbox").
*/
@JvmStatic
fun getPluginUpdates(): Collection<PluginDownloader>? =
checkPluginsUpdate(UpdateSettings.getInstance(), EmptyProgressIndicator(), null, ApplicationInfo.getInstance().build)
private fun doUpdateAndShowResult(project: Project?,
fromSettings: Boolean,
manualCheck: Boolean,
updateSettings: UpdateSettings,
indicator: ProgressIndicator?,
callback: ActionCallback?) {
// check platform update
indicator?.text = IdeBundle.message("updates.checking.platform")
val result = checkPlatformUpdate(updateSettings)
if (result.state == UpdateStrategy.State.CONNECTION_ERROR) {
val e = result.error
if (e != null) LOG.debug(e)
showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", e?.message ?: "internal error"))
callback?.setRejected()
return
}
// check plugins update (with regard to potential platform update)
indicator?.text = IdeBundle.message("updates.checking.plugins")
val buildNumber: BuildNumber? = result.newBuild?.apiVersion
val incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>? = if (buildNumber != null) HashSet() else null
val updatedPlugins: Collection<PluginDownloader>?
val externalUpdates: Collection<ExternalUpdate>?
try {
updatedPlugins = checkPluginsUpdate(updateSettings, indicator, incompatiblePlugins, buildNumber)
externalUpdates = checkExternalUpdates(manualCheck, updateSettings, indicator)
}
catch (e: IOException) {
showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", e.message))
callback?.setRejected()
return
}
// show result
UpdateSettings.getInstance().saveLastCheckedInfo()
ApplicationManager.getApplication().invokeLater({
showUpdateResult(project, result, updateSettings, updatedPlugins, incompatiblePlugins, externalUpdates, !fromSettings, manualCheck)
callback?.setDone()
}, if (fromSettings) ModalityState.any() else ModalityState.NON_MODAL)
}
private fun checkPlatformUpdate(settings: UpdateSettings): CheckForUpdateResult {
val updateInfo: UpdatesInfo?
try {
var updateUrl = Urls.newFromEncoded(updateUrl)
if (updateUrl.scheme != URLUtil.FILE_PROTOCOL) {
updateUrl = prepareUpdateCheckArgs(updateUrl, settings.packageManagerName)
}
LogUtil.debug(LOG, "load update xml (UPDATE_URL='%s')", updateUrl)
updateInfo = HttpRequests.request(updateUrl)
.forceHttps(settings.canUseSecureConnection())
.connect {
try {
if (settings.isPlatformUpdateEnabled)
UpdatesInfo(loadElement(it.reader))
else
null
}
catch (e: JDOMException) {
// corrupted content, don't bother telling user
LOG.info(e)
null
}
}
}
catch (e: Exception) {
LOG.info(e)
return CheckForUpdateResult(UpdateStrategy.State.CONNECTION_ERROR, e)
}
if (updateInfo == null) {
return CheckForUpdateResult(UpdateStrategy.State.NOTHING_LOADED, null)
}
val strategy = UpdateStrategy(ApplicationInfo.getInstance().build, updateInfo, settings)
return strategy.checkForUpdates()
}
@JvmStatic
@Throws(IOException::class)
fun getUpdatesInfo(settings: UpdateSettings): UpdatesInfo? {
val updateUrl = Urls.newFromEncoded(updateUrl)
LogUtil.debug(LOG, "load update xml (UPDATE_URL='%s')", updateUrl)
return HttpRequests.request(updateUrl)
.forceHttps(settings.canUseSecureConnection())
.connect {
try {
UpdatesInfo(loadElement(it.reader))
}
catch (e: JDOMException) {
// corrupted content, don't bother telling user
LOG.info(e)
null
}
}
}
private fun checkPluginsUpdate(updateSettings: UpdateSettings,
indicator: ProgressIndicator?,
incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?,
buildNumber: BuildNumber?): Collection<PluginDownloader>? {
val updateable = collectUpdateablePlugins()
if (updateable.isEmpty()) return null
val toUpdate = ContainerUtil.newTroveMap<PluginId, PluginDownloader>()
val state = InstalledPluginsState.getInstance()
outer@ for (host in RepositoryHelper.getPluginHosts()) {
try {
val forceHttps = host == null && updateSettings.canUseSecureConnection()
val list = RepositoryHelper.loadPlugins(host, buildNumber, forceHttps, indicator)
for (descriptor in list) {
val id = descriptor.pluginId
if (updateable.containsKey(id)) {
updateable.remove(id)
state.onDescriptorDownload(descriptor)
val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber, forceHttps)
checkAndPrepareToInstall(downloader, state, toUpdate, incompatiblePlugins, indicator)
if (updateable.isEmpty()) {
break@outer
}
}
}
}
catch (e: IOException) {
LOG.debug(e)
LOG.info("failed to load plugin descriptions from ${host ?: "default repository"}: ${e.message}")
}
}
return if (toUpdate.isEmpty) null else toUpdate.values
}
/**
* Returns a list of plugins which are currently installed or were installed in the previous installation from which
* we're importing the settings.
*/
private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor> {
val updateable = ContainerUtil.newTroveMap<PluginId, IdeaPluginDescriptor>()
updateable += PluginManagerCore.getPlugins().filter { !it.isBundled || it.allowBundledUpdate()}.associateBy { it.pluginId }
val onceInstalled = PluginManager.getOnceInstalledIfExists()
if (onceInstalled != null) {
try {
FileUtil.loadLines(onceInstalled)
.map { line -> PluginId.getId(line.trim { it <= ' ' }) }
.filter { it !in updateable }
.forEach { updateable[it] = null }
}
catch (e: IOException) {
LOG.error(onceInstalled.path, e)
}
//noinspection SSBasedInspection
onceInstalled.deleteOnExit()
}
if (!excludedFromUpdateCheckPlugins.isEmpty()) {
val required = ProjectManager.getInstance().openProjects
.flatMap { ExternalDependenciesManager.getInstance(it).getDependencies(DependencyOnPlugin::class.java) }
.map { PluginId.getId(it.pluginId) }
.toSet()
excludedFromUpdateCheckPlugins.forEach {
val excluded = PluginId.getId(it)
if (excluded !in required) {
val plugin = updateable[excluded]
if (plugin != null && plugin.isBundled) {
updateable.remove(excluded)
}
}
}
}
return updateable
}
private fun checkExternalUpdates(manualCheck: Boolean, updateSettings: UpdateSettings, indicator: ProgressIndicator?) : Collection<ExternalUpdate> {
val result = arrayListOf<ExternalUpdate>()
val manager = ExternalComponentManager.getInstance()
indicator?.text = IdeBundle.message("updates.external.progress")
for (source in manager.componentSources) {
indicator?.checkCanceled()
if (source.name in updateSettings.enabledExternalUpdateSources) {
try {
val siteResult = source.getAvailableVersions(indicator, updateSettings)
.filter { it.isUpdateFor(manager.findExistingComponentMatching(it, source)) }
if (!siteResult.isEmpty()) {
result += ExternalUpdate(siteResult, source)
}
}
catch (e: Exception) {
LOG.warn(e)
showErrorMessage(manualCheck, IdeBundle.message("updates.external.error.message", source.name, e.message ?: "internal error"))
}
}
}
return result
}
@Throws(IOException::class)
@JvmStatic
fun checkAndPrepareToInstall(downloader: PluginDownloader,
state: InstalledPluginsState,
toUpdate: MutableMap<PluginId, PluginDownloader>,
incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?,
indicator: ProgressIndicator?) {
@Suppress("NAME_SHADOWING")
var downloader = downloader
val pluginId = downloader.pluginId
if (PluginManagerCore.getDisabledPlugins().contains(pluginId)) return
val pluginVersion = downloader.pluginVersion
val installedPlugin = PluginManager.getPlugin(PluginId.getId(pluginId))
if (installedPlugin == null || pluginVersion == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(installedPlugin, pluginVersion) > 0) {
var descriptor: IdeaPluginDescriptor?
val oldDownloader = ourUpdatedPlugins[pluginId]
if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) {
descriptor = downloader.descriptor
if (descriptor is PluginNode && descriptor.isIncomplete) {
if (downloader.prepareToInstall(indicator ?: EmptyProgressIndicator())) {
descriptor = downloader.descriptor
}
ourUpdatedPlugins[pluginId] = downloader
}
}
else {
downloader = oldDownloader
descriptor = oldDownloader.descriptor
}
if (PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) {
toUpdate[PluginId.getId(pluginId)] = downloader
}
}
// collect plugins which were not updated and would be incompatible with new version
if (incompatiblePlugins != null && installedPlugin != null && installedPlugin.isEnabled &&
!toUpdate.containsKey(installedPlugin.pluginId) &&
!PluginManagerCore.isCompatible(installedPlugin, downloader.buildNumber)) {
incompatiblePlugins += installedPlugin
}
}
private fun showErrorMessage(showDialog: Boolean, message: String) {
LOG.info(message)
if (showDialog) {
UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(message, IdeBundle.message("updates.error.connection.title")) }
}
}
private fun showUpdateResult(project: Project?,
checkForUpdateResult: CheckForUpdateResult,
updateSettings: UpdateSettings,
updatedPlugins: Collection<PluginDownloader>?,
incompatiblePlugins: Collection<IdeaPluginDescriptor>?,
externalUpdates: Collection<ExternalUpdate>?,
enableLink: Boolean,
alwaysShowResults: Boolean) {
val updatedChannel = checkForUpdateResult.updatedChannel
val newBuild = checkForUpdateResult.newBuild
if (updatedChannel != null && newBuild != null) {
val runnable = {
val patches = checkForUpdateResult.patches
val forceHttps = updateSettings.canUseSecureConnection()
UpdateInfoDialog(updatedChannel, newBuild, patches, enableLink, forceHttps, updatedPlugins, incompatiblePlugins).show()
}
ourShownNotifications.remove(NotificationUniqueType.PLATFORM)?.forEach { it.expire() }
if (alwaysShowResults) {
runnable.invoke()
}
else {
FUSApplicationUsageTrigger.getInstance().trigger(IdeUpdateUsageTriggerCollector::class.java, "notification.shown")
val message = IdeBundle.message("updates.ready.message", ApplicationNamesInfo.getInstance().fullProductName)
showNotification(project, message, {
FUSApplicationUsageTrigger.getInstance().trigger(IdeUpdateUsageTriggerCollector::class.java, "notification.clicked")
runnable()
}, NotificationUniqueType.PLATFORM)
}
return
}
var updateFound = false
if (updatedPlugins != null && !updatedPlugins.isEmpty()) {
updateFound = true
val runnable = { PluginUpdateInfoDialog(updatedPlugins, enableLink).show() }
ourShownNotifications.remove(NotificationUniqueType.PLUGINS)?.forEach { it.expire() }
if (alwaysShowResults) {
runnable.invoke()
}
else {
val plugins = updatedPlugins.joinToString { downloader -> downloader.pluginName }
val message = IdeBundle.message("updates.plugins.ready.message", updatedPlugins.size, plugins)
showNotification(project, message, runnable, NotificationUniqueType.PLUGINS)
}
}
if (externalUpdates != null && !externalUpdates.isEmpty()) {
updateFound = true
ourShownNotifications.remove(NotificationUniqueType.EXTERNAL)?.forEach { it.expire() }
for (update in externalUpdates) {
val runnable = { update.source.installUpdates(update.components) }
if (alwaysShowResults) {
runnable.invoke()
}
else {
val updates = update.components.joinToString(", ")
val message = IdeBundle.message("updates.external.ready.message", update.components.size, updates)
showNotification(project, message, runnable, NotificationUniqueType.EXTERNAL)
}
}
}
if (!updateFound && alwaysShowResults) {
NoUpdatesDialog(enableLink).show()
}
}
private fun showNotification(project: Project?, message: String, action: () -> Unit, notificationType: NotificationUniqueType) {
val listener = NotificationListener { notification, _ ->
notification.expire()
action.invoke()
}
val title = IdeBundle.message("update.notifications.title")
val notification = NOTIFICATIONS.createNotification(title, XmlStringUtil.wrapInHtml(message), NotificationType.INFORMATION, listener)
notification.whenExpired { ourShownNotifications.remove(notificationType, notification) }
notification.notify(project)
ourShownNotifications.putValue(notificationType, notification)
}
@JvmStatic
fun addUpdateRequestParameter(name: String, value: String) {
ourAdditionalRequestOptions[name] = value
}
private fun prepareUpdateCheckArgs(url: Url, packageManagerName: String?): Url {
addUpdateRequestParameter("build", ApplicationInfo.getInstance().build.asString())
addUpdateRequestParameter("uid", PermanentInstallationID.get())
addUpdateRequestParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION)
if (packageManagerName != null) {
addUpdateRequestParameter("manager", packageManagerName)
}
if (ApplicationInfoEx.getInstanceEx().isEAP) {
addUpdateRequestParameter("eap", "")
}
return url.addParameters(ourAdditionalRequestOptions)
}
@Deprecated("Replaced", ReplaceWith("PermanentInstallationID.get()", "com.intellij.openapi.application.PermanentInstallationID"))
@JvmStatic
@Suppress("unused", "UNUSED_PARAMETER")
fun getInstallationUID(c: PropertiesComponent): String = PermanentInstallationID.get()
@JvmStatic
val disabledToUpdatePlugins: Set<String>
get() {
if (ourDisabledToUpdatePlugins == null) {
ourDisabledToUpdatePlugins = TreeSet()
if (!ApplicationManager.getApplication().isUnitTestMode) {
try {
val file = File(PathManager.getConfigPath(), DISABLED_UPDATE)
if (file.isFile) {
FileUtil.loadFile(file)
.split("[\\s]".toRegex())
.map { it.trim() }
.filterTo(ourDisabledToUpdatePlugins!!) { it.isNotEmpty() }
}
}
catch (e: IOException) {
LOG.error(e)
}
}
}
return ourDisabledToUpdatePlugins!!
}
@JvmStatic
fun saveDisabledToUpdatePlugins() {
val plugins = File(PathManager.getConfigPath(), DISABLED_UPDATE)
try {
PluginManagerCore.savePluginsList(disabledToUpdatePlugins, false, plugins)
}
catch (e: IOException) {
LOG.error(e)
}
}
private var ourHasFailedPlugins = false
@JvmStatic
fun checkForUpdate(event: IdeaLoggingEvent) {
if (!ourHasFailedPlugins) {
val app = ApplicationManager.getApplication()
if (app != null && !app.isDisposed && !app.isDisposeInProgress && UpdateSettings.getInstance().isCheckNeeded) {
val pluginDescriptor = PluginManager.getPlugin(IdeErrorsDialog.findPluginId(event.throwable))
if (pluginDescriptor != null && !pluginDescriptor.isBundled) {
ourHasFailedPlugins = true
updateAndShowResult()
}
}
}
}
/** A helper method for manually testing platform updates (see [com.intellij.internal.ShowUpdateInfoDialogAction]). */
fun testPlatformUpdate(updateInfoText: String, patchFilePath: String?, forceUpdate: Boolean) {
if (!ApplicationManager.getApplication().isInternal) {
throw IllegalStateException()
}
val channel: UpdateChannel?
val newBuild: BuildInfo?
val patches: UpdateChain?
if (forceUpdate) {
val node = loadElement(updateInfoText).getChild("product")?.getChild("channel") ?: throw IllegalArgumentException("//channel missing")
channel = UpdateChannel(node)
newBuild = channel.builds.firstOrNull() ?: throw IllegalArgumentException("//build missing")
patches = newBuild.patches.firstOrNull()?.let { UpdateChain(listOf(it.fromBuild, newBuild.number), it.size) }
}
else {
val updateInfo = UpdatesInfo(loadElement(updateInfoText))
val strategy = UpdateStrategy(ApplicationInfo.getInstance().build, updateInfo)
val checkForUpdateResult = strategy.checkForUpdates()
channel = checkForUpdateResult.updatedChannel
newBuild = checkForUpdateResult.newBuild
patches = checkForUpdateResult.patches
}
if (channel != null && newBuild != null) {
val patchFile = if (patchFilePath != null) File(FileUtil.toSystemDependentName(patchFilePath)) else null
UpdateInfoDialog(channel, newBuild, patches, patchFile).show()
}
else {
NoUpdatesDialog(true).show()
}
}
} | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt | 4138112211 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet")
package com.intellij.openapi.keymap.impl
import com.intellij.configurationStore.LazySchemeProcessor
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.ide.IdeBundle
import com.intellij.ide.WelcomeWizardUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ConfigImportHelper
import com.intellij.openapi.components.*
import com.intellij.openapi.editor.actions.CtrlYActionChooser
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.keymap.ex.KeymapManagerEx
import com.intellij.openapi.options.SchemeManager
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.text.NaturalComparator
import com.intellij.ui.AppUIUtil
import com.intellij.util.ResourceUtil
import com.intellij.util.containers.ContainerUtil
import org.jdom.Element
import java.util.function.Function
import java.util.function.Predicate
const val KEYMAPS_DIR_PATH = "keymaps"
private const val ACTIVE_KEYMAP = "active_keymap"
private const val NAME_ATTRIBUTE = "name"
@State(name = "KeymapManager", storages = [(Storage(value = "keymap.xml", roamingType = RoamingType.PER_OS))],
additionalExportDirectory = KEYMAPS_DIR_PATH,
category = SettingsCategory.KEYMAP)
class KeymapManagerImpl : KeymapManagerEx(), PersistentStateComponent<Element> {
private val listeners = ContainerUtil.createLockFreeCopyOnWriteList<KeymapManagerListener>()
private val boundShortcuts = HashMap<String, String>()
private val schemeManager: SchemeManager<Keymap>
companion object {
@JvmStatic
var isKeymapManagerInitialized = false
private set
}
init {
schemeManager = SchemeManagerFactory.getInstance().create(KEYMAPS_DIR_PATH, object : LazySchemeProcessor<Keymap, KeymapImpl>() {
override fun createScheme(dataHolder: SchemeDataHolder<KeymapImpl>,
name: String,
attributeProvider: Function<in String, String?>,
isBundled: Boolean) = KeymapImpl(name, dataHolder)
override fun onCurrentSchemeSwitched(oldScheme: Keymap?,
newScheme: Keymap?,
processChangeSynchronously: Boolean) {
fireActiveKeymapChanged(newScheme, activeKeymap)
}
override fun reloaded(schemeManager: SchemeManager<Keymap>, schemes: Collection<Keymap>) {
if (schemeManager.activeScheme == null) {
// listeners expect that event will be fired in EDT
AppUIUtil.invokeOnEdt {
schemeManager.setCurrentSchemeName(DefaultKeymap.getInstance().defaultKeymapName, true)
}
}
}
})
val defaultKeymapManager = DefaultKeymap.getInstance()
val systemDefaultKeymap = WelcomeWizardUtil.getWizardMacKeymap() ?: defaultKeymapManager.defaultKeymapName
for (keymap in defaultKeymapManager.keymaps) {
schemeManager.addScheme(keymap)
if (keymap.name == systemDefaultKeymap) {
schemeManager.setCurrent(keymap, notify = false)
}
}
schemeManager.loadSchemes()
isKeymapManagerInitialized = true
if (ConfigImportHelper.isNewUser()) {
CtrlYActionChooser.askAboutShortcut()
}
fun removeKeymap(keymapName: String) {
val isCurrent = schemeManager.activeScheme?.name.equals(keymapName)
val keymap = schemeManager.removeScheme(keymapName)
if (keymap != null) {
fireKeymapRemoved(keymap)
}
DefaultKeymap.getInstance().removeKeymap(keymapName)
if (isCurrent) {
val activeKeymap = schemeManager.activeScheme
?: schemeManager.findSchemeByName(DefaultKeymap.getInstance().defaultKeymapName)
?: schemeManager.findSchemeByName(KeymapManager.DEFAULT_IDEA_KEYMAP)
schemeManager.setCurrent(activeKeymap, notify = true, processChangeSynchronously = true)
fireActiveKeymapChanged(activeKeymap, activeKeymap)
}
}
BundledKeymapBean.EP_NAME.addExtensionPointListener(object : ExtensionPointListener<BundledKeymapBean> {
override fun extensionAdded(ep: BundledKeymapBean, pluginDescriptor: PluginDescriptor) {
val keymapName = getKeymapName(ep)
//if (!SystemInfo.isMac &&
// keymapName != KeymapManager.MAC_OS_X_KEYMAP &&
// keymapName != KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP &&
// DefaultKeymap.isBundledKeymapHidden(keymapName) &&
// schemeManager.findSchemeByName(KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP) == null) return
val keymap = DefaultKeymap.getInstance().loadKeymap(keymapName, object : SchemeDataHolder<KeymapImpl> {
override fun read(): Element {
return JDOMUtil.load(ResourceUtil.getResourceAsBytes(getEffectiveFile(ep), pluginDescriptor.classLoader, true))
}
}, pluginDescriptor)
schemeManager.addScheme(keymap)
fireKeymapAdded(keymap)
// do no set current keymap here, consider: multi-keymap plugins, parent keymaps loading
}
override fun extensionRemoved(ep: BundledKeymapBean, pluginDescriptor: PluginDescriptor) {
removeKeymap(getKeymapName(ep))
}
}, null)
}
private fun fireKeymapAdded(keymap: Keymap) {
ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).keymapAdded(keymap)
for (listener in listeners) {
listener.keymapAdded(keymap)
}
}
private fun fireKeymapRemoved(keymap: Keymap) {
ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).keymapRemoved(keymap)
for (listener in listeners) {
listener.keymapRemoved(keymap)
}
}
private fun fireActiveKeymapChanged(newScheme: Keymap?, activeKeymap: Keymap?) {
ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).activeKeymapChanged(activeKeymap)
for (listener in listeners) {
listener.activeKeymapChanged(newScheme)
}
}
override fun getAllKeymaps(): Array<Keymap> = getKeymaps(null).toTypedArray()
fun getKeymaps(additionalFilter: Predicate<Keymap>?): List<Keymap> {
return schemeManager.allSchemes.filter { !it.presentableName.startsWith("$") && (additionalFilter == null || additionalFilter.test(it)) }
}
override fun getKeymap(name: String): Keymap? = schemeManager.findSchemeByName(name)
override fun getActiveKeymap(): Keymap {
return schemeManager.activeScheme
?: schemeManager.findSchemeByName(DefaultKeymap.getInstance().defaultKeymapName)
?: schemeManager.findSchemeByName(KeymapManager.DEFAULT_IDEA_KEYMAP)!!
}
override fun setActiveKeymap(keymap: Keymap) {
schemeManager.setCurrent(keymap)
}
override fun bindShortcuts(sourceActionId: String, targetActionId: String) {
boundShortcuts.put(targetActionId, sourceActionId)
}
override fun unbindShortcuts(targetActionId: String) {
boundShortcuts.remove(targetActionId)
}
override fun getBoundActions(): MutableSet<String> = boundShortcuts.keys
override fun getActionBinding(actionId: String): String? {
var visited: MutableSet<String>? = null
var id = actionId
while (true) {
val next = boundShortcuts.get(id) ?: break
if (visited == null) {
visited = HashSet()
}
id = next
if (!visited.add(id)) {
break
}
}
return if (id == actionId) null else id
}
override fun getSchemeManager(): SchemeManager<Keymap> = schemeManager
fun setKeymaps(keymaps: List<Keymap>, active: Keymap?, removeCondition: Predicate<Keymap>?) {
schemeManager.setSchemes(keymaps, active, removeCondition)
fireActiveKeymapChanged(active, activeKeymap)
}
override fun getState(): Element {
val result = Element("state")
schemeManager.activeScheme?.let {
if (it.name != DefaultKeymap.getInstance().defaultKeymapName) {
val e = Element(ACTIVE_KEYMAP)
e.setAttribute(NAME_ATTRIBUTE, it.name)
result.addContent(e)
}
}
return result
}
override fun loadState(state: Element) {
val child = state.getChild(ACTIVE_KEYMAP)
val activeKeymapName = child?.getAttributeValue(NAME_ATTRIBUTE)
if (!activeKeymapName.isNullOrBlank()) {
schemeManager.currentSchemeName = activeKeymapName
if (schemeManager.currentSchemeName != activeKeymapName) {
notifyAboutMissingKeymap(activeKeymapName, IdeBundle.message("notification.content.cannot.find.keymap", activeKeymapName), false)
}
}
}
@Suppress("OverridingDeprecatedMember")
override fun addKeymapManagerListener(listener: KeymapManagerListener, parentDisposable: Disposable) {
pollQueue()
ApplicationManager.getApplication().messageBus.connect(parentDisposable).subscribe(KeymapManagerListener.TOPIC, listener)
}
private fun pollQueue() {
listeners.removeAll { it is WeakKeymapManagerListener && it.isDead }
}
@Suppress("OverridingDeprecatedMember")
override fun removeKeymapManagerListener(listener: KeymapManagerListener) {
pollQueue()
listeners.remove(listener)
}
override fun addWeakListener(listener: KeymapManagerListener) {
pollQueue()
listeners.add(WeakKeymapManagerListener(this, listener))
}
override fun removeWeakListener(listenerToRemove: KeymapManagerListener) {
listeners.removeAll { it is WeakKeymapManagerListener && it.isWrapped(listenerToRemove) }
}
}
internal val keymapComparator: Comparator<Keymap?> by lazy {
val defaultKeymapName = DefaultKeymap.getInstance().defaultKeymapName
Comparator { keymap1, keymap2 ->
if (keymap1 === keymap2) return@Comparator 0
if (keymap1 == null) return@Comparator - 1
if (keymap2 == null) return@Comparator 1
val parent1 = (if (!keymap1.canModify()) null else keymap1.parent) ?: keymap1
val parent2 = (if (!keymap2.canModify()) null else keymap2.parent) ?: keymap2
if (parent1 === parent2) {
when {
!keymap1.canModify() -> - 1
!keymap2.canModify() -> 1
else -> compareByName(keymap1, keymap2, defaultKeymapName)
}
}
else {
compareByName(parent1, parent2, defaultKeymapName)
}
}
}
private fun compareByName(keymap1: Keymap, keymap2: Keymap, defaultKeymapName: String): Int {
return when (defaultKeymapName) {
keymap1.name -> -1
keymap2.name -> 1
else -> NaturalComparator.INSTANCE.compare(keymap1.presentableName, keymap2.presentableName)
}
} | platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.kt | 2907313039 |
package tripleklay.game.trans
import klay.core.Platform
import tripleklay.game.ScreenStack.Screen
/**
* Fades the new screen in front of the old one.
*/
class FadeTransition : InterpedTransition<SlideTransition>() {
override fun init(plat: Platform, oscreen: Screen, nscreen: Screen) {
super.init(plat, oscreen, nscreen)
nscreen.layer.setAlpha(0f)
}
override fun update(oscreen: Screen, nscreen: Screen, elapsed: Float): Boolean {
val nalpha = _interp.applyClamp(0f, 1f, elapsed, _duration)
nscreen.layer.setAlpha(nalpha)
return elapsed >= _duration
}
override fun complete(oscreen: Screen, nscreen: Screen) {
super.complete(oscreen, nscreen)
nscreen.layer.setAlpha(1f)
}
}
| tripleklay/src/main/kotlin/tripleklay/game/trans/FadeTransition.kt | 1849063913 |
package source
open class MyClass {
val foo: Int = 1
}
object MyObj: MyClass()
fun <caret>test() {
MyObj.foo
} | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/misc/fakeOverrideInObject/before/source/Foo.kt | 1767306888 |
fun test() {
return 0
}
// SEARCH_TEXT: flushBuffer
// CHECK_BOX
// REF: of java.io.BufferedOutputStream.flushBuffer()
// REF: of java.io.BufferedWriter.flushBuffer()
// REF: of java.io.OutputStreamWriter.flushBuffer()
| plugins/kotlin/idea/tests/testData/navigation/gotoSymbol/javaMethods.kt | 3032242622 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package vulkan.templates
import org.lwjgl.generator.*
import vulkan.*
val EXT_depth_range_unrestricted = "EXTDepthRangeUnrestricted".nativeClassVK("EXT_depth_range_unrestricted", type = "device", postfix = "EXT") {
documentation =
"""
This extension removes the ##VkViewport {@code minDepth} and {@code maxDepth} restrictions that the values must be between {@code 0.0} and {@code 1.0}, inclusive. It also removes the same restriction on ##VkPipelineDepthStencilStateCreateInfo {@code minDepthBounds} and {@code maxDepthBounds}. Finally it removes the restriction on the {@code depth} value in ##VkClearDepthStencilValue.
<h5>VK_EXT_depth_range_unrestricted</h5>
<dl>
<dt><b>Name String</b></dt>
<dd>{@code VK_EXT_depth_range_unrestricted}</dd>
<dt><b>Extension Type</b></dt>
<dd>Device extension</dd>
<dt><b>Registered Extension Number</b></dt>
<dd>14</dd>
<dt><b>Revision</b></dt>
<dd>1</dd>
<dt><b>Extension and Version Dependencies</b></dt>
<dd><ul>
<li>Requires support for Vulkan 1.0</li>
</ul></dd>
<dt><b>Contact</b></dt>
<dd><ul>
<li>Piers Daniell <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_depth_range_unrestricted]%20@pdaniell-nv%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_depth_range_unrestricted%20extension%3E%3E">pdaniell-nv</a></li>
</ul></dd>
</dl>
<h5>Other Extension Metadata</h5>
<dl>
<dt><b>Last Modified Date</b></dt>
<dd>2017-06-22</dd>
<dt><b>Contributors</b></dt>
<dd><ul>
<li>Daniel Koch, NVIDIA</li>
<li>Jeff Bolz, NVIDIA</li>
</ul></dd>
</dl>
"""
IntConstant(
"The extension specification version.",
"EXT_DEPTH_RANGE_UNRESTRICTED_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME".."VK_EXT_depth_range_unrestricted"
)
} | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/EXT_depth_range_unrestricted.kt | 2877460108 |
package com.github.spoptchev.kotlin.preconditions
import com.github.spoptchev.kotlin.preconditions.matcher.*
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.fail
class PreconditionDSLTest {
@Test(expected = IllegalStateException::class)
fun `test invalid check`() {
checkThat("hello") { matches("olleh") }
fail("should not be executed")
}
@Test(expected = IllegalArgumentException::class)
fun `test invalid require`() {
requireThat(1) { isLt(0) }
fail("should not be executed")
}
@Test
fun `test check invalid with label`() {
try {
checkThat("x", "ID") { not(isEqualTo("x")) }
fail("should not be executed")
} catch (e: IllegalStateException) {
assertEquals("expected ID x not to be equal to 'x'", e.message)
}
}
@Test
fun `test labeled valid evaluation`() {
checkThat("y", "Should") { isEqualTo("y") }
}
@Test
fun `test shouldNotBe`() {
try {
requireThat(1) { isGt(0) }
} catch (e: IllegalArgumentException) {
assertEquals("expected 1 not to be > 0", e.message)
}
}
@Test
fun `test result value`() {
val result: Int = requireThat(1) { isGt(0) }
assertEquals(result, 1)
}
@Test
fun `test integration of all collection preconditions`() {
val list = listOf(1, 2)
requireThat(list) { hasSize(2) }
requireThat(list) { contains(1) or contains(3) and not(hasSize(3)) }
requireThat(list) { containsAll(1, 2) }
requireThat(list) { containsAll(list) }
requireThat(list) { isSorted() }
requireThat(list) { not(isEmpty()) }
}
@Test
fun `test integration of all comparable preconditions`() {
requireThat(1) { isLt(2) }
requireThat(1) { isLte(1) }
requireThat(1) { isGt(0) }
requireThat(1) { isGte(1) }
requireThat(1) { isBetween(0..2) }
}
@Test
fun `test integration of all map preconditions`() {
val map = mapOf(1 to "1")
requireThat(map) { hasKey(1) }
requireThat(map) { hasValue("1") }
requireThat(map) { contains(1, "1") }
}
@Test
fun `test integration of all string preconditions`() {
val value = "hello"
requireThat(value) { startsWith("he") and hasLength(5) and not(includes("io")) }
requireThat(value) { includes("ll") }
requireThat(value) { matches("hello") }
requireThat(value) { endsWith("lo") }
requireThat(value) { hasLength(5) }
requireThat(value) { not(isBlank()) }
requireThat(value) { not(isEmpty()) }
requireThat(value) { hasLengthBetween(1, 5) }
}
@Test
fun `test integration of all object preconditions`() {
val result = Result(true) { "" }
requireThat(result) { not(isNull()) }
requireThat(result) { isEqualTo(result) }
requireThat(result) { isSameInstanceAs(result) }
}
@Test
fun `test nested preconditions`() {
requireThat("hello") {
not(isNull()) and {
hasLength(6) or {
startsWith("he") and endsWith("llo")
}
}
}
}
}
| src/test/kotlin/com/github/spoptchev/kotlin/preconditions/PreconditionDSLTest.kt | 3911185871 |
package org.amshove.kluent.tests.assertions.file
import org.amshove.kluent.shouldNotBeDir
import org.junit.Before
import org.junit.Test
import java.io.File
import kotlin.test.assertFails
class ShouldNotBeDirShould {
lateinit var dir: File
lateinit var file: File
@Before
fun setup() {
dir = File("testDir")
file = File("test")
}
@Test
fun passWhenTestingAFile() {
dir.useFile { it.shouldNotBeDir() }
}
@Test
fun failWhenTestingADir() {
file.useDir { assertFails { it.shouldNotBeDir() } }
}
}
| jvm/src/test/kotlin/org/amshove/kluent/tests/assertions/file/ShouldNotBeDirShould.kt | 3475385602 |
package co.smartreceipts.android.tooltip.model
/**
* Defines the different tooltip display styles that are available to us
*/
enum class TooltipDisplayStyle {
/**
* Indicates that this tooltip is displaying an informational message to the end user
*/
Informational,
/**
* Indicates that this tooltip is asking an explicit question of this end user. This type
* differs from [Informational] in that it can multiple distinct actions (e.g. Yes, No).
*/
Question,
/**
* Indicates that this tooltip is displaying an error message to the end user
*/
Error,
} | app/src/main/java/co/smartreceipts/android/tooltip/model/TooltipDisplayStyle.kt | 1358066565 |
fun box(): String {
if ((((Boolean::not)!!)!!)(false) != true)({})
} | kotlin/kotlin-formal/examples/fuzzer/booleanNotIntrinsic.kt1942524773.kt_minimized.kt | 1362310690 |
package de.ph1b.audiobook.features.folderOverview
import de.ph1b.audiobook.common.comparator.NaturalOrderComparator
import java.io.File
data class FolderModel(val folder: String, val isCollection: Boolean) : Comparable<FolderModel> {
override fun compareTo(other: FolderModel): Int {
val isCollectionCompare = other.isCollection.compareTo(isCollection)
if (isCollectionCompare != 0) return isCollectionCompare
return NaturalOrderComparator.fileComparator.compare(File(folder), File(other.folder))
}
}
| app/src/main/java/de/ph1b/audiobook/features/folderOverview/FolderModel.kt | 95269896 |
package com.example.avjindersinghsekhon.minimaltodo
import android.content.res.Resources
/**
* Created by avjindersinghsekhon on 9/21/15.
*/
class PreferenceKeys(resources: Resources) {
@JvmField
val night_mode_pref_key: String = resources.getString(R.string.night_mode_pref_key)
}
| app/src/main/java/com/example/avjindersinghsekhon/minimaltodo/PreferenceKeys.kt | 2116980378 |
/*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.util
import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository
import com.intellij.openapi.application.EDT
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.ProgressManagerImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.UserDataHolder
import com.intellij.psi.PsiFile
import com.intellij.util.flow.throttle
import com.jetbrains.packagesearch.intellij.plugin.extensibility.AsyncModuleTransformer
import com.jetbrains.packagesearch.intellij.plugin.extensibility.AsyncProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineModuleTransformer
import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyOperationMetadata
import com.jetbrains.packagesearch.intellij.plugin.extensibility.FlowModuleChangesSignalProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ModuleChangesSignalProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ModuleTransformer
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleType
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ProducerScope
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.future.await
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import org.jetbrains.annotations.Nls
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
import kotlin.time.Duration
import kotlin.time.TimedValue
import kotlin.time.measureTimedValue
internal fun <T> Flow<T>.onEach(context: CoroutineContext, action: suspend (T) -> Unit) =
onEach { withContext(context) { action(it) } }
internal fun <T, R> Flow<T>.map(context: CoroutineContext, action: suspend (T) -> R) =
map { withContext(context) { action(it) } }
internal fun <T> Flow<T>.replayOnSignals(vararg signals: Flow<Any>) = channelFlow {
var lastValue: T? = null
onEach { send(it) }
.onEach { lastValue = it }
.launchIn(this)
merge(*signals)
.onEach { lastValue?.let { send(it) } }
.launchIn(this)
}
suspend fun <T, R> Iterable<T>.parallelMap(transform: suspend CoroutineScope.(T) -> R) = coroutineScope {
map { async { transform(it) } }.awaitAll()
}
internal suspend fun <T> Iterable<T>.parallelFilterNot(transform: suspend (T) -> Boolean) =
channelFlow { parallelForEach { if (!transform(it)) send(it) } }.toList()
internal suspend fun <T, R> Iterable<T>.parallelMapNotNull(transform: suspend (T) -> R?) =
channelFlow { parallelForEach { transform(it)?.let { send(it) } } }.toList()
internal suspend fun <T> Iterable<T>.parallelForEach(action: suspend CoroutineScope.(T) -> Unit) = coroutineScope {
forEach { launch { action(it) } }
}
internal suspend fun <T, R, K> Map<T, R>.parallelMap(transform: suspend (Map.Entry<T, R>) -> K) = coroutineScope {
map { async { transform(it) } }.awaitAll()
}
internal suspend fun <T, R> Iterable<T>.parallelFlatMap(transform: suspend (T) -> Iterable<R>) = coroutineScope {
map { async { transform(it) } }.flatMap { it.await() }
}
internal suspend inline fun <K, V> Map<K, V>.parallelUpdatedKeys(keys: Iterable<K>, crossinline action: suspend (K) -> V): Map<K, V> {
val map = toMutableMap()
keys.parallelForEach { map[it] = action(it) }
return map
}
internal fun timer(each: Duration, emitAtStartup: Boolean = true) = flow {
if (emitAtStartup) emit(Unit)
while (true) {
delay(each)
emit(Unit)
}
}
internal fun <T> Flow<T>.throttle(time: Duration) =
throttle(time.inWholeMilliseconds)
internal inline fun <reified T, reified R> Flow<T>.modifiedBy(
modifierFlow: Flow<R>,
crossinline transform: suspend (T, R) -> T
): Flow<T> = flow {
coroutineScope {
val queue = Channel<Any?>(capacity = 1)
val mutex = Mutex(locked = true)
[email protected] {
queue.send(it)
if (mutex.isLocked) mutex.unlock()
}.launchIn(this)
mutex.lock()
modifierFlow.onEach { queue.send(it) }.launchIn(this)
var currentState: T = queue.receive() as T
emit(currentState)
for (e in queue) {
when (e) {
is T -> currentState = e
is R -> currentState = transform(currentState, e)
else -> continue
}
emit(currentState)
}
}
}
internal fun <T, R> Flow<T>.mapLatestTimedWithLoading(
loggingContext: String,
loadingFlow: MutableStateFlow<Boolean>? = null,
transform: suspend CoroutineScope.(T) -> R
) =
mapLatest {
measureTimedValue {
loadingFlow?.emit(true)
val result = try {
coroutineScope { transform(it) }
} finally {
loadingFlow?.emit(false)
}
result
}
}.map {
logDebug(loggingContext) { "Took ${it.duration.absoluteValue} to process" }
it.value
}
internal fun <T> Flow<T>.catchAndLog(context: String, message: String? = null) =
catch {
if (message != null) {
logDebug(context, it) { message }
} else logDebug(context, it)
}
internal suspend inline fun <R> MutableStateFlow<Boolean>.whileLoading(action: () -> R): TimedValue<R> {
emit(true)
val r = measureTimedValue { action() }
emit(false)
return r
}
internal inline fun <reified T> Flow<T>.batchAtIntervals(duration: Duration) = channelFlow {
val mutex = Mutex()
val buffer = mutableListOf<T>()
var job: Job? = null
collect {
mutex.withLock { buffer.add(it) }
if (job == null || job?.isCompleted == true) {
job = launch {
delay(duration)
mutex.withLock {
send(buffer.toTypedArray())
buffer.clear()
}
}
}
}
}
internal suspend fun showBackgroundLoadingBar(
project: Project,
@Nls title: String,
@Nls upperMessage: String,
cancellable: Boolean = false,
isSafe: Boolean = true
): BackgroundLoadingBarController {
val syncSignal = Mutex(true)
val externalScopeJob = coroutineContext.job
val progressManager = ProgressManager.getInstance()
val progressController = BackgroundLoadingBarController(syncSignal)
progressManager.run(object : Task.Backgroundable(project, title, cancellable) {
override fun run(indicator: ProgressIndicator) {
if (isSafe && progressManager is ProgressManagerImpl && indicator is UserDataHolder) {
progressManager.markProgressSafe(indicator)
}
indicator.text = upperMessage // ??? why does it work?
runBlocking {
indicator.text = upperMessage // ??? why does it work?
val indicatorCancelledPollingJob = launch {
while (true) {
if (indicator.isCanceled) break
delay(50)
}
}
val internalJob = launch {
syncSignal.lock()
}
select {
internalJob.onJoin { }
externalScopeJob.onJoin {
internalJob.cancel()
indicatorCancelledPollingJob.cancel()
}
indicatorCancelledPollingJob.onJoin {
syncSignal.unlock()
progressController.triggerCallbacks()
}
}
indicatorCancelledPollingJob.cancel()
}
}
})
return progressController
}
internal class BackgroundLoadingBarController(private val syncMutex: Mutex) {
private val callbacks = mutableSetOf<() -> Unit>()
fun addOnComputationInterruptedCallback(callback: () -> Unit) {
callbacks.add(callback)
}
internal fun triggerCallbacks() = callbacks.forEach { it.invoke() }
fun clear() {
runCatching { syncMutex.unlock() }
}
}
suspend fun <R> writeAction(action: () -> R): R = withContext(Dispatchers.EDT) { action() }
internal fun ModuleTransformer.asCoroutine() = object : CoroutineModuleTransformer {
override suspend fun transformModules(project: Project, nativeModules: List<Module>): List<ProjectModule> =
[email protected](project, nativeModules)
}
internal fun AsyncModuleTransformer.asCoroutine() = object : CoroutineModuleTransformer {
override suspend fun transformModules(project: Project, nativeModules: List<Module>): List<ProjectModule> =
[email protected](project, nativeModules).await()
}
internal fun ModuleChangesSignalProvider.asCoroutine() = object : FlowModuleChangesSignalProvider {
override fun registerModuleChangesListener(project: Project) = callbackFlow {
val sub = registerModuleChangesListener(project) { trySend() }
awaitClose { sub.unsubscribe() }
}
}
internal fun ProjectModuleOperationProvider.asCoroutine() = object : CoroutineProjectModuleOperationProvider {
override fun hasSupportFor(project: Project, psiFile: PsiFile?) = [email protected](project, psiFile)
override fun hasSupportFor(projectModuleType: ProjectModuleType) = [email protected](projectModuleType)
override suspend fun addDependencyToModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).toList()
override suspend fun removeDependencyFromModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).toList()
override suspend fun updateDependencyInModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).toList()
override suspend fun declaredDependenciesInModule(module: ProjectModule) =
[email protected](module).toList()
override suspend fun resolvedDependenciesInModule(module: ProjectModule, scopes: Set<String>) =
[email protected](module, scopes).toList()
override suspend fun addRepositoryToModule(repository: UnifiedDependencyRepository, module: ProjectModule) =
[email protected](repository, module).toList()
override suspend fun removeRepositoryFromModule(repository: UnifiedDependencyRepository, module: ProjectModule) =
[email protected](repository, module).toList()
override suspend fun listRepositoriesInModule(module: ProjectModule) =
[email protected](module).toList()
}
internal fun AsyncProjectModuleOperationProvider.asCoroutine() = object : CoroutineProjectModuleOperationProvider {
override fun hasSupportFor(project: Project, psiFile: PsiFile?) = [email protected](project, psiFile)
override fun hasSupportFor(projectModuleType: ProjectModuleType) = [email protected](projectModuleType)
override suspend fun addDependencyToModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).await().toList()
override suspend fun removeDependencyFromModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).await().toList()
override suspend fun updateDependencyInModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).await().toList()
override suspend fun declaredDependenciesInModule(module: ProjectModule) =
[email protected](module).await().toList()
override suspend fun resolvedDependenciesInModule(module: ProjectModule, scopes: Set<String>) =
[email protected](module, scopes).await().toList()
override suspend fun addRepositoryToModule(repository: UnifiedDependencyRepository, module: ProjectModule) =
[email protected](repository, module).await().toList()
override suspend fun removeRepositoryFromModule(repository: UnifiedDependencyRepository, module: ProjectModule) =
[email protected](repository, module).await().toList()
override suspend fun listRepositoriesInModule(module: ProjectModule) =
[email protected](module).await().toList()
}
fun SendChannel<Unit>.trySend() = trySend(Unit)
fun ProducerScope<Unit>.trySend() = trySend(Unit)
suspend fun SendChannel<Unit>.send() = send(Unit)
suspend fun ProducerScope<Unit>.send() = send(Unit)
data class CombineLatest3<A, B, C>(val a: A, val b: B, val c: C)
fun <A, B, C, Z> combineLatest(
flowA: Flow<A>,
flowB: Flow<B>,
flowC: Flow<C>,
transform: suspend (CombineLatest3<A, B, C>) -> Z
) = combine(flowA, flowB, flowC) { a, b, c -> CombineLatest3(a, b, c) }
.mapLatest(transform)
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/CoroutinesUtils.kt | 987772534 |
package au.com.dius.pact.model.generators
import au.com.dius.pact.model.PactSpecVersion
import com.mifmif.common.regex.Generex
import mu.KotlinLogging
import org.apache.commons.lang3.RandomStringUtils
import org.apache.commons.lang3.RandomUtils
import java.math.BigDecimal
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.OffsetDateTime
import java.time.OffsetTime
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.UUID
import java.util.concurrent.ThreadLocalRandom
import kotlin.reflect.full.companionObject
import kotlin.reflect.full.companionObjectInstance
import kotlin.reflect.full.declaredMemberFunctions
private val logger = KotlinLogging.logger {}
fun lookupGenerator(generatorMap: Map<String, Any>): Generator? {
var generator: Generator? = null
try {
val generatorClass = Class.forName("au.com.dius.pact.model.generators.${generatorMap["type"]}Generator").kotlin
val fromMap = when {
generatorClass.companionObject != null ->
generatorClass.companionObjectInstance to generatorClass.companionObject?.declaredMemberFunctions?.find { it.name == "fromMap" }
generatorClass.objectInstance != null ->
generatorClass.objectInstance to generatorClass.declaredMemberFunctions.find { it.name == "fromMap" }
else -> null
}
if (fromMap?.second != null) {
generator = fromMap.second!!.call(fromMap.first, generatorMap) as Generator?
} else {
logger.warn { "Could not invoke generator class 'fromMap' for generator config '$generatorMap'" }
}
} catch (e: ClassNotFoundException) {
logger.warn(e) { "Could not find generator class for generator config '$generatorMap'" }
}
return generator
}
interface Generator {
fun generate(base: Any?): Any
fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any>
}
data class RandomIntGenerator(val min: Int, val max: Int) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "RandomInt", "min" to min, "max" to max)
}
override fun generate(base: Any?): Any {
return RandomUtils.nextInt(min, max)
}
companion object {
fun fromMap(map: Map<String, Any>): RandomIntGenerator {
val min = if (map["min"] is Number) {
(map["min"] as Number).toInt()
} else {
logger.warn { "Ignoring invalid value for min: '${map["min"]}'" }
0
}
val max = if (map["max"] is Number) {
(map["max"] as Number).toInt()
} else {
logger.warn { "Ignoring invalid value for max: '${map["max"]}'" }
Int.MAX_VALUE
}
return RandomIntGenerator(min, max)
}
}
}
data class RandomDecimalGenerator(val digits: Int) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "RandomDecimal", "digits" to digits)
}
override fun generate(base: Any?): Any = BigDecimal(RandomStringUtils.randomNumeric(digits))
companion object {
fun fromMap(map: Map<String, Any>): RandomDecimalGenerator {
val digits = if (map["digits"] is Number) {
(map["digits"] as Number).toInt()
} else {
logger.warn { "Ignoring invalid value for digits: '${map["digits"]}'" }
10
}
return RandomDecimalGenerator(digits)
}
}
}
data class RandomHexadecimalGenerator(val digits: Int) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "RandomHexadecimal", "digits" to digits)
}
override fun generate(base: Any?): Any = RandomStringUtils.random(digits, "0123456789abcdef")
companion object {
fun fromMap(map: Map<String, Any>): RandomHexadecimalGenerator {
val digits = if (map["digits"] is Number) {
(map["digits"] as Number).toInt()
} else {
logger.warn { "Ignoring invalid value for digits: '${map["digits"]}'" }
10
}
return RandomHexadecimalGenerator(digits)
}
}
}
data class RandomStringGenerator(val size: Int = 20) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "RandomString", "size" to size)
}
override fun generate(base: Any?): Any {
return RandomStringUtils.randomAlphanumeric(size)
}
companion object {
fun fromMap(map: Map<String, Any>): RandomStringGenerator {
val size = if (map["size"] is Number) {
(map["size"] as Number).toInt()
} else {
logger.warn { "Ignoring invalid value for size: '${map["size"]}'" }
10
}
return RandomStringGenerator(size)
}
}
}
data class RegexGenerator(val regex: String) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "Regex", "regex" to regex)
}
override fun generate(base: Any?): Any = Generex(regex).random()
companion object {
fun fromMap(map: Map<String, Any>) = RegexGenerator(map["regex"]!! as String)
}
}
object UuidGenerator : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "Uuid")
}
override fun generate(base: Any?): Any {
return UUID.randomUUID().toString()
}
@Suppress("UNUSED_PARAMETER")
fun fromMap(map: Map<String, Any>): UuidGenerator {
return UuidGenerator
}
}
data class DateGenerator(val format: String? = null) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
if (format != null) {
return mapOf("type" to "Date", "format" to this.format)
}
return mapOf("type" to "Date")
}
override fun generate(base: Any?): Any {
return if (format != null) {
OffsetDateTime.now().format(DateTimeFormatter.ofPattern(format))
} else {
LocalDate.now().toString()
}
}
companion object {
fun fromMap(map: Map<String, Any>): DateGenerator {
return DateGenerator(map["format"] as String?)
}
}
}
data class TimeGenerator(val format: String? = null) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
if (format != null) {
return mapOf("type" to "Time", "format" to this.format)
}
return mapOf("type" to "Time")
}
override fun generate(base: Any?): Any {
return if (format != null) {
OffsetTime.now().format(DateTimeFormatter.ofPattern(format))
} else {
LocalTime.now().toString()
}
}
companion object {
fun fromMap(map: Map<String, Any>): TimeGenerator {
return TimeGenerator(map["format"] as String?)
}
}
}
data class DateTimeGenerator(val format: String? = null) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
if (format != null) {
return mapOf("type" to "DateTime", "format" to this.format)
}
return mapOf("type" to "DateTime")
}
override fun generate(base: Any?): Any {
return if (format != null) {
ZonedDateTime.now().format(DateTimeFormatter.ofPattern(format))
} else {
LocalDateTime.now().toString()
}
}
companion object {
fun fromMap(map: Map<String, Any>): DateTimeGenerator {
return DateTimeGenerator(map["format"] as String?)
}
}
}
object RandomBooleanGenerator : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "RandomBoolean")
}
override fun generate(base: Any?): Any {
return ThreadLocalRandom.current().nextBoolean()
}
override fun equals(other: Any?) = other is RandomBooleanGenerator
@Suppress("UNUSED_PARAMETER")
fun fromMap(map: Map<String, Any>): RandomBooleanGenerator {
return RandomBooleanGenerator
}
}
| pact-jvm-model/src/main/kotlin/au/com/dius/pact/model/generators/Generator.kt | 2590567079 |
@file:JvmName("Main")
package org.abendigo.controller
import org.abendigo.controller.network.Client
import org.abendigo.controller.overlay.Overlay
import org.jnativehook.GlobalScreen
import java.util.logging.Level
import java.util.logging.Logger
fun main(args: Array<String>) {
val out = System.out
System.setOut(null)
with(Logger.getLogger(GlobalScreen::class.java.`package`.name)) {
level = Level.OFF
useParentHandlers = false
}
GlobalScreen.registerNativeHook()
GlobalScreen.addNativeKeyListener(Keyboard)
System.setOut(out)
Client.connect().syncUninterruptibly()
Settings.load()
Settings.startAutosave()
Overlay.isVisible = true
} | Client Files/IntrepidClient-menu/src/main/kotlin/org/abendigo/controller/Main.kt | 3011302374 |
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.test.util.fakes
import com.google.samples.apps.iosched.model.ConferenceData
import com.google.samples.apps.iosched.shared.data.BootstrapConferenceDataSource
import com.google.samples.apps.iosched.shared.data.ConferenceDataSource
/**
* ConferenceDataSource data source that never touches the network.
*
* This class is only available with the staging variant. It's used for unit tests.
*/
object FakeConferenceDataSource : ConferenceDataSource {
override fun getRemoteConferenceData() = getOfflineConferenceData()
override fun getOfflineConferenceData(): ConferenceData? {
val bootstrapContent = BootstrapConferenceDataSource.getOfflineConferenceData()
return bootstrapContent ?: throw Exception("Couldn't load data")
}
}
| mobile/src/test/java/com/google/samples/apps/iosched/test/util/fakes/FakeConferenceDataSource.kt | 1761380371 |
package com.github.vhromada.catalog.web.validator
import com.github.vhromada.catalog.web.fo.AccountFO
import com.github.vhromada.catalog.web.validator.constraints.Password
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
/**
* A class represents validator for password constraint.
*
* @author Vladimir Hromada
*/
class PasswordValidator : ConstraintValidator<Password, AccountFO> {
override fun isValid(account: AccountFO?, constraintValidatorContext: ConstraintValidatorContext): Boolean {
if (account == null) {
return false
}
if (account.password.isNullOrEmpty() || account.copyPassword.isNullOrEmpty()) {
return true
}
return account.password == account.copyPassword
}
}
| web/src/main/kotlin/com/github/vhromada/catalog/web/validator/PasswordValidator.kt | 649613447 |
// 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.k2.codeinsight.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.diagnostics.WhenMissingCase
import org.jetbrains.kotlin.idea.codeinsight.api.applicable.intentions.AbstractKotlinApplicableIntentionWithContext
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicabilityRange
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges
import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.AddRemainingWhenBranchesUtils
import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.AddRemainingWhenBranchesUtils.addRemainingWhenBranches
import org.jetbrains.kotlin.psi.KtWhenExpression
internal class AddWhenRemainingBranchesIntention
: AbstractKotlinApplicableIntentionWithContext<KtWhenExpression, AddRemainingWhenBranchesUtils.Context>(KtWhenExpression::class) {
override fun getFamilyName(): String = AddRemainingWhenBranchesUtils.familyAndActionName(false)
override fun getActionName(element: KtWhenExpression, context: AddRemainingWhenBranchesUtils.Context): String = familyName
override fun getApplicabilityRange(): KotlinApplicabilityRange<KtWhenExpression> = ApplicabilityRanges.SELF
override fun isApplicableByPsi(element: KtWhenExpression): Boolean = true
context(KtAnalysisSession)
override fun prepareContext(element: KtWhenExpression): AddRemainingWhenBranchesUtils.Context? {
val whenMissingCases = element.getMissingCases().takeIf {
it.isNotEmpty() && it.singleOrNull() != WhenMissingCase.Unknown
} ?: return null
return AddRemainingWhenBranchesUtils.Context(whenMissingCases, enumToStarImport = null)
}
override fun apply(element: KtWhenExpression, context: AddRemainingWhenBranchesUtils.Context, project: Project, editor: Editor?) {
addRemainingWhenBranches(element, context)
}
} | plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/AddWhenRemainingBranchesIntention.kt | 430063600 |
package com.fueled.recyclerviewbindings.widget.scroll
import android.support.v7.widget.RecyclerView
class RecyclerViewScrollCallback(private val visibleThreshold: Int, private val layoutManager: RecyclerView.LayoutManager)
: RecyclerView.OnScrollListener() {
// The minimum amount of items to have below your current scroll position
// before loading more.
// The current offset index of data you have loaded
private var currentPage = 0
// The total number of items in the dataset after the last load
private var previousTotalItemCount = 0
// True if we are still waiting for the last set of data to load.
private var loading = true
// Sets the starting page index
private val startingPageIndex = 0
lateinit var layoutManagerType: LayoutManagerType
lateinit var onScrolledListener: OnScrolledListener
constructor(builder: Builder) : this(builder.visibleThreshold, builder.layoutManager) {
this.layoutManagerType = builder.layoutManagerType
this.onScrolledListener = builder.onScrolledListener
if (builder.resetLoadingState) {
resetState()
}
}
// This happens many times a second during a scroll, so be wary of the code you place here.
// We are given a few useful parameters to help us work out if we need to load some more data,
// but first we check if we are waiting for the previous load to finish.
override fun onScrolled(view: RecyclerView?, dx: Int, dy: Int) {
val lastVisibleItemPosition = RecyclerViewUtil.getLastVisibleItemPosition(layoutManager, layoutManagerType)
val totalItemCount = layoutManager.itemCount
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state
if (totalItemCount < previousTotalItemCount) {
this.currentPage = this.startingPageIndex
this.previousTotalItemCount = totalItemCount
if (totalItemCount == 0) {
this.loading = true
}
}
// If it’s still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the current page
// number and total item count.
if (loading && totalItemCount > previousTotalItemCount) {
loading = false
previousTotalItemCount = totalItemCount
}
// If it isn’t currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to fetch the data.
// threshold should reflect how many total columns there are too
if (!loading && lastVisibleItemPosition + visibleThreshold > totalItemCount) {
currentPage++
onScrolledListener.onScrolledToBottom(currentPage)
loading = true
}
}
// Call this method whenever performing new searches
private fun resetState() {
this.currentPage = this.startingPageIndex
this.previousTotalItemCount = 0
this.loading = true
}
interface OnScrolledListener {
fun onScrolledToBottom(page: Int)
}
class Builder(internal val layoutManager: RecyclerView.LayoutManager) {
internal var visibleThreshold = 7
internal var layoutManagerType = LayoutManagerType.LINEAR
internal lateinit var onScrolledListener: OnScrolledListener
internal var resetLoadingState: Boolean = false
fun visibleThreshold(value: Int): Builder {
visibleThreshold = value
return this
}
fun onScrolledListener(value: OnScrolledListener): Builder {
onScrolledListener = value
return this
}
fun resetLoadingState(value: Boolean): Builder {
resetLoadingState = value
return this
}
fun build(): RecyclerViewScrollCallback {
layoutManagerType = RecyclerViewUtil.computeLayoutManagerType(layoutManager)
visibleThreshold = RecyclerViewUtil.computeVisibleThreshold(
layoutManager, layoutManagerType, visibleThreshold)
return RecyclerViewScrollCallback(this)
}
}
} | app/src/main/java/com/fueled/recyclerviewbindings/widget/scroll/RecyclerViewScrollCallback.kt | 3894992358 |
package io.github.ranolp.kubo.discord.objects
import io.github.ranolp.kubo.general.objects.Chat
import io.github.ranolp.kubo.general.objects.History
import io.github.ranolp.kubo.general.objects.Message
import net.dv8tion.jda.core.entities.MessageHistory
class DiscordHistory(val jdaHistory: MessageHistory) : History {
override val chat: Chat by lazy {
DiscordChat(jdaHistory.channel)
}
override fun retrieve(count: Int): List<Message> {
return jdaHistory.retrievePast(count).complete().map(::DiscordMessage)
}
} | Kubo-Discord/src/main/kotlin/io/github/ranolp/kubo/discord/objects/DiscordHistory.kt | 1105012009 |
package com.glodanif.bluetoothchat.ui.activity
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import androidx.transition.Transition
import androidx.transition.TransitionManager
import androidx.core.app.ActivityOptionsCompat
import androidx.core.view.ViewCompat
import android.util.ArrayMap
import android.view.Menu
import android.view.MenuItem
import android.view.ViewGroup
import android.widget.ImageView
import com.github.chrisbanes.photoview.PhotoView
import com.glodanif.bluetoothchat.R
import com.glodanif.bluetoothchat.data.entity.MessageFile
import com.glodanif.bluetoothchat.ui.presenter.ImagePreviewPresenter
import com.glodanif.bluetoothchat.ui.view.ImagePreviewView
import com.glodanif.bluetoothchat.ui.viewmodel.ChatMessageViewModel
import com.glodanif.bluetoothchat.utils.argument
import com.glodanif.bluetoothchat.utils.bind
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import org.koin.android.ext.android.inject
import org.koin.core.parameter.parametersOf
import java.io.File
import java.lang.Exception
import java.lang.ref.WeakReference
class ImagePreviewActivity : SkeletonActivity(), ImagePreviewView {
private val messageId: Long by argument(EXTRA_MESSAGE_ID, -1L)
private val imagePath: String? by argument(EXTRA_IMAGE_PATH)
private val own: Boolean by argument(EXTRA_OWN, false)
private val presenter: ImagePreviewPresenter by inject {
parametersOf(messageId, File(imagePath), this)
}
private val imageView: PhotoView by bind(R.id.pv_preview)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image_preview, ActivityType.CHILD_ACTIVITY)
supportPostponeEnterTransition()
ViewCompat.setTransitionName(imageView, messageId.toString())
toolbar?.setTitleTextAppearance(this, R.style.ActionBar_TitleTextStyle)
toolbar?.setSubtitleTextAppearance(this, R.style.ActionBar_SubTitleTextStyle)
imageView.minimumScale = .75f
imageView.maximumScale = 2f
presenter.loadImage()
}
override fun displayImage(fileUrl: String) {
val callback = object : Callback {
override fun onSuccess() {
supportStartPostponedEnterTransition()
}
override fun onError(e: Exception?) {
supportStartPostponedEnterTransition()
}
}
Picasso.get()
.load(fileUrl)
.config(Bitmap.Config.RGB_565)
.noFade()
.into(imageView, callback)
}
override fun showFileInfo(name: String, readableSize: String) {
title = name
toolbar?.subtitle = readableSize
}
override fun close() {
finish()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
if (!own) {
menuInflater.inflate(R.menu.menu_image_preview, menu)
}
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_remove -> {
confirmFileRemoval()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun confirmFileRemoval() {
AlertDialog.Builder(this)
.setMessage(getString(R.string.images__removal_confirmation))
.setPositiveButton(getString(R.string.general__yes)) { _, _ ->
presenter.removeFile()
}
.setNegativeButton(getString(R.string.general__no), null)
.show()
}
override fun onDestroy() {
super.onDestroy()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return
}
//Fixes https://issuetracker.google.com/issues/37042900
val transitionManagerClass = TransitionManager::class.java
try {
val runningTransitionsField = transitionManagerClass.getDeclaredField("sRunningTransitions")
runningTransitionsField.isAccessible = true
val runningTransitions = runningTransitionsField.get(transitionManagerClass)
as ThreadLocal<WeakReference<ArrayMap<ViewGroup, ArrayList<Transition>>>>
if (runningTransitions.get() == null || runningTransitions.get().get() == null) {
return
}
val map = runningTransitions.get().get()
val decorView = window.decorView
if (map != null && map.containsKey(decorView)) {
map.remove(decorView)
}
} catch (e: NoSuchFieldException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
}
companion object {
const val EXTRA_MESSAGE_ID = "extra.message_id"
const val EXTRA_IMAGE_PATH = "extra.image_path"
const val EXTRA_OWN = "extra.own"
fun start(activity: Activity, transitionView: ImageView, message: MessageFile) {
start(activity, transitionView, message.uid, message.filePath ?: "unknown", message.own)
}
fun start(activity: Activity, transitionView: ImageView, message: ChatMessageViewModel) {
start(activity, transitionView, message.uid, message.imagePath
?: "unknown", message.own)
}
fun start(activity: Activity, transitionView: ImageView, messageId: Long, imagePath: String, ownMessage: Boolean) {
val intent = Intent(activity, ImagePreviewActivity::class.java)
.putExtra(EXTRA_MESSAGE_ID, messageId)
.putExtra(EXTRA_IMAGE_PATH, imagePath)
.putExtra(EXTRA_OWN, ownMessage)
val options = ActivityOptionsCompat
.makeSceneTransitionAnimation(activity, transitionView, messageId.toString())
activity.startActivity(intent, options.toBundle())
}
}
}
| app/src/main/kotlin/com/glodanif/bluetoothchat/ui/activity/ImagePreviewActivity.kt | 3431042010 |
package com.widgets
import com.google.inject.AbstractModule
import com.widgets.controllers.WidgetController
import com.widgets.services.WidgetService
import com.widgets.services.impl.DefaultWidgetService
/**
* @author Michael Vaughan
*/
class Module : AbstractModule() {
override fun configure() {
bind(Routes::class.java).asEagerSingleton()
bind(WidgetController::class.java)
bind(WidgetService::class.java).to(DefaultWidgetService::class.java)
}
} | src/main/kotlin/com/widgets/Module.kt | 3106946166 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.multitenant.fs
import java.nio.file.FileSystems
import java.nio.file.Paths
import org.hamcrest.Matchers
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThat
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
class FsAgnosticPathTest {
@get:Rule
val thrown: ExpectedException = ExpectedException.none()
@Test
fun emptyPathIsOk() {
val path = FsAgnosticPath.of("")
assertEquals("", path.toString())
}
@Test
fun singleComponentIsOk() {
val path = FsAgnosticPath.of("foo")
assertEquals("foo", path.toString())
}
@Test
fun multiComponentIsOk() {
val path = FsAgnosticPath.of("foo/bar")
assertEquals("foo/bar", path.toString())
}
@Test
fun isEmpty() {
val emptyPath = FsAgnosticPath.of("")
assertTrue(emptyPath.isEmpty())
val foo = FsAgnosticPath.of("foo")
assertFalse(foo.isEmpty())
val fooBar = FsAgnosticPath.of("foo/bar")
assertFalse(fooBar.isEmpty())
}
@Test
fun pathStartsWithItself() {
val emptyPath = FsAgnosticPath.of("")
assertTrue(emptyPath.startsWith(emptyPath))
val foo = FsAgnosticPath.of("foo")
assertTrue(foo.startsWith(foo))
val fooBar = FsAgnosticPath.of("foo/bar")
assertTrue(fooBar.startsWith(fooBar))
}
@Test
fun emptyPathIsAUniversalPrefix() {
val emptyPath = FsAgnosticPath.of("")
assertTrue(FsAgnosticPath.of("foo").startsWith(emptyPath))
assertTrue(FsAgnosticPath.of("foo/bar").startsWith(emptyPath))
}
@Test
fun startsWith() {
val foo = FsAgnosticPath.of("foo")
val fooBar = FsAgnosticPath.of("foo/bar")
val food = FsAgnosticPath.of("food")
assertTrue(fooBar.startsWith(foo))
assertFalse(foo.startsWith(fooBar))
assertFalse(food.startsWith(foo))
}
@Test
fun invalidSingleDotPath() {
thrown.expect(IllegalArgumentException::class.java)
thrown.expectMessage("dot in path")
FsAgnosticPath.of(".")
}
@Test
fun invalidDoubleDotPath() {
thrown.expect(IllegalArgumentException::class.java)
thrown.expectMessage("dot-dot in path")
FsAgnosticPath.of("..")
}
@Test
fun invalidSlashOnlyPath() {
thrown.expect(IllegalArgumentException::class.java)
thrown.expectMessage("path must not start with slash")
FsAgnosticPath.of("/")
}
@Test
fun invalidAbsolutePath() {
thrown.expect(IllegalArgumentException::class.java)
thrown.expectMessage("path must not start with slash")
FsAgnosticPath.of("/foo/bar")
}
@Test
fun invalidPathWithTrailingSlash() {
thrown.expect(IllegalArgumentException::class.java)
thrown.expectMessage("must not end with slash")
FsAgnosticPath.of("foo/bar/")
}
@Test
fun invalidPathWithDoubleSlash() {
thrown.expect(IllegalArgumentException::class.java)
thrown.expectMessage("two slashes")
FsAgnosticPath.of("foo//bar")
}
@Test
fun invalidPathWithDotComponent() {
thrown.expect(IllegalArgumentException::class.java)
thrown.expectMessage("dot in path")
FsAgnosticPath.of("foo/./bar")
}
@Test
fun invalidPathWithDoubleDotComponent() {
thrown.expect(IllegalArgumentException::class.java)
thrown.expectMessage("dot-dot in path")
FsAgnosticPath.of("foo/../bar")
}
@Test
fun compareEqual() {
val a = FsAgnosticPath.of("foo/bar")
val b = FsAgnosticPath.of("foo/bar")
assertEquals(0, a.compareTo(b))
assertEquals(0, b.compareTo(a))
}
@Test
fun compareNotEqual() {
val a = FsAgnosticPath.of("foo/a")
val b = FsAgnosticPath.of("foo/b")
assertThat(a.compareTo(b), Matchers.lessThan(0))
assertThat(b.compareTo(a), Matchers.greaterThan(0))
}
@Test
fun resolveEmptyAgainstEmpty() {
val empty1 = FsAgnosticPath.of("")
val empty2 = FsAgnosticPath.of("")
assertEquals(FsAgnosticPath.of(""), empty1.resolve(empty2))
}
@Test
fun resolveEmptyAgainstNonEmpty() {
val empty = FsAgnosticPath.of("")
val other = FsAgnosticPath.of("foo/bar")
assertEquals(FsAgnosticPath.of("foo/bar"), empty.resolve(other))
}
@Test
fun resolveNonEmptyAgainstEmpty() {
val other = FsAgnosticPath.of("foo/bar")
val empty = FsAgnosticPath.of("")
assertEquals(FsAgnosticPath.of("foo/bar"), other.resolve(empty))
}
@Test
fun resolveNonEmptyAgainstNonEmpty() {
val a = FsAgnosticPath.of("foo/bar")
val b = FsAgnosticPath.of("baz/buzz")
assertEquals(FsAgnosticPath.of("foo/bar/baz/buzz"), a.resolve(b))
assertEquals(FsAgnosticPath.of("baz/buzz/foo/bar"), b.resolve(a))
}
@Test
fun toPath() {
val empty = FsAgnosticPath.of("")
val foo = FsAgnosticPath.of("foo")
val fooBar = FsAgnosticPath.of("foo/bar")
val fooBarBaz = FsAgnosticPath.of("foo/bar/baz")
val fooPath = Paths.get("foo")
val fooBarPath = fooPath.resolve(Paths.get("bar"))
val fooBarBazPath = fooBarPath.resolve(Paths.get("baz"))
val fileSystem = FileSystems.getDefault()
assertEquals(empty.toPath(fileSystem), Paths.get(""))
assertEquals(foo.toPath(fileSystem), fooPath)
assertEquals(fooBar.toPath(fileSystem), fooBarPath)
assertEquals(fooBarBaz.toPath(fileSystem), fooBarBazPath)
}
}
| test/com/facebook/buck/multitenant/fs/FsAgnosticPathTest.kt | 767635311 |
package no.skatteetaten.aurora.boober.utils
import no.skatteetaten.aurora.boober.model.PortNumbers
import no.skatteetaten.aurora.boober.service.UrlValidationException
import java.net.URI
class UrlParser(val url: String) {
private val uri: URI? = if (isJdbcUrl()) null else URI(url)
private val jdbcUri: JdbcUri? = when {
isPostgresJdbcUrl() -> PostgresJdbcUri(url)
isOracleJdbcUrl() -> OracleJdbcUri(url)
else -> null
}
val hostName: String get() {
assertIsValid()
return uri?.host ?: jdbcUri!!.hostName
}
val port: Int get() {
assertIsValid()
return uri?.givenOrDefaultPort() ?: jdbcUri!!.port
}
val suffix: String get() {
assertIsValid()
return uri?.suffix() ?: jdbcUri!!.suffix
}
private fun isJdbcUrl() = url.startsWith("jdbc:")
private fun isOracleJdbcUrl() = url.startsWith("jdbc:oracle:thin:@")
private fun isPostgresJdbcUrl() = url.startsWith("jdbc:postgresql:")
fun isValid(): Boolean = (if (isJdbcUrl()) jdbcUri?.isValid() else uri?.isValid()) ?: false
fun assertIsValid() = if (!isValid()) {
throw UrlValidationException("The format of the URL \"$url\" is not supported")
} else { null }
fun makeString(
modifiedHostName: String = hostName,
modifiedPort: Int = port,
modifiedSuffix: String = suffix
): String {
assertIsValid()
return if (isJdbcUrl()) {
jdbcUri!!.makeString(modifiedHostName, modifiedPort, modifiedSuffix)
} else {
uri!!.makeString(modifiedHostName, modifiedPort, modifiedSuffix)
}
}
fun withModifiedHostName(newHostName: String) = UrlParser(makeString(modifiedHostName = newHostName))
fun withModifiedPort(newPort: Int) = UrlParser(makeString(modifiedPort = newPort))
}
private abstract class JdbcUri {
abstract val hostName: String
abstract val port: Int
abstract val suffix: String
abstract fun isValid(): Boolean
abstract fun makeString(
modifiedHostName: String = hostName,
modifiedPort: Int = port,
modifiedSuffix: String = suffix
): String
}
private class PostgresJdbcUri(postgresJdbcUrl: String) : JdbcUri() {
val uri = URI(
if (postgresJdbcUrl.startsWith("jdbc:postgresql://")) {
postgresJdbcUrl
} else {
// If hostname is not given, it should default to localhost
postgresJdbcUrl.replaceFirst("sql:", "sql://localhost/")
}.removePrefix("jdbc:")
)
override val hostName: String get() = uri.host
override val port: Int get() = uri.givenOrDefaultPort()
override val suffix: String get() = uri.suffix()
override fun isValid(): Boolean = uri.isValid()
override fun makeString(
modifiedHostName: String,
modifiedPort: Int,
modifiedSuffix: String
) = "jdbc:postgresql://$modifiedHostName:$modifiedPort$modifiedSuffix"
}
private class OracleJdbcUri(private val oracleJdbcUrl: String) : JdbcUri() {
override val hostName: String get() = oracleJdbcUrl
.removeEverythingBeforeHostnameFromOracleJdbcUrl()
.substringBefore('?')
.substringBefore('/')
.substringBefore(':')
override val port: Int get() = Regex("^[0-9]+")
.find(
oracleJdbcUrl
.removeEverythingBeforeHostnameFromOracleJdbcUrl()
.removePrefix("$hostName:")
)
?.value
?.toInt()
?: PortNumbers.DEFAULT_ORACLE_PORT
override val suffix: String get() = oracleJdbcUrl
.removeEverythingBeforeHostnameFromOracleJdbcUrl()
.removePrefix(hostName)
.replace(Regex("^:[0-9]+"), "")
val protocol: String get() =
Regex("(?<=^jdbc:oracle:thin:@)([a-z]+:\\/\\/|\\/\\/)").find(oracleJdbcUrl)?.value ?: ""
override fun isValid(): Boolean = hostName.isNotEmpty()
override fun makeString(
modifiedHostName: String,
modifiedPort: Int,
modifiedSuffix: String
) = "jdbc:oracle:thin:@$protocol$modifiedHostName:$modifiedPort$modifiedSuffix"
private fun String.removeEverythingBeforeHostnameFromOracleJdbcUrl() =
replace(Regex("^jdbc:oracle:thin:@([a-z]+:\\/\\/|\\/\\/)?"), "")
}
private fun URI.givenOrDefaultPort() = if (port == -1) when (scheme) {
"https" -> PortNumbers.HTTPS_PORT
"postgresql" -> PortNumbers.DEFAULT_POSTGRES_PORT
else -> PortNumbers.HTTP_PORT
} else port
private fun URI.suffix() = path + (if (query != null) "?$query" else "")
private fun URI.isValid() = !scheme.isNullOrEmpty() && !host.isNullOrEmpty()
private fun URI.makeString(
modifiedHostName: String,
modifiedPort: Int,
modifiedSuffix: String
) = "$scheme://$modifiedHostName:$modifiedPort$modifiedSuffix"
| src/main/kotlin/no/skatteetaten/aurora/boober/utils/UrlParser.kt | 1775595259 |
package ch.difty.scipamato.core.entity.search
import ch.difty.scipamato.common.entity.CodeClassId
import ch.difty.scipamato.core.entity.Code
import ch.difty.scipamato.core.entity.IdScipamatoEntity.IdScipamatoEntityFields.ID
import ch.difty.scipamato.core.entity.Paper.PaperFields.DOI
import ch.difty.scipamato.core.entity.Paper.PaperFields.FIRST_AUTHOR_OVERRIDDEN
import ch.difty.scipamato.core.entity.Paper.PaperFields.NUMBER
import ch.difty.scipamato.core.entity.newsletter.NewsletterTopic
import io.mockk.every
import io.mockk.mockk
import org.amshove.kluent.invoking
import org.amshove.kluent.shouldBeEmpty
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeFalse
import org.amshove.kluent.shouldBeNull
import org.amshove.kluent.shouldBeTrue
import org.amshove.kluent.shouldContainAll
import org.amshove.kluent.shouldContainSame
import org.amshove.kluent.shouldHaveSize
import org.amshove.kluent.shouldNotBeEqualTo
import org.amshove.kluent.shouldThrow
import org.amshove.kluent.withMessage
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.fail
private const val SEARCH_CONDITION_ID: Long = 1
private const val X = "x"
@Suppress("LargeClass", "SpellCheckingInspection")
internal class SearchConditionTest {
private val sc1 = SearchCondition(SEARCH_CONDITION_ID)
private val sc2 = SearchCondition()
@Test
fun allStringSearchTerms() {
sc1.doi = X
sc1.authors = X
sc1.firstAuthor = X
sc1.title = X
sc1.location = X
sc1.goals = X
sc1.population = X
sc1.populationPlace = X
sc1.populationParticipants = X
sc1.populationDuration = X
sc1.exposureAssessment = X
sc1.exposurePollutant = X
sc1.methods = X
sc1.methodStudyDesign = X
sc1.methodOutcome = X
sc1.methodStatistics = X
sc1.methodConfounders = X
sc1.result = X
sc1.resultExposureRange = X
sc1.resultEffectEstimate = X
sc1.resultMeasuredOutcome = X
sc1.conclusion = X
sc1.comment = X
sc1.intern = X
sc1.originalAbstract = X
sc1.mainCodeOfCodeclass1 = X
sc1.stringSearchTerms shouldHaveSize 26
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.auditSearchTerms.shouldBeEmpty()
sc1.createdDisplayValue.shouldBeNull()
sc1.modifiedDisplayValue.shouldBeNull()
sc1.searchConditionId shouldBeEqualTo SEARCH_CONDITION_ID
}
@Test
fun allIntegerSearchTerms() {
sc1.id = "3"
sc1.pmId = "6"
sc1.number = "30"
sc1.publicationYear = "2017"
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms shouldHaveSize 4
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.auditSearchTerms.shouldBeEmpty()
sc1.createdDisplayValue.shouldBeNull()
sc1.modifiedDisplayValue.shouldBeNull()
sc1.searchConditionId shouldBeEqualTo SEARCH_CONDITION_ID
sc1.number shouldBeEqualTo "30"
}
@Test
fun allBooleanSearchTerms() {
sc1.isFirstAuthorOverridden = true
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms shouldHaveSize 1
sc1.auditSearchTerms.shouldBeEmpty()
sc1.createdDisplayValue.shouldBeNull()
sc1.modifiedDisplayValue.shouldBeNull()
sc1.searchConditionId shouldBeEqualTo SEARCH_CONDITION_ID
}
@Test
fun allAuditSearchTerms() {
sc1.createdDisplayValue = X
sc1.modifiedDisplayValue = X + X
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.auditSearchTerms shouldHaveSize 4
sc1.searchConditionId shouldBeEqualTo SEARCH_CONDITION_ID
}
@Test
fun id_extensiveTest() {
sc1.id.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.id = "5"
sc1.id shouldBeEqualTo "5"
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms shouldHaveSize 1
sc1.booleanSearchTerms.shouldBeEmpty()
var st = sc1.integerSearchTerms.first()
st.fieldName shouldBeEqualTo ID.fieldName
st.rawSearchTerm shouldBeEqualTo "5"
sc1.id = "10"
sc1.id shouldBeEqualTo "10"
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms shouldHaveSize 1
sc1.booleanSearchTerms.shouldBeEmpty()
st = sc1.integerSearchTerms.first()
st.fieldName shouldBeEqualTo ID.fieldName
st.rawSearchTerm shouldBeEqualTo "10"
sc1.id = null
sc1.id.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
}
@Test
fun number_extensiveTest() {
sc1.number.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.number = "50"
sc1.number shouldBeEqualTo "50"
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms shouldHaveSize 1
sc1.booleanSearchTerms.shouldBeEmpty()
var st = sc1.integerSearchTerms.first()
st.fieldName shouldBeEqualTo NUMBER.fieldName
st.rawSearchTerm shouldBeEqualTo "50"
sc1.number = "100"
sc1.number shouldBeEqualTo "100"
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms shouldHaveSize 1
sc1.booleanSearchTerms.shouldBeEmpty()
st = sc1.integerSearchTerms.first()
st.fieldName shouldBeEqualTo NUMBER.fieldName
st.rawSearchTerm shouldBeEqualTo "100"
sc1.number = null
sc1.number.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
}
@Test
fun doi_extensiveTest() {
sc1.doi.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.doi = "101111"
sc1.doi shouldBeEqualTo "101111"
sc1.stringSearchTerms shouldHaveSize 1
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
var st = sc1.stringSearchTerms.first()
st.fieldName shouldBeEqualTo DOI.fieldName
st.rawSearchTerm shouldBeEqualTo "101111"
sc1.doi = "102222"
sc1.doi shouldBeEqualTo "102222"
sc1.stringSearchTerms shouldHaveSize 1
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
st = sc1.stringSearchTerms.first()
st.fieldName shouldBeEqualTo DOI.fieldName
st.rawSearchTerm shouldBeEqualTo "102222"
sc1.doi = null
sc1.doi.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.searchConditionId shouldBeEqualTo SEARCH_CONDITION_ID
}
@Test
fun pmId() {
sc1.pmId.shouldBeNull()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.pmId = "6"
sc1.pmId shouldBeEqualTo "6"
sc1.integerSearchTerms shouldHaveSize 1
sc1.pmId = null
sc1.pmId.shouldBeNull()
sc1.integerSearchTerms.shouldBeEmpty()
}
@Test
fun authors() {
sc1.authors.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.authors = X
sc1.authors shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.authors = null
sc1.authors.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun firstAuthor() {
sc1.firstAuthor.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.firstAuthor = X
sc1.firstAuthor shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.firstAuthor = null
sc1.firstAuthor.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun firstAuthorOverridden_extensiveTest() {
sc1.isFirstAuthorOverridden.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.isFirstAuthorOverridden = true
(sc1.isFirstAuthorOverridden == true).shouldBeTrue()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms shouldHaveSize 1
var st = sc1.booleanSearchTerms.first()
st.fieldName shouldBeEqualTo FIRST_AUTHOR_OVERRIDDEN.fieldName
st.rawSearchTerm shouldBeEqualTo "true"
st.value.shouldBeTrue()
sc1.isFirstAuthorOverridden = false
(sc1.isFirstAuthorOverridden == true).shouldBeFalse()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms shouldHaveSize 1
st = sc1.booleanSearchTerms.first()
st.fieldName shouldBeEqualTo FIRST_AUTHOR_OVERRIDDEN.fieldName
st.rawSearchTerm shouldBeEqualTo "false"
st.value.shouldBeFalse()
sc1.isFirstAuthorOverridden = null
sc1.isFirstAuthorOverridden.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
}
@Test
fun title() {
sc1.title.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.title = X
sc1.title shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.title = null
sc1.title.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun location() {
sc1.location.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.location = X
sc1.location shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.location = null
sc1.location.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun publicationYear() {
sc1.publicationYear.shouldBeNull()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.publicationYear = "2016"
sc1.publicationYear shouldBeEqualTo "2016"
sc1.integerSearchTerms shouldHaveSize 1
sc1.publicationYear = null
sc1.publicationYear.shouldBeNull()
sc1.integerSearchTerms.shouldBeEmpty()
}
@Test
fun goals() {
sc1.goals.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.goals = X
sc1.goals shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.goals = null
sc1.goals.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun population() {
sc1.population.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.population = X
sc1.population shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.population = null
sc1.population.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun populationPlace() {
sc1.populationPlace.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.populationPlace = X
sc1.populationPlace shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.populationPlace = null
sc1.populationPlace.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun populationParticipants() {
sc1.populationParticipants.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.populationParticipants = X
sc1.populationParticipants shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.populationParticipants = null
sc1.populationParticipants.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun populationDuration() {
sc1.populationDuration.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.populationDuration = X
sc1.populationDuration shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.populationDuration = null
sc1.populationDuration.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun exposurePollutant() {
sc1.exposurePollutant.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.exposurePollutant = X
sc1.exposurePollutant shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.exposurePollutant = null
sc1.exposurePollutant.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun exposureAssessment() {
sc1.exposureAssessment.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.exposureAssessment = X
sc1.exposureAssessment shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.exposureAssessment = null
sc1.exposureAssessment.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun methods() {
sc1.methods.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.methods = X
sc1.methods shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.methods = null
sc1.methods.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun methodStudyDesign() {
sc1.methodStudyDesign.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.methodStudyDesign = X
sc1.methodStudyDesign shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.methodStudyDesign = null
sc1.methodStudyDesign.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun methodOutcome() {
sc1.methodOutcome.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.methodOutcome = X
sc1.methodOutcome shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.methodOutcome = null
sc1.methodOutcome.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun methodStatistics() {
sc1.methodStatistics.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.methodStatistics = X
sc1.methodStatistics shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.methodStatistics = null
sc1.methodStatistics.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun methodConfounders() {
sc1.methodConfounders.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.methodConfounders = X
sc1.methodConfounders shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.methodConfounders = null
sc1.methodConfounders.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun result() {
sc1.result.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.result = X
sc1.result shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.result = null
sc1.result.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun resultExposureRange() {
sc1.resultExposureRange.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.resultExposureRange = X
sc1.resultExposureRange shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.resultExposureRange = null
sc1.resultExposureRange.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun resultEffectEstimate() {
sc1.resultEffectEstimate.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.resultEffectEstimate = X
sc1.resultEffectEstimate shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.resultEffectEstimate = null
sc1.resultEffectEstimate.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun resultMeasuredOutcome() {
sc1.resultMeasuredOutcome.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.resultMeasuredOutcome = X
sc1.resultMeasuredOutcome shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.resultMeasuredOutcome = null
sc1.resultMeasuredOutcome.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun conclusion() {
sc1.conclusion.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.conclusion = X
sc1.conclusion shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.conclusion = null
sc1.conclusion.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun comment() {
sc1.comment.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.comment = X
sc1.comment shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.comment = null
sc1.comment.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun intern() {
sc1.intern.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.intern = X
sc1.intern shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.intern = null
sc1.intern.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun originalAbstract() {
sc1.originalAbstract.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.originalAbstract = X
sc1.originalAbstract shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.originalAbstract = null
sc1.originalAbstract.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun mainCodeOfClass1() {
sc1.mainCodeOfCodeclass1.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.mainCodeOfCodeclass1 = X
sc1.mainCodeOfCodeclass1 shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.mainCodeOfCodeclass1 = null
sc1.mainCodeOfCodeclass1.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun createdDisplayValue() {
sc1.createdDisplayValue.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.createdDisplayValue = X
sc1.createdDisplayValue shouldBeEqualTo X
sc1.created shouldBeEqualTo X
sc1.createdBy shouldBeEqualTo X
sc1.lastModified.shouldBeNull()
sc1.lastModifiedBy.shouldBeNull()
sc1.stringSearchTerms shouldHaveSize 0
sc1.createdDisplayValue = null
sc1.createdDisplayValue.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun modifiedDisplayValue() {
sc1.modifiedDisplayValue.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.modifiedDisplayValue = X
sc1.modifiedDisplayValue shouldBeEqualTo X
sc1.lastModified shouldBeEqualTo X
sc1.lastModifiedBy shouldBeEqualTo X
sc1.created.shouldBeNull()
sc1.createdBy.shouldBeNull()
sc1.stringSearchTerms shouldHaveSize 0
sc1.modifiedDisplayValue = null
sc1.modifiedDisplayValue.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun testDisplayValue_withSingleStringSearchTerms_returnsIt() {
sc1.authors = "hoops"
sc1.displayValue shouldBeEqualTo "hoops"
}
@Test
fun testDisplayValue_withTwoStringSearchTerms_joinsThemUsingAnd() {
sc1.authors = "rag"
sc1.methodConfounders = "bones"
sc1.displayValue shouldBeEqualTo "rag AND bones"
}
@Test
fun testDisplayValue_forBooleanSearchTermsBeginFalse() {
sc1.isFirstAuthorOverridden = false
sc1.displayValue shouldBeEqualTo "-firstAuthorOverridden"
}
@Test
fun testDisplayValue_forIntegerSearchTerms() {
sc1.publicationYear = "2017"
sc1.displayValue shouldBeEqualTo "2017"
}
@Test
fun testDisplayValue_forAuditSearchTermsForAuthorSearch() {
sc1.createdDisplayValue = "mkj"
sc1.displayValue shouldBeEqualTo "mkj"
}
@Test
fun testDisplayValue_forAuditSearchTermsForDateSearch() {
sc1.createdDisplayValue = ">2017-01-23"
sc1.displayValue shouldBeEqualTo ">2017-01-23"
}
@Test
fun testDisplayValue_forAuditSearchTermsForCombinedSearch() {
sc1.modifiedDisplayValue = "rk >=2017-01-23"
sc1.displayValue shouldBeEqualTo "rk >=2017-01-23"
}
@Test
fun testDisplayValue_withHasAttachment() {
sc1.hasAttachments = true
sc1.displayValue shouldBeEqualTo "attachment=true"
sc1.hasAttachments = false
sc1.displayValue shouldBeEqualTo "attachment=false"
}
@Test
fun testDisplayValue_withAttachmentMask_displaysItRegardlessOfHasAttachment() {
// attachmentNameMask is not considered if hasAttachment is set to non-null
sc1.attachmentNameMask = "foo"
sc1.hasAttachments = true
sc1.displayValue shouldBeEqualTo "attachment=foo"
sc1.hasAttachments = false
sc1.displayValue shouldBeEqualTo "attachment=foo"
sc1.hasAttachments = null
sc1.displayValue shouldBeEqualTo "attachment=foo"
}
@Test
fun testDisplayValue_withMultipleSearchTerms_joinsThemAllUsingAND() {
sc1.authors = "fooAuth"
sc1.methodStudyDesign = "bar"
sc1.doi = "baz"
sc1.publicationYear = "2016"
sc1.isFirstAuthorOverridden = true
sc1.displayValue shouldBeEqualTo "fooAuth AND bar AND baz AND 2016 AND firstAuthorOverridden"
}
@Test
fun testDisplayValue_withCodesOnly() {
sc1.addCode(Code("1F", "C1F", "", false, 1, "CC1", "", 0))
sc1.addCode(Code("5H", "C5H", "", false, 5, "CC5", "", 0))
sc1.displayValue shouldBeEqualTo "1F&5H"
}
@Test
fun testDisplayValue_withSearchTermsAndCodes() {
sc1.authors = "foobar"
sc1.addCode(Code("1F", "C1F", "", false, 1, "CC1", "", 0))
sc1.addCode(Code("5H", "C5H", "", false, 5, "CC5", "", 0))
sc1.displayValue shouldBeEqualTo "foobar AND 1F&5H"
}
@Test
fun testDisplayValue_withNewsletterHeadlineOnly() {
sc1.newsletterHeadline = "foo"
sc1.displayValue shouldBeEqualTo "headline=foo"
}
@Test
fun testDisplayValue_withNewsletterTopicOnly() {
sc1.setNewsletterTopic(NewsletterTopic(1, "t1"))
sc1.displayValue shouldBeEqualTo "topic=t1"
}
@Test
fun testDisplayValue_withNewsletterIssueOnly() {
sc1.newsletterIssue = "2018/06"
sc1.displayValue shouldBeEqualTo "issue=2018/06"
}
@Test
fun testDisplayValue_withNewsletterHeadlinePlusSomethingElse() {
sc1.authors = "foobar"
sc1.newsletterHeadline = "foo"
sc1.displayValue shouldBeEqualTo "foobar AND headline=foo"
}
@Test
fun testDisplayValue_withNewsletterTopicPlusSomethingElse() {
sc1.authors = "foobar"
sc1.setNewsletterTopic(NewsletterTopic(1, "t1"))
sc1.displayValue shouldBeEqualTo "foobar AND topic=t1"
}
@Test
fun testDisplayValue_withNewsletterIssuePlusSomethingElse() {
sc1.authors = "foobar"
sc1.newsletterIssue = "2018/04"
sc1.displayValue shouldBeEqualTo "foobar AND issue=2018/04"
}
@Test
fun testDisplayValue_withAllNewsletterRelatedFields() {
sc1.newsletterHeadline = "foobar"
sc1.newsletterIssue = "2018/02"
sc1.setNewsletterTopic(NewsletterTopic(10, "t2"))
sc1.displayValue shouldBeEqualTo "issue=2018/02 AND headline=foobar AND topic=t2"
}
@Test
fun testDisplayValue_withNewsletterTopicNull_() {
sc1.newsletterHeadline = "foobar"
sc1.newsletterIssue = "2018/02"
sc1.setNewsletterTopic(null)
sc1.displayValue shouldBeEqualTo "issue=2018/02 AND headline=foobar"
}
@Test
fun equalsAndHash1_ofFieldSc() {
(sc1 == sc1).shouldBeTrue()
}
@Test
fun equalsAndHash2_withEmptySearchConditions() {
val f1 = SearchCondition()
val f2 = SearchCondition()
assertEquality(f1, f2)
}
private fun assertEquality(f1: SearchCondition, f2: SearchCondition) {
f1.hashCode() shouldBeEqualTo f2.hashCode()
((f1 == f2)).shouldBeTrue()
((f2 == f1)).shouldBeTrue()
}
@Test
fun equalsAndHash3_withSingleAttribute() {
val f1 = SearchCondition()
f1.authors = "foo"
val f2 = SearchCondition()
f2.authors = "foo"
assertEquality(f1, f2)
}
@Test
fun equalsAndHash4_withManyAttributes() {
val f1 = SearchCondition()
f1.authors = "foo"
f1.comment = "bar"
f1.publicationYear = "2014"
f1.firstAuthor = "baz"
f1.isFirstAuthorOverridden = true
f1.methodOutcome = "blup"
val f2 = SearchCondition()
f2.authors = "foo"
f2.comment = "bar"
f2.publicationYear = "2014"
f2.firstAuthor = "baz"
f2.isFirstAuthorOverridden = true
f2.methodOutcome = "blup"
assertEquality(f1, f2)
f2.methodOutcome = "blup2"
((f1 == f2)).shouldBeFalse()
f1.hashCode() shouldNotBeEqualTo f2.hashCode()
f2.methodOutcome = "blup"
f2.methodStatistics = "bloop"
((f1 == f2)).shouldBeFalse()
f1.hashCode() shouldNotBeEqualTo f2.hashCode()
}
@Test
fun equalsAndHash5_withDifferentSearchConditionIds() {
val f1 = SearchCondition()
f1.authors = "foo"
val f2 = SearchCondition()
f2.authors = "foo"
assertEquality(f1, f2)
f1.searchConditionId = 3L
f1.hashCode() shouldNotBeEqualTo f2.hashCode()
(f1 == f2).shouldBeFalse()
(f2 == f1).shouldBeFalse()
f2.searchConditionId = 4L
f1.hashCode() shouldNotBeEqualTo f2.hashCode()
(f1 == f2).shouldBeFalse()
(f2 == f1).shouldBeFalse()
f2.searchConditionId = 3L
assertEquality(f1, f2)
}
@Test
fun equalsAndHash6_withCreatedDisplayValue() {
val f1 = SearchCondition()
f1.createdDisplayValue = "foo"
val f2 = SearchCondition()
(f1 == f2).shouldBeFalse()
f2.createdDisplayValue = "foo"
assertEquality(f1, f2)
f2.createdDisplayValue = "bar"
(f1 == f2).shouldBeFalse()
f1.createdDisplayValue = null
(f2 == f1).shouldBeFalse()
}
@Test
fun equalsAndHash7_withModifiedDisplayValue() {
val f1 = SearchCondition()
f1.modifiedDisplayValue = "foo"
val f2 = SearchCondition()
(f1 == f2).shouldBeFalse()
f2.modifiedDisplayValue = "foo"
assertEquality(f1, f2)
f2.modifiedDisplayValue = "bar"
(f1 == f2).shouldBeFalse()
f1.createdDisplayValue = null
(f2 == f1).shouldBeFalse()
}
@Test
fun equalsAndHash8_withDifferentBooleanSearchTerms() {
val f1 = SearchCondition()
f1.addSearchTerm(SearchTerm.newBooleanSearchTerm("f1", "false"))
val f2 = SearchCondition()
f2.addSearchTerm(SearchTerm.newBooleanSearchTerm("f1", "true"))
assertInequality(f1, f2)
}
private fun assertInequality(f1: SearchCondition, f2: SearchCondition) {
(f1 == f2).shouldBeFalse()
(f2 == f1).shouldBeFalse()
f1.hashCode() shouldNotBeEqualTo f2.hashCode()
}
@Test
fun equalsAndHash8_withDifferentIntegerSearchTerms() {
val f1 = SearchCondition()
f1.addSearchTerm(SearchTerm.newIntegerSearchTerm("f1", "1"))
val f2 = SearchCondition()
f2.addSearchTerm(SearchTerm.newIntegerSearchTerm("f1", "2"))
assertInequality(f1, f2)
}
@Test
fun equalsAndHash9_withDifferentStringSearchTerms() {
val f1 = SearchCondition()
f1.addSearchTerm(SearchTerm.newStringSearchTerm("f1", "foo"))
val f2 = SearchCondition()
f2.addSearchTerm(SearchTerm.newStringSearchTerm("f1", "bar"))
assertInequality(f1, f2)
}
@Test
fun equalsAndHash10_withDifferentStringAuditTerms() {
val f1 = SearchCondition()
f1.addSearchTerm(SearchTerm.newAuditSearchTerm("f1", "foo"))
val f2 = SearchCondition()
f2.addSearchTerm(SearchTerm.newAuditSearchTerm("f1", "bar"))
assertInequality(f1, f2)
}
@Test
fun equalsAndHash11_withDifferentCodes() {
val f1 = SearchCondition()
f1.addCode(Code("1F", "C1F", "", false, 1, "CC1", "", 0))
val f2 = SearchCondition()
f2.addCode(Code("1G", "C1G", "", false, 1, "CC1", "", 0))
assertInequality(f1, f2)
}
@Test
fun equalsAndHash12_withDifferentNewsletterTopics_notDifferent() {
val f1 = SearchCondition()
f1.setNewsletterTopic(NewsletterTopic(1, "foo"))
val f2 = SearchCondition()
f2.setNewsletterTopic(NewsletterTopic(2, "foo"))
assertEquality(f1, f2)
}
@Test
fun equalsAndHash13_withDifferentNewsletterHeadlines_notDifferent() {
val f1 = SearchCondition()
f1.newsletterHeadline = "foo"
val f2 = SearchCondition()
f2.newsletterHeadline = "bar"
assertEquality(f1, f2)
}
@Test
fun equalsAndHash14_withDifferentNewsletterIssue_notDifferent() {
val f1 = SearchCondition()
f1.newsletterIssue = "foo"
val f2 = SearchCondition()
f2.newsletterIssue = "bar"
assertEquality(f1, f2)
}
@Test
fun equalsAndHash15_withDifferentNewsletterTopics_firstNull_notDifferent() {
val f1 = SearchCondition()
f1.setNewsletterTopic(null)
val f2 = SearchCondition()
f2.setNewsletterTopic(NewsletterTopic(2, "foo"))
assertEquality(f1, f2)
}
@Test
fun equalsAndHash16_withDifferentNewsletterHeadlines_firstNull_notDifferent() {
val f1 = SearchCondition()
f1.newsletterHeadline = null
val f2 = SearchCondition()
f2.newsletterHeadline = "bar"
assertEquality(f1, f2)
}
@Test
fun equalsAndHash17_withDifferentNewsletterIssue_firstNull_notDifferent() {
val f1 = SearchCondition()
f1.newsletterIssue = null
val f2 = SearchCondition()
f2.newsletterIssue = "bar"
assertEquality(f1, f2)
}
@Test
fun newSearchCondition_hasEmptyRemovedKeys() {
SearchCondition().removedKeys.shouldBeEmpty()
}
@Test
fun addingSearchTerms_leavesRemovedKeysEmpty() {
sc2.authors = "foo"
sc2.publicationYear = "2014"
sc2.isFirstAuthorOverridden = true
sc2.removedKeys.shouldBeEmpty()
}
@Test
fun removingSearchTerms_addsThemToRemovedKeys() {
sc2.authors = "foo"
sc2.publicationYear = "2014"
sc2.goals = "bar"
sc2.publicationYear = null
sc2.removedKeys shouldContainSame listOf("publicationYear")
}
@Test
fun addingSearchTerm_afterRemovingIt_removesItFromRemovedKeys() {
sc2.publicationYear = "2014"
sc2.publicationYear = null
sc2.publicationYear = "2015"
sc2.removedKeys.shouldBeEmpty()
}
@Test
fun clearingRemovedKeys_removesAllPresent() {
sc1.authors = "foo"
sc1.authors = null
sc1.publicationYear = "2014"
sc1.publicationYear = null
sc1.removedKeys shouldHaveSize 2
sc1.clearRemovedKeys()
sc1.removedKeys.shouldBeEmpty()
}
@Test
fun addingBooleanSearchTerm() {
sc2.addSearchTerm(SearchTerm.newBooleanSearchTerm("fn", "rst"))
sc2.booleanSearchTerms shouldHaveSize 1
sc2.integerSearchTerms.shouldBeEmpty()
sc2.stringSearchTerms.shouldBeEmpty()
sc2.auditSearchTerms.shouldBeEmpty()
}
@Test
fun addingIntegerTerm() {
sc2.addSearchTerm(SearchTerm.newIntegerSearchTerm("fn", "1"))
sc2.booleanSearchTerms.shouldBeEmpty()
sc2.integerSearchTerms shouldHaveSize 1
sc2.stringSearchTerms.shouldBeEmpty()
sc2.auditSearchTerms.shouldBeEmpty()
}
@Test
fun addingStringSearchTerm() {
sc1.addSearchTerm(SearchTerm.newStringSearchTerm("fn", "rst"))
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.stringSearchTerms shouldHaveSize 1
sc1.auditSearchTerms.shouldBeEmpty()
}
@Test
fun addingAuditSearchTerm() {
sc2.addSearchTerm(SearchTerm.newAuditSearchTerm("fn", "rst"))
sc2.booleanSearchTerms.shouldBeEmpty()
sc2.integerSearchTerms.shouldBeEmpty()
sc2.stringSearchTerms.shouldBeEmpty()
sc2.auditSearchTerms shouldHaveSize 1
}
@Test
fun addingUnsupportedSearchTerm() {
val stMock = mockk<SearchTerm> {
every { searchTermType } returns SearchTermType.UNSUPPORTED
}
invoking { sc2.addSearchTerm(stMock) } shouldThrow AssertionError::class withMessage "SearchTermType.UNSUPPORTED is not supported"
}
@Test
fun addingCodes() {
val c1 = Code("c1", "c1", "", false, 1, "cc1", "", 0)
val c2 = Code("c2", "c2", "", false, 2, "cc2", "", 0)
val c3 = Code("c3", "c3", "", false, 3, "cc3", "", 0)
val c4 = Code("c4", "c4", "", false, 3, "cc3", "", 0)
sc2.addCodes(listOf(c1, c2, c3, c4))
sc2.codes shouldHaveSize 4
sc2.getCodesOf(CodeClassId.CC3) shouldContainAll listOf(c3, c4)
sc2.clearCodesOf(CodeClassId.CC3)
sc2.codes shouldHaveSize 2
sc2.clearCodes()
sc2.codes.shouldBeEmpty()
}
@Test
fun settingAndResettingNewsletterHeadline() {
sc1.newsletterHeadline.shouldBeNull()
sc1.newsletterHeadline = "foo"
sc1.newsletterHeadline shouldBeEqualTo "foo"
sc1.newsletterHeadline = null
sc1.newsletterHeadline.shouldBeNull()
}
@Test
fun settingAndResettingNewsletterTopic() {
sc1.newsletterTopicId.shouldBeNull()
sc1.setNewsletterTopic(NewsletterTopic(1, "tp1"))
sc1.newsletterTopicId shouldBeEqualTo 1
sc1.setNewsletterTopic(null)
sc1.newsletterTopicId.shouldBeNull()
}
@Test
fun settingAndResettingNewsletterIssue() {
sc1.newsletterIssue.shouldBeNull()
sc1.newsletterIssue = "foo"
sc1.newsletterIssue shouldBeEqualTo "foo"
sc1.newsletterIssue = null
sc1.newsletterIssue.shouldBeNull()
}
@Test
fun hasAttachments() {
sc1.hasAttachments.shouldBeNull()
sc1.hasAttachments = true
sc1.hasAttachments?.shouldBeTrue() ?: fail("should not be null")
sc1.hasAttachments = false
sc1.hasAttachments?.shouldBeFalse() ?: fail("should not be null")
sc1.hasAttachments = null
sc1.hasAttachments.shouldBeNull()
}
@Test
fun attachmentNameMas() {
sc1.attachmentNameMask.shouldBeNull()
sc1.attachmentNameMask = "foo"
sc1.attachmentNameMask shouldBeEqualTo "foo"
sc1.attachmentNameMask = null
sc1.attachmentNameMask.shouldBeNull()
}
}
| core/core-entity/src/test/kotlin/ch/difty/scipamato/core/entity/search/SearchConditionTest.kt | 1749799335 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.history
import com.intellij.openapi.util.registry.Registry
data class GitCommitRequirements(private val includeRootChanges: Boolean = true,
val diffRenameLimit: DiffRenameLimit = DiffRenameLimit.GIT_CONFIG,
val diffInMergeCommits: DiffInMergeCommits = DiffInMergeCommits.COMBINED_DIFF) {
fun configParameters(): List<String> {
val result = mutableListOf<String>()
when (diffRenameLimit) {
DiffRenameLimit.INFINITY -> result.add(renameLimit(0))
DiffRenameLimit.REGISTRY -> result.add(renameLimit(Registry.intValue("git.diff.renameLimit")))
DiffRenameLimit.NO_RENAMES -> result.add("diff.renames=false")
else -> {
}
}
if (!includeRootChanges) {
result.add("log.showRoot=false")
}
return result
}
fun commandParameters(): List<String> {
val result = mutableListOf<String>()
if (diffRenameLimit != DiffRenameLimit.NO_RENAMES) {
result.add("-M")
}
when (diffInMergeCommits) {
DiffInMergeCommits.DIFF_TO_PARENTS -> result.add("-m")
DiffInMergeCommits.COMBINED_DIFF -> result.add("-c")
DiffInMergeCommits.NO_DIFF -> {
}
}
return result
}
private fun renameLimit(limit: Int): String {
return "diff.renameLimit=$limit"
}
enum class DiffRenameLimit {
/**
* Use zero value
*/
INFINITY,
/**
* Use value set in registry (usually 1000)
*/
REGISTRY,
/**
* Use value set in users git.config
*/
GIT_CONFIG,
/**
* Disable renames detection
*/
NO_RENAMES
}
enum class DiffInMergeCommits {
/**
* Do not report changes for merge commits
*/
NO_DIFF,
/**
* Report combined changes (same as `git log -c`)
*/
COMBINED_DIFF,
/**
* Report changes to all of the parents (same as `git log -m`)
*/
DIFF_TO_PARENTS
}
companion object {
@JvmField
val DEFAULT = GitCommitRequirements()
}
}
| plugins/git4idea/src/git4idea/history/GitCommitRequirements.kt | 2667235826 |
/*
* Copyright 2018 New Vector Ltd
*
* 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.matrix.androidsdk.crypto.model.keys
import com.google.gson.JsonElement
import com.google.gson.annotations.SerializedName
import org.matrix.androidsdk.core.JsonUtility
import org.matrix.androidsdk.crypto.keysbackup.MegolmBackupAuthData
/**
* <pre>
* Example:
*
* {
* "algorithm": "m.megolm_backup.v1.curve25519-aes-sha2",
* "auth_data": {
* "public_key": "abcdefg",
* "signatures": {
* "something": {
* "ed25519:something": "hijklmnop"
* }
* }
* }
* }
* </pre>
*/
open class KeysAlgorithmAndData {
/**
* The algorithm used for storing backups. Currently, only "m.megolm_backup.v1.curve25519-aes-sha2" is defined
*/
var algorithm: String? = null
/**
* algorithm-dependent data, for "m.megolm_backup.v1.curve25519-aes-sha2" see [org.matrix.androidsdk.crypto.keysbackup.MegolmBackupAuthData]
*/
@SerializedName("auth_data")
var authData: JsonElement? = null
/**
* Facility method to convert authData to a MegolmBackupAuthData object
*/
fun getAuthDataAsMegolmBackupAuthData() = JsonUtility.getBasicGson()
.fromJson(authData, MegolmBackupAuthData::class.java)
}
| matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/model/keys/KeysAlgorithmAndData.kt | 3872517133 |
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
// This file was automatically generated from select-expression.md by Knit tool. Do not edit.
package kotlinx.coroutines.guide.exampleSelect05
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*
fun CoroutineScope.switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String> {
var current = input.receive() // start with first received deferred value
while (isActive) { // loop while not cancelled/closed
val next = select<Deferred<String>?> { // return next deferred value from this select or null
input.onReceiveCatching { update ->
update.getOrNull()
}
current.onAwait { value ->
send(value) // send value that current deferred has produced
input.receiveCatching().getOrNull() // and use the next deferred from the input channel
}
}
if (next == null) {
println("Channel was closed")
break // out of loop
} else {
current = next
}
}
}
fun CoroutineScope.asyncString(str: String, time: Long) = async {
delay(time)
str
}
fun main() = runBlocking<Unit> {
val chan = Channel<Deferred<String>>() // the channel for test
launch { // launch printing coroutine
for (s in switchMapDeferreds(chan))
println(s) // print each received string
}
chan.send(asyncString("BEGIN", 100))
delay(200) // enough time for "BEGIN" to be produced
chan.send(asyncString("Slow", 500))
delay(100) // not enough time to produce slow
chan.send(asyncString("Replace", 100))
delay(500) // give it time before the last one
chan.send(asyncString("END", 500))
delay(1000) // give it time to process
chan.close() // close the channel ...
delay(500) // and wait some time to let it finish
}
| kotlinx-coroutines-core/jvm/test/guide/example-select-05.kt | 4269629799 |
package org.http4k.contract
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.core.Filter
import org.http4k.core.Method.GET
import org.http4k.core.Method.OPTIONS
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.core.Status.Companion.UNAUTHORIZED
import org.http4k.core.then
import org.http4k.core.with
import org.http4k.format.Argo
import org.http4k.lens.Header
import org.http4k.lens.Header.X_URI_TEMPLATE
import org.http4k.lens.Path
import org.http4k.lens.Query
import org.http4k.routing.bind
import org.http4k.routing.routes
import org.junit.Test
class ContractRoutingHttpHandlerTest {
private val header = Header.optional("FILTER")
@Test
fun `by default the description lives at the route`() {
Request(GET, "/root")
val response = ("/root" bind contract(SimpleJson(Argo))).invoke(Request(GET, "/root"))
assertThat(response.status, equalTo(OK))
assertThat(response.bodyString(), equalTo("""{"resources":{}}"""))
}
@Test
fun `passes through contract filter`() {
val filter = Filter { next ->
{ next(it.with(header of "true")) }
}
val root = "/root" bind contract(SimpleJson(Argo), "/docs",
"/" bindContract GET to { Response(OK).with(header of header(it)) })
val withRoute = filter.then(root)
val response = withRoute(Request(GET, "/root"))
assertThat(response.status, equalTo(OK))
assertThat(header(response), equalTo("true"))
}
@Test
fun `traffic goes to the path specified`() {
val root = org.http4k.routing.routes(
"/root/bar" bind contract(
"/foo/bar" / Path.of("world") bindContract GET to { _ -> { Response(OK).with(X_URI_TEMPLATE of X_URI_TEMPLATE(it)) } })
)
val response = root(Request(GET, "/root/bar/foo/bar/hello"))
assertThat(response.status, equalTo(OK))
assertThat(X_URI_TEMPLATE(response), equalTo("/root/bar/foo/bar/{world}"))
}
@Test
fun `identifies called route using identity header on request`() {
val root = org.http4k.routing.routes(
"/root" bind contract(
Path.fixed("hello") / Path.of("world") bindContract GET to { _, _ -> { Response(OK).with(X_URI_TEMPLATE of X_URI_TEMPLATE(it)) } })
)
val response = root(Request(GET, "/root/hello/planet"))
assertThat(response.status, equalTo(OK))
assertThat(X_URI_TEMPLATE(response), equalTo("/root/hello/{world}"))
}
@Test
fun `applies security and responds with a 401 to unauthorized requests`() {
val root = "/root" bind contract(SimpleJson(Argo), "", ApiKey(Query.required("key"), { it == "bob" }),
"/bob" bindContract GET to { Response(OK) }
)
val response = root(Request(GET, "/root/bob?key=sue"))
assertThat(response.status, equalTo(UNAUTHORIZED))
}
@Test
fun `applies security and responds with a 200 to authorized requests`() {
val root = "/root" bind contract(SimpleJson(Argo), "", ApiKey(Query.required("key"), { it == "bob" }),
"/bob" bindContract GET to { Response(OK) }
)
val response = root(Request(GET, "/root/bob?key=bob"))
assertThat(response.status, equalTo(OK))
}
@Test
fun `can change path to description route`() {
val response = ("/root/foo" bind contract(SimpleJson(Argo), "/docs/swagger.json"))
.invoke(Request(GET, "/root/foo/docs/swagger.json"))
assertThat(response.status, equalTo(OK))
}
@Test
fun `only calls filters once`() {
val filter = Filter { next ->
{
next(it.header("foo", "bar"))
}
}
val contract = contract(
"/test"
bindContract GET to
{ Response(OK).body(it.headerValues("foo").toString()) })
val withFilter = filter.then(contract)
val response = withFilter(Request(GET, "/test"))
assertThat(response.status, equalTo(OK))
assertThat(response.bodyString(), equalTo("[bar]"))
}
@Test
fun `only calls filters once - in various combos`() {
var called = false
val filter = Filter {
{ req: Request ->
assertThat(called, equalTo(false))
called = true
it(req)
}
}
var calledHandler = false
val contract = contract(
"/test" bindContract GET to {
assertThat(calledHandler, equalTo(false))
calledHandler = true
Response(OK)
})
val request = Request(OPTIONS, "/test")
(filter.then("/" bind contract))(request)
(filter.then(contract))(request)
(org.http4k.routing.routes(filter.then(contract)))(request)
(filter.then(routes(contract)))(request)
}
}
| http4k-contract/src/test/kotlin/org/http4k/contract/ContractRoutingHttpHandlerTest.kt | 2825047238 |
package org.purescript.file
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.*
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.KeyDescriptor
import org.jetbrains.annotations.NonNls
class ModuleNameIndex : ScalarIndexExtension<String>() {
override fun getName(): ID<String, Void?> {
return NAME
}
override fun getIndexer(): DataIndexer<String, Void?, FileContent> {
return DataIndexer<String, Void?, FileContent> {
when (val file = it.psiFile) {
is PSFile -> file.module?.name?.let { mapOf(it to null) }
?: emptyMap()
else -> emptyMap()
}
}
}
override fun getKeyDescriptor(): KeyDescriptor<String> =
EnumeratorStringDescriptor.INSTANCE
override fun getVersion(): Int = 0
override fun getInputFilter(): FileBasedIndex.InputFilter =
DefaultFileTypeSpecificInputFilter(PSFileType.INSTANCE)
override fun dependsOnFileContent(): Boolean = true
companion object {
@NonNls
val NAME =
ID.create<String, Void?>("org.purescript.file.ModuleNameIndex")
fun fileContainingModule(
project: Project,
moduleName: String
): PSFile? {
val fileBasedIndex = FileBasedIndex.getInstance()
return ReadAction.compute<PSFile?, Throwable> {
val files = fileBasedIndex.getContainingFiles(
NAME,
moduleName,
GlobalSearchScope.allScope(project)
)
files
//.filter { it.isValid }
.map { PsiManager.getInstance(project).findFile(it) }
.filterIsInstance(PSFile::class.java)
.firstOrNull()
}
}
fun getAllModuleNames(project: Project): List<String> {
val fileBasedIndex = FileBasedIndex.getInstance()
return fileBasedIndex.getAllKeys(NAME, project)
.filter { fileContainingModule(project, it) != null }
.toList()
}
fun getModuleNameFromFile(project: Project,file: VirtualFile) =
FileBasedIndex
.getInstance()
.getFileData(NAME, file, project)
.keys
.firstOrNull()
}
} | src/main/kotlin/org/purescript/file/ModuleNameIndex.kt | 1367355630 |
package org.purescript.features
import com.intellij.lang.cacheBuilder.DefaultWordsScanner
import com.intellij.lang.cacheBuilder.WordsScanner
import com.intellij.lang.findUsages.FindUsagesProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.tree.TokenSet
import org.purescript.lexer.PSLexer
import org.purescript.parser.ARROW
import org.purescript.parser.BACKSLASH
import org.purescript.parser.CHAR
import org.purescript.parser.COMMA
import org.purescript.parser.DARROW
import org.purescript.parser.DCOLON
import org.purescript.parser.DDOT
import org.purescript.parser.DOC_COMMENT
import org.purescript.parser.DOT
import org.purescript.parser.EQ
import org.purescript.parser.FLOAT
import org.purescript.parser.IDENT
import org.purescript.parser.LARROW
import org.purescript.parser.LDARROW
import org.purescript.parser.MLCOMMENT
import org.purescript.parser.MODULE_PREFIX
import org.purescript.parser.NATURAL
import org.purescript.parser.OPERATOR
import org.purescript.parser.OPTIMISTIC
import org.purescript.parser.PIPE
import org.purescript.parser.PROPER_NAME
import org.purescript.parser.SEMI
import org.purescript.parser.SLCOMMENT
import org.purescript.parser.STRING
import org.purescript.parser.STRING_ERROR
import org.purescript.parser.STRING_ESCAPED
import org.purescript.parser.STRING_GAP
import org.purescript.psi.PSForeignDataDeclaration
import org.purescript.psi.PSForeignValueDeclaration
import org.purescript.psi.PSModule
import org.purescript.psi.binder.PSVarBinder
import org.purescript.psi.classes.PSClassDeclaration
import org.purescript.psi.classes.PSClassMember
import org.purescript.psi.data.PSDataConstructor
import org.purescript.psi.data.PSDataDeclaration
import org.purescript.psi.declaration.PSFixityDeclaration
import org.purescript.psi.declaration.PSValueDeclaration
import org.purescript.psi.imports.PSImportAlias
import org.purescript.psi.newtype.PSNewTypeConstructor
import org.purescript.psi.newtype.PSNewTypeDeclaration
import org.purescript.psi.typesynonym.PSTypeSynonymDeclaration
class PSFindUsageProvider : FindUsagesProvider {
override fun canFindUsagesFor(psiElement: PsiElement): Boolean =
psiElement is PSValueDeclaration
|| psiElement is PSVarBinder
|| psiElement is PSModule
|| psiElement is PSForeignValueDeclaration
|| psiElement is PSNewTypeDeclaration
|| psiElement is PSNewTypeConstructor
|| psiElement is PSImportAlias
|| psiElement is PSDataDeclaration
|| psiElement is PSDataConstructor
|| psiElement is PSClassDeclaration
|| psiElement is PSTypeSynonymDeclaration
|| psiElement is PSClassMember
|| psiElement is PSFixityDeclaration
|| psiElement is PSForeignDataDeclaration
override fun getWordsScanner(): WordsScanner {
val psWordScanner = DefaultWordsScanner(
PSLexer(),
TokenSet.create(IDENT, PROPER_NAME, MODULE_PREFIX),
TokenSet.create(MLCOMMENT, SLCOMMENT, DOC_COMMENT),
TokenSet.create(
STRING,
STRING_ERROR,
STRING_ESCAPED,
STRING_GAP,
CHAR,
NATURAL,
FLOAT
),
TokenSet.EMPTY,
TokenSet.create(
OPERATOR,
ARROW,
BACKSLASH, // maybe?!
COMMA,
DARROW,
DCOLON,
DDOT,
DOT,
EQ, // maybe?!
LARROW,
LDARROW,
OPTIMISTIC,
PIPE,
SEMI,
)
)
return psWordScanner
}
override fun getHelpId(psiElement: PsiElement): String? {
return null
}
override fun getType(element: PsiElement): String {
return when (element) {
is PSValueDeclaration -> "value"
is PSVarBinder -> "parameter"
is PSModule -> "module"
is PSNewTypeDeclaration -> "newtype"
is PSNewTypeConstructor -> "newtype constructor"
is PSImportAlias -> "import alias"
is PSDataDeclaration -> "data"
is PSDataConstructor -> "data constructor"
is PSClassDeclaration -> "class"
is PSForeignValueDeclaration -> "foreign value"
is PSForeignDataDeclaration -> "foreign data"
is PSTypeSynonymDeclaration -> "type synonym"
is PSClassMember -> "class member"
is PSFixityDeclaration -> "operator"
else -> "unknown"
}
}
override fun getDescriptiveName(element: PsiElement): String {
when (element) {
is PSValueDeclaration -> {
return "${element.module?.name}.${element.name}"
}
is PsiNamedElement -> {
val name = element.name
if (name != null) {
return name
}
}
}
return ""
}
override fun getNodeText(
element: PsiElement,
useFullName: Boolean
): String {
if (useFullName) {
return getDescriptiveName(element)
} else if (element is PsiNamedElement) {
val name = element.name
if (name != null) {
return name
}
}
return ""
}
}
| src/main/kotlin/org/purescript/features/PSFindUsageProvider.kt | 624417950 |
/*
* Copyright 2015-2019 The twitlatte authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.moko256.twitlatte
/**
* Created by moko256 on 2019/07/25.
*
* @author moko256
*/
interface HasNotifiableAppBar {
fun requestAppBarCollapsed()
} | app/src/main/java/com/github/moko256/twitlatte/HasNotifiableAppBar.kt | 3873914210 |
// 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.groovy.lang.resolve.references
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrConstructorCall
import org.jetbrains.plugins.groovy.lang.resolve.api.*
class GrMapConstructorPropertyReference(element: GrArgumentLabel) : GroovyPropertyWriteReferenceBase<GrArgumentLabel>(element) {
override val receiverArgument: Argument?
get() {
val label: GrArgumentLabel = element
val namedArgument: GrNamedArgument = label.parent as GrNamedArgument // hard cast because reference must be checked before
val constructorReference: GroovyConstructorReference = requireNotNull(getConstructorReference(namedArgument))
val resolveResult: GroovyResolveResult = constructorReference.resolveClass() ?: return null
val clazz: PsiClass = resolveResult.element as? PsiClass ?: return null
val type: PsiClassType = JavaPsiFacade.getElementFactory(label.project).createType(clazz, resolveResult.substitutor)
return JustTypeArgument(type)
}
override val propertyName: String get() = requireNotNull(element.name)
override val argument: Argument? get() = (element.parent as GrNamedArgument).expression?.let(::ExpressionArgument)
companion object {
@JvmStatic
fun getConstructorReference(argument: GrNamedArgument): GroovyConstructorReference? {
val parent: PsiElement? = argument.parent
if (parent is GrListOrMap) {
return parent.constructorReference
}
else if (parent is GrArgumentList) {
val grandParent: PsiElement? = parent.getParent()
if (grandParent is GrConstructorCall) {
return grandParent.constructorReference
}
}
return null
}
}
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/references/GrMapConstructorPropertyReference.kt | 2137210430 |
package slatekit.http
import okhttp3.Response
import slatekit.results.*
import slatekit.results.builders.Notices
import slatekit.results.builders.Outcomes
import slatekit.results.builders.Tries
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
suspend fun awaitHttp(callback: (HttpRPC.HttpRPCResult) -> Unit ) : Response {
return suspendCoroutine { cont ->
callback(object : HttpRPC.HttpRPCResult {
override fun onSuccess(result: Response) = cont.resume(result)
override fun onFailure(e: Exception?) {
e?.let { cont.resumeWithException(it) }
}
})
}
}
suspend fun awaitHttpTry(callback: (HttpRPC.HttpRPCResult) -> Unit ) : Result<Response,Exception> {
return suspendCoroutine { cont ->
callback(object : HttpRPC.HttpRPCResult {
override fun onSuccess(result: Response) = cont.resume(Success(result))
override fun onFailure(e: Exception?) {
e?.let { cont.resume(Failure(e, Codes.ERRORED)) }
}
})
}
}
suspend fun awaitHttpOutcome(callback: (HttpRPC.HttpRPCResult) -> Unit ) : Outcome<Response> {
return suspendCoroutine { cont ->
callback(object : HttpRPC.HttpRPCResult {
override fun onSuccess(result: Response) {
cont.resume(Outcomes.success(result))
}
override fun onFailure(e: Exception?) {
e?.let { cont.resume(Outcomes.errored(e)) }
}
})
}
}
suspend fun awaitHttpNotice(callback: (HttpRPC.HttpRPCResult) -> Unit ) : Notice<Response> {
return suspendCoroutine { cont ->
callback(object : HttpRPC.HttpRPCResult {
override fun onSuccess(result: Response) = cont.resume(Notices.success(result))
override fun onFailure(e: Exception?) {
e?.let { cont.resume(Notices.errored(e)) }
}
})
}
} | src/lib/kotlin/slatekit-http/src/main/kotlin/slatekit/http/HttpCoroutine.kt | 1062453713 |
package slatekit.policy
/**
* Allows enabling/disabling of a feature/middleware.
* This is designed for use at runtime
*/
interface Toggle {
fun toggle(on: Boolean)
fun enable() = toggle(true)
fun disable() = toggle(false)
}
| src/lib/kotlin/slatekit-policy/src/main/kotlin/slatekit/policy/Toggle.kt | 1996137552 |
enum class MyEnum {
O;
companion object {
val K = "K"
}
}
typealias MyAlias = MyEnum
fun box() = MyAlias.O.name + MyAlias.K | backend.native/tests/external/codegen/box/typealias/enumEntryQualifier.kt | 3199285356 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// FILE: B.java
public abstract class B<E> extends A<E> implements L<E> {
public String callIndexAdd(int x) {
add(0, null);
return null;
}
}
// FILE: main.kt
open class A<T> : Collection<T> {
override val size: Int
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
override fun contains(element: T): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun containsAll(elements: Collection<T>): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isEmpty(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun iterator(): Iterator<T> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
interface L<Q> : List<Q>
// 'add(Int; Object)' method must be present in C though it has supeclass that is subclass of List
class C<F> : B<F>() {
override fun get(index: Int): F {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun indexOf(element: F): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun lastIndexOf(element: F): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun listIterator(): ListIterator<F> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun listIterator(index: Int): ListIterator<F> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun subList(fromIndex: Int, toIndex: Int): List<F> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
fun box() = try {
C<String>().callIndexAdd(1)
throw RuntimeException("fail 1")
} catch (e: UnsupportedOperationException) {
if (e.message != "Operation is not supported for read-only collection") throw RuntimeException("fail 2")
"OK"
}
| backend.native/tests/external/codegen/box/collections/noStubsInJavaSuperClass.kt | 406199402 |
package codegen.basics.typealias1
import kotlin.test.*
@Test
fun runTest() {
println(Bar(42).x)
}
class Foo(val x: Int)
typealias Bar = Foo | backend.native/tests/codegen/basics/typealias1.kt | 1438872778 |
package com.antonio.samir.meteoritelandingsspots.data.remote
import com.antonio.samir.meteoritelandingsspots.data.repository.model.Meteorite
interface MeteoriteRemoteRepository {
suspend fun getMeteorites(offset: Int, limit: Int): List<Meteorite>
}
| app/src/main/java/com/antonio/samir/meteoritelandingsspots/data/remote/MeteoriteRemoteRepository.kt | 2868605564 |
package me.consuegra.algorithms
import org.hamcrest.CoreMatchers.`is` as iz
import org.junit.Assert.*
import org.junit.Test
class KWaveArrayTest {
val waveArray = KWaveArray()
@Test
fun testEmptyArray() {
assertThat(waveArray.wave(intArrayOf()), iz(intArrayOf()))
}
@Test
fun test1EntryArray() {
assertThat(waveArray.wave(intArrayOf(2)), iz(intArrayOf(2)))
}
@Test
fun test2EntriesArray() {
assertThat(waveArray.wave(intArrayOf(1, 2)), iz(intArrayOf(2, 1)))
}
@Test
fun testMediumArray() {
assertThat(waveArray.wave(intArrayOf(3, 1, 2, 5, 4)), iz(intArrayOf(2, 1, 4, 3, 5)))
}
} | src/test/kotlin/me/consuegra/algorithms/KWaveArrayTest.kt | 4138199308 |
// IGNORE_BACKEND: NATIVE
// FILE: A.kt
@file:[JvmName("Test") JvmMultifileClass]
val property = "K"
inline fun K(body: () -> String): String =
body() + property
// FILE: B.kt
fun box(): String {
return K { "O" }
}
| backend.native/tests/external/compileKotlinAgainstKotlin/multifileClassInlineFunctionAccessingProperty.kt | 3435248700 |
package de.sudoq.model.sudoku.sudokuTypes
import de.sudoq.model.sudoku.complexity.Complexity
import de.sudoq.model.sudoku.complexity.ComplexityConstraint
import java.util.*
/**
* Builder for Complexity constraints.
*/
class ComplexityConstraintBuilder {
var specimen: MutableMap<Complexity?, ComplexityConstraint> = HashMap()
constructor()
constructor(specimen: MutableMap<Complexity?, ComplexityConstraint>) {
this.specimen = specimen
}
fun getComplexityConstraint(complexity: Complexity?): ComplexityConstraint? {
return if (complexity != null && specimen.containsKey(complexity)) {
specimen[complexity]!!.clone() as ComplexityConstraint
} else null
}
} | sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/sudoku/sudokuTypes/ComplexityConstraintBuilder.kt | 3191627287 |
// "Create extension function 'Unit.foo'" "true"
// WITH_STDLIB
fun test() {
val a: Int = Unit.<caret>foo(2)
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createFunction/call/funOnLibObject.kt | 1785244064 |
package com.goldenpiedevs.schedule.app.ui.launcher
import com.goldenpiedevs.schedule.app.ui.base.BasePresenter
interface LauncherPresenter : BasePresenter<LauncherView> {
fun showNextScreen()
} | app/src/main/java/com/goldenpiedevs/schedule/app/ui/launcher/LauncherPresenter.kt | 1171905857 |
// FLOW: OUT
package sample
expect class ExpectClass() {
fun foo(p: Any)
}
fun f(c: ExpectClass) {
c.foo(<caret>1)
} | plugins/kotlin/idea/tests/testData/slicer/mpp/expectClassFunctionParameter/common/common.kt | 305307484 |
// WITH_STDLIB
val someList = listOf("alpha", "beta").<caret>mapIndexedNotNullTo(destination = hashSetOf()) { index, value -> index + value.length } | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/uselessCallOnCollection/MapIndexedNotNullTo.kt | 2537401229 |
// 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.openapi.externalSystem.autoimport
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType.INTERNAL
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ProjectEvent.*
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ProjectState.*
import java.util.concurrent.atomic.AtomicReference
import kotlin.math.max
class ProjectStatus(private val debugName: String? = null) {
private var state = AtomicReference(Synchronized(-1) as ProjectState)
fun isDirty() = state.get() is Dirty
fun isUpToDate() = when (state.get()) {
is Modified, is Dirty, is Broken -> false
is Synchronized, is Reverted -> true
}
fun getModificationType() = when (val state = state.get()) {
is Dirty -> state.type
is Modified -> state.type
else -> null
}
fun markBroken(stamp: Long): ProjectState {
return update(Break(stamp))
}
fun markDirty(stamp: Long, type: ModificationType = INTERNAL): ProjectState {
return update(Invalidate(stamp, type))
}
fun markModified(stamp: Long, type: ModificationType = INTERNAL): ProjectState {
return update(Modify(stamp, type))
}
fun markReverted(stamp: Long): ProjectState {
return update(Revert(stamp))
}
fun markSynchronized(stamp: Long): ProjectState {
return update(Synchronize(stamp))
}
fun update(event: ProjectEvent): ProjectState {
val oldState = AtomicReference<ProjectState>()
val newState = state.updateAndGet { currentState ->
oldState.set(currentState)
when (currentState) {
is Synchronized -> when (event) {
is Synchronize -> event.withFuture(currentState, ::Synchronized)
is Invalidate -> event.ifFuture(currentState) { Dirty(it, event.type) }
is Modify -> event.ifFuture(currentState) { Modified(it, event.type) }
is Revert -> event.ifFuture(currentState, ::Reverted)
is Break -> event.ifFuture(currentState, ::Broken)
}
is Dirty -> when (event) {
is Synchronize -> event.ifFuture(currentState, ::Synchronized)
is Invalidate -> event.withFuture(currentState) { Dirty(it, currentState.type.merge(event.type)) }
is Modify -> event.withFuture(currentState) { Dirty(it, currentState.type.merge(event.type)) }
is Revert -> event.withFuture(currentState) { Dirty(it, currentState.type) }
is Break -> event.withFuture(currentState) { Dirty(it, currentState.type) }
}
is Modified -> when (event) {
is Synchronize -> event.ifFuture(currentState, ::Synchronized)
is Invalidate -> event.withFuture(currentState) { Dirty(it, currentState.type.merge(event.type)) }
is Modify -> event.withFuture(currentState) { Modified(it, currentState.type.merge(event.type)) }
is Revert -> event.ifFuture(currentState, ::Reverted)
is Break -> event.withFuture(currentState) { Dirty(it, currentState.type) }
}
is Reverted -> when (event) {
is Synchronize -> event.ifFuture(currentState, ::Synchronized)
is Invalidate -> event.withFuture(currentState) { Dirty(it, event.type) }
is Modify -> event.ifFuture(currentState) { Modified(it, event.type) }
is Revert -> event.withFuture(currentState, ::Reverted)
is Break -> event.ifFuture(currentState, ::Broken)
}
is Broken -> when (event) {
is Synchronize -> event.ifFuture(currentState, ::Synchronized)
is Invalidate -> event.withFuture(currentState) { Dirty(it, event.type) }
is Modify -> event.withFuture(currentState) { Dirty(it, event.type) }
is Revert -> event.withFuture(currentState, ::Broken)
is Break -> event.withFuture(currentState, ::Broken)
}
}
}
debug(newState, oldState.get(), event)
return newState
}
private fun debug(newState: ProjectState, oldState: ProjectState, event: ProjectEvent) {
if (LOG.isDebugEnabled) {
val debugPrefix = if (debugName == null) "" else "$debugName: "
LOG.debug("${debugPrefix}$oldState -> $newState by $event")
}
}
private fun ProjectEvent.withFuture(state: ProjectState, action: (Long) -> ProjectState): ProjectState {
return action(max(stamp, state.stamp))
}
private fun ProjectEvent.ifFuture(state: ProjectState, action: (Long) -> ProjectState): ProjectState {
return if (stamp > state.stamp) action(stamp) else state
}
companion object {
private val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport")
}
enum class ModificationType {
EXTERNAL, INTERNAL;
fun merge(other: ModificationType): ModificationType {
return when (this) {
INTERNAL -> INTERNAL
EXTERNAL -> other
}
}
}
sealed class ProjectEvent {
abstract val stamp: Long
data class Synchronize(override val stamp: Long) : ProjectEvent()
data class Invalidate(override val stamp: Long, val type: ModificationType) : ProjectEvent()
data class Modify(override val stamp: Long, val type: ModificationType) : ProjectEvent()
data class Revert(override val stamp: Long) : ProjectEvent()
data class Break(override val stamp: Long) : ProjectEvent()
}
sealed class ProjectState {
abstract val stamp: Long
data class Synchronized(override val stamp: Long) : ProjectState()
data class Dirty(override val stamp: Long, val type: ModificationType) : ProjectState()
data class Modified(override val stamp: Long, val type: ModificationType) : ProjectState()
data class Reverted(override val stamp: Long) : ProjectState()
data class Broken(override val stamp: Long) : ProjectState()
}
}
| platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectStatus.kt | 1061780029 |
package com.lucciola.haskellanywhereforandroidkt.console
interface Entity {
data class Haskell (
val mode: Int,
val program: String,
val result: String
) {
companion object {
const val RUNNING = -1
const val SUCCESS = 0
const val ERROR = 1
const val NETWORK = 2
}
}
}
| app/src/main/kotlin/com/lucciola/haskellanywhereforandroidkt/console/Entity.kt | 3034298567 |
class String {}
val <caret>x = "" | plugins/kotlin/idea/tests/testData/intentions/specifyTypeExplicitly/stringRedefined.kt | 940149414 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.server
import com.intellij.build.FilePosition
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.StreamUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.isDirectory
import org.jetbrains.idea.maven.buildtool.MavenSyncConsole
import org.jetbrains.idea.maven.execution.SyncBundle
import org.jetbrains.idea.maven.utils.MavenLog
import org.jetbrains.idea.maven.utils.MavenUtil
import java.io.*
import java.math.BigInteger
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFilePermissions
import java.security.MessageDigest
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
@State(name = "MavenWrapperMapping",
storages = [Storage(value = "maven.wrapper.mapping.xml", roamingType = RoamingType.PER_OS)],
category = SettingsCategory.TOOLS)
internal class MavenWrapperMapping : PersistentStateComponent<MavenWrapperMapping.State> {
internal var myState = State()
class State {
@JvmField
val mapping = ConcurrentHashMap<String, String>()
}
override fun getState() = myState
override fun loadState(state: State) {
myState.mapping.putAll(state.mapping)
}
companion object {
@JvmStatic
fun getInstance(): MavenWrapperMapping {
return ApplicationManager.getApplication().getService(MavenWrapperMapping::class.java)
}
}
}
private const val DISTS_DIR = "wrapper/dists"
internal class MavenWrapperSupport {
@Throws(IOException::class)
fun downloadAndInstallMaven(urlString: String, indicator: ProgressIndicator?): MavenDistribution {
val current = getCurrentDistribution(urlString)
if (current != null) return current
val zipFile = getZipFile(urlString)
if (!zipFile.isFile) {
val partFile = File(zipFile.parentFile, "${zipFile.name}.part-${System.currentTimeMillis()}")
indicator?.apply { text = SyncBundle.message("maven.sync.wrapper.downloading.from", urlString) }
try {
HttpRequests.request(urlString)
.forceHttps(false)
.connectTimeout(30_000)
.readTimeout(30_000)
.saveToFile(partFile, indicator)
}
catch (t: Throwable) {
if (t is ControlFlowException) throw RuntimeException(SyncBundle.message("maven.sync.wrapper.downloading.canceled"))
}
FileUtil.rename(partFile, zipFile)
}
if (!zipFile.isFile) {
throw RuntimeException(SyncBundle.message("cannot.download.zip.from", urlString))
}
val home = unpackZipFile(zipFile, indicator).canonicalFile
MavenWrapperMapping.getInstance().myState.mapping[urlString] = home.absolutePath
return LocalMavenDistribution(home.toPath(), urlString)
}
private fun unpackZipFile(zipFile: File, indicator: ProgressIndicator?): File {
unzip(zipFile, indicator)
val dirs = zipFile.parentFile.listFiles { it -> it.isDirectory }
if (dirs == null || dirs.size != 1) {
MavenLog.LOG.warn("Expected exactly 1 top level dir in Maven distribution, found: " + dirs?.asList())
throw IllegalStateException(SyncBundle.message("zip.is.not.correct", zipFile.absoluteFile))
}
val mavenHome = dirs[0]
if (!SystemInfo.isWindows) {
makeMavenBinRunnable(mavenHome)
}
return mavenHome
}
private fun makeMavenBinRunnable(mavenHome: File?) {
val mvnExe = File(mavenHome, "bin/mvn").canonicalFile
val permissions = PosixFilePermissions.fromString("rwxr-xr-x")
Files.setPosixFilePermissions(mvnExe.toPath(), permissions)
}
private fun unzip(zip: File, indicator: ProgressIndicator?) {
indicator?.apply { text = SyncBundle.message("maven.sync.wrapper.unpacking") }
val unpackDir = zip.parentFile
val destinationCanonicalPath = unpackDir.canonicalPath
var errorUnpacking = true
try {
ZipFile(zip).use { zipFile ->
val entries: Enumeration<*> = zipFile.entries()
while (entries.hasMoreElements()) {
val entry = entries.nextElement() as ZipEntry
val destFile = File(unpackDir, entry.name)
val canonicalPath = destFile.canonicalPath
if (!canonicalPath.startsWith(destinationCanonicalPath)) {
FileUtil.delete(zip)
throw RuntimeException("Directory traversal attack detected, zip file is malicious and IDEA dropped it")
}
if (entry.isDirectory) {
destFile.mkdirs()
}
else {
destFile.parentFile.mkdirs()
BufferedOutputStream(FileOutputStream(destFile)).use {
StreamUtil.copy(zipFile.getInputStream(entry), it)
}
}
}
}
errorUnpacking = false
indicator?.apply { text = SyncBundle.message("maven.sync.wrapper.unpacked.into", destinationCanonicalPath) }
}
finally {
if (errorUnpacking) {
indicator?.apply { text = SyncBundle.message("maven.sync.wrapper.failure") }
zip.parentFile.listFiles { it -> it.name != zip.name }?.forEach { FileUtil.delete(it) }
}
}
}
private fun getZipFile(distributionUrl: String): File {
val baseName: String = getDistName(distributionUrl)
val distName: String = FileUtil.getNameWithoutExtension(baseName)
val md5Hash: String = getMd5Hash(distributionUrl)
val m2dir = MavenUtil.resolveM2Dir()
val distsDir = File(m2dir, DISTS_DIR)
return File(File(File(distsDir, distName), md5Hash), baseName).absoluteFile
}
private fun getDistName(distUrl: String): String {
val p = distUrl.lastIndexOf("/")
return if (p < 0) distUrl else distUrl.substring(p + 1)
}
private fun getMd5Hash(string: String): String {
return try {
val messageDigest = MessageDigest.getInstance("MD5")
val bytes = string.toByteArray()
messageDigest.update(bytes)
BigInteger(1, messageDigest.digest()).toString(32)
}
catch (var4: Exception) {
throw RuntimeException("Could not hash input string.", var4)
}
}
companion object {
val DISTRIBUTION_URL_PROPERTY = "distributionUrl"
@JvmStatic
fun getWrapperDistributionUrl(baseDir: VirtualFile?): String? {
val wrapperProperties = getWrapperProperties(baseDir) ?: return null
val properties = Properties()
val stream = ByteArrayInputStream(wrapperProperties.contentsToByteArray(true))
properties.load(stream)
return properties.getProperty(DISTRIBUTION_URL_PROPERTY)
}
@JvmStatic
fun showUnsecureWarning(console: MavenSyncConsole, mavenProjectMultimodulePath: VirtualFile?) {
val properties = getWrapperProperties(mavenProjectMultimodulePath)
val line = properties?.inputStream?.bufferedReader(properties.charset)?.readLines()?.indexOfFirst {
it.startsWith(DISTRIBUTION_URL_PROPERTY)
} ?: -1
val position = properties?.let { FilePosition(it.toNioPath().toFile(), line, 0) }
console.addWarning(SyncBundle.message("maven.sync.wrapper.http.title"),
SyncBundle.message("maven.sync.wrapper.http.description"),
position)
}
@JvmStatic
fun getCurrentDistribution(urlString: String): MavenDistribution? {
val mapping = MavenWrapperMapping.getInstance()
val cachedHome = mapping.myState.mapping.get(urlString)
if (cachedHome != null) {
val path = Path.of(cachedHome)
if (path.isDirectory()) {
return LocalMavenDistribution(path, urlString)
}
else {
mapping.myState.mapping.remove(urlString)
}
}
return null
}
@JvmStatic
fun getWrapperProperties(baseDir: VirtualFile?) =
baseDir?.findChild(".mvn")?.findChild("wrapper")?.findChild("maven-wrapper.properties")
}
} | plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenWrapperSupport.kt | 4090748004 |
// "Change type of 'f' to '(Delegates) -> Unit'" "true"
// WITH_STDLIB
fun foo() {
var f: Int = { x: kotlin.properties.Delegates -> }<caret>
} | plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/propertyTypeMismatchLongNameRuntime.kt | 1308207902 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.notification.impl
import com.intellij.UtilBundle
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.ui.LafManagerListener
import com.intellij.idea.ActionsBundle
import com.intellij.notification.ActionCenter
import com.intellij.notification.EventLog
import com.intellij.notification.LogModel
import com.intellij.notification.Notification
import com.intellij.notification.impl.ui.NotificationsUtil
import com.intellij.notification.impl.widget.IdeNotificationArea
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Divider
import com.intellij.openapi.ui.NullableComponent
import com.intellij.openapi.ui.OnePixelDivider
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.openapi.util.Clock
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.*
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBOptionButton
import com.intellij.ui.components.JBPanel
import com.intellij.ui.components.JBPanelWithEmptyText
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.labels.LinkListener
import com.intellij.ui.components.panels.HorizontalLayout
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.ui.content.ContentFactory
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.Alarm
import com.intellij.util.text.DateFormatUtil
import com.intellij.util.ui.*
import org.jetbrains.annotations.Nls
import java.awt.*
import java.awt.event.*
import java.util.*
import java.util.function.Consumer
import javax.accessibility.AccessibleContext
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.event.HyperlinkEvent
import javax.swing.event.PopupMenuEvent
import javax.swing.text.JTextComponent
internal class NotificationsToolWindowFactory : ToolWindowFactory, DumbAware {
companion object {
const val ID = "Notifications"
internal const val CLEAR_ACTION_ID = "ClearAllNotifications"
internal val myModel = ApplicationNotificationModel()
fun addNotification(project: Project?, notification: Notification) {
if (ActionCenter.isEnabled() && notification.canShowFor(project) && NotificationsConfigurationImpl.getSettings(
notification.groupId).isShouldLog) {
myModel.addNotification(project, notification)
}
}
fun expire(notification: Notification) {
myModel.expire(notification)
}
fun expireAll() {
myModel.expireAll()
}
fun clearAll(project: Project?) {
myModel.clearAll(project)
}
fun getStateNotifications(project: Project) = myModel.getStateNotifications(project)
fun getNotifications(project: Project?) = myModel.getNotifications(project)
}
override fun isApplicable(project: Project) = ActionCenter.isEnabled()
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
NotificationContent(project, toolWindow)
}
}
internal class NotificationContent(val project: Project,
private val toolWindow: ToolWindow) : Disposable, ToolWindowManagerListener {
private val myMainPanel = JBPanelWithEmptyText(BorderLayout())
private val myNotifications = ArrayList<Notification>()
private val myIconNotifications = ArrayList<Notification>()
private val suggestions: NotificationGroupComponent
private val timeline: NotificationGroupComponent
private val searchController: SearchController
private val singleSelectionHandler = SingleTextSelectionHandler()
private var myVisible = true
private val mySearchUpdateAlarm = Alarm()
init {
myMainPanel.background = NotificationComponent.BG_COLOR
setEmptyState()
handleFocus()
suggestions = NotificationGroupComponent(this, true, project)
timeline = NotificationGroupComponent(this, false, project)
searchController = SearchController(this, suggestions, timeline)
myMainPanel.add(createSearchComponent(toolWindow), BorderLayout.NORTH)
createGearActions()
val splitter = MySplitter()
splitter.firstComponent = suggestions
splitter.secondComponent = timeline
myMainPanel.add(splitter)
suggestions.setRemoveCallback(Consumer(::remove))
timeline.setClearCallback(::clear)
Disposer.register(toolWindow.disposable, this)
val content = ContentFactory.getInstance().createContent(myMainPanel, "", false)
content.preferredFocusableComponent = myMainPanel
val contentManager = toolWindow.contentManager
contentManager.addContent(content)
contentManager.setSelectedContent(content)
project.messageBus.connect(toolWindow.disposable).subscribe(ToolWindowManagerListener.TOPIC, this)
ApplicationManager.getApplication().messageBus.connect(toolWindow.disposable).subscribe(LafManagerListener.TOPIC, LafManagerListener {
suggestions.updateLaf()
timeline.updateLaf()
})
val newNotifications = ArrayList<Notification>()
NotificationsToolWindowFactory.myModel.registerAndGetInitNotifications(this, newNotifications)
for (notification in newNotifications) {
add(notification)
}
}
private fun createSearchComponent(toolWindow: ToolWindow): SearchTextField {
val searchField = object : SearchTextField() {
override fun updateUI() {
super.updateUI()
textEditor?.border = null
}
override fun preprocessEventForTextField(event: KeyEvent): Boolean {
if (event.keyCode == KeyEvent.VK_ESCAPE && event.id == KeyEvent.KEY_PRESSED) {
isVisible = false
searchController.cancelSearch()
return true
}
return super.preprocessEventForTextField(event)
}
}
searchField.textEditor.border = null
searchField.border = JBUI.Borders.customLineBottom(JBColor.border())
searchField.isVisible = false
if (ExperimentalUI.isNewUI()) {
searchController.background = JBUI.CurrentTheme.ToolWindow.background()
searchField.textEditor.background = searchController.background
}
else {
searchController.background = UIUtil.getTextFieldBackground()
}
searchController.searchField = searchField
searchField.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
mySearchUpdateAlarm.cancelAllRequests()
mySearchUpdateAlarm.addRequest(searchController::doSearch, 100, ModalityState.stateForComponent(searchField))
}
})
return searchField
}
private fun createGearActions() {
val gearAction = object : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
searchController.startSearch()
}
}
val actionManager = ActionManager.getInstance()
val findAction = actionManager.getAction(IdeActions.ACTION_FIND)
if (findAction == null) {
gearAction.templatePresentation.text = ActionsBundle.actionText(IdeActions.ACTION_FIND)
}
else {
gearAction.copyFrom(findAction)
gearAction.registerCustomShortcutSet(findAction.shortcutSet, myMainPanel)
}
val group = DefaultActionGroup()
group.add(gearAction)
group.addSeparator()
val clearAction = actionManager.getAction(NotificationsToolWindowFactory.CLEAR_ACTION_ID)
if (clearAction != null) {
group.add(clearAction)
}
val markAction = actionManager.getAction("MarkNotificationsAsRead")
if (markAction != null) {
group.add(markAction)
}
(toolWindow as ToolWindowEx).setAdditionalGearActions(group)
}
fun setEmptyState() {
myMainPanel.emptyText.appendLine(IdeBundle.message("notifications.toolwindow.empty.text.first.line"))
@Suppress("DialogTitleCapitalization")
myMainPanel.emptyText.appendLine(IdeBundle.message("notifications.toolwindow.empty.text.second.line"))
}
fun clearEmptyState() {
myMainPanel.emptyText.clear()
}
private fun handleFocus() {
val listener = AWTEventListener {
if (it is MouseEvent && it.id == MouseEvent.MOUSE_PRESSED && !toolWindow.isActive && UIUtil.isAncestor(myMainPanel, it.component)) {
it.component.requestFocus()
}
}
Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.MOUSE_EVENT_MASK)
Disposer.register(toolWindow.disposable, Disposable {
Toolkit.getDefaultToolkit().removeAWTEventListener(listener)
})
}
fun add(notification: Notification) {
if (!NotificationsConfigurationImpl.getSettings(notification.groupId).isShouldLog) {
return
}
if (notification.isSuggestionType) {
suggestions.add(notification, singleSelectionHandler)
}
else {
timeline.add(notification, singleSelectionHandler)
}
myNotifications.add(notification)
myIconNotifications.add(notification)
searchController.update()
setStatusMessage(notification)
updateIcon()
}
fun getStateNotifications() = ArrayList(myIconNotifications)
fun getNotifications() = ArrayList(myNotifications)
fun isEmpty() = suggestions.isEmpty() && timeline.isEmpty()
fun expire(notification: Notification?) {
if (notification == null) {
val notifications = ArrayList(myNotifications)
myNotifications.clear()
myIconNotifications.clear()
suggestions.expireAll()
timeline.expireAll()
searchController.update()
setStatusMessage(null)
updateIcon()
for (n in notifications) {
n.expire()
}
}
else {
remove(notification)
}
}
private fun remove(notification: Notification) {
if (notification.isSuggestionType) {
suggestions.remove(notification)
}
else {
timeline.remove(notification)
}
myNotifications.remove(notification)
myIconNotifications.remove(notification)
searchController.update()
setStatusMessage()
updateIcon()
}
private fun clear(notifications: List<Notification>) {
myNotifications.removeAll(notifications)
myIconNotifications.removeAll(notifications)
searchController.update()
setStatusMessage()
updateIcon()
}
fun clearAll() {
project.closeAllBalloons()
myNotifications.clear()
myIconNotifications.clear()
suggestions.clear()
timeline.clear()
searchController.update()
setStatusMessage(null)
updateIcon()
}
override fun stateChanged(toolWindowManager: ToolWindowManager) {
val visible = toolWindow.isVisible
if (myVisible != visible) {
myVisible = visible
if (visible) {
project.closeAllBalloons()
suggestions.updateComponents()
timeline.updateComponents()
}
else {
suggestions.clearNewState()
timeline.clearNewState()
myIconNotifications.clear()
updateIcon()
}
}
}
private fun updateIcon() {
toolWindow.setIcon(IdeNotificationArea.getActionCenterNotificationIcon(myIconNotifications))
LogModel.fireModelChanged()
}
private fun setStatusMessage() {
setStatusMessage(myNotifications.findLast { it.isImportant || it.isImportantSuggestion })
}
private fun setStatusMessage(notification: Notification?) {
EventLog.getLogModel(project).setStatusMessage(notification)
}
override fun dispose() {
NotificationsToolWindowFactory.myModel.unregister(this)
Disposer.dispose(mySearchUpdateAlarm)
}
fun fullRepaint() {
myMainPanel.doLayout()
myMainPanel.revalidate()
myMainPanel.repaint()
}
}
private class MySplitter : OnePixelSplitter(true, .5f) {
override fun createDivider(): Divider {
return object : OnePixelDivider(true, this) {
override fun setVisible(aFlag: Boolean) {
super.setVisible(aFlag)
setResizeEnabled(aFlag)
if (!aFlag) {
setBounds(0, 0, 0, 0)
}
}
override fun setBackground(bg: Color?) {
super.setBackground(JBColor.border())
}
}
}
}
private fun JComponent.mediumFontFunction() {
font = JBFont.medium()
val f: (JComponent) -> Unit = {
it.font = JBFont.medium()
}
putClientProperty(NotificationGroupComponent.FONT_KEY, f)
}
private fun JComponent.smallFontFunction() {
font = JBFont.smallOrNewUiMedium()
val f: (JComponent) -> Unit = {
it.font = JBFont.smallOrNewUiMedium()
}
putClientProperty(NotificationGroupComponent.FONT_KEY, f)
}
private class SearchController(private val mainContent: NotificationContent,
private val suggestions: NotificationGroupComponent,
private val timeline: NotificationGroupComponent) {
lateinit var searchField: SearchTextField
lateinit var background: Color
fun startSearch() {
searchField.isVisible = true
searchField.selectText()
searchField.requestFocus()
mainContent.clearEmptyState()
if (searchField.text.isNotEmpty()) {
doSearch()
}
}
fun doSearch() {
val query = searchField.text
if (query.isEmpty()) {
searchField.textEditor.background = background
clearSearch()
return
}
var result = false
val function: (NotificationComponent) -> Unit = {
if (it.applySearchQuery(query)) {
result = true
}
}
suggestions.iterateComponents(function)
timeline.iterateComponents(function)
searchField.textEditor.background = if (result) background else LightColors.RED
mainContent.fullRepaint()
}
fun update() {
if (searchField.isVisible && searchField.text.isNotEmpty()) {
doSearch()
}
}
fun cancelSearch() {
mainContent.setEmptyState()
clearSearch()
}
private fun clearSearch() {
val function: (NotificationComponent) -> Unit = { it.applySearchQuery(null) }
suggestions.iterateComponents(function)
timeline.iterateComponents(function)
mainContent.fullRepaint()
}
}
private class NotificationGroupComponent(private val myMainContent: NotificationContent,
private val mySuggestionType: Boolean,
private val myProject: Project) :
JBPanel<NotificationGroupComponent>(BorderLayout()), NullableComponent {
companion object {
const val FONT_KEY = "FontFunction"
}
private val myTitle = JBLabel(
IdeBundle.message(if (mySuggestionType) "notifications.toolwindow.suggestions" else "notifications.toolwindow.timeline"))
private val myList = JPanel(VerticalLayout(JBUI.scale(10)))
private val myScrollPane = object : JBScrollPane(myList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) {
override fun setupCorners() {
super.setupCorners()
border = null
}
override fun updateUI() {
super.updateUI()
border = null
}
}
private var myScrollValue = 0
private val myEventHandler = ComponentEventHandler()
private val myTimeComponents = ArrayList<JLabel>()
private val myTimeAlarm = Alarm(myProject)
private lateinit var myClearCallback: (List<Notification>) -> Unit
private lateinit var myRemoveCallback: Consumer<Notification>
init {
background = NotificationComponent.BG_COLOR
val mainPanel = JPanel(BorderLayout(0, JBUI.scale(8)))
mainPanel.isOpaque = false
mainPanel.border = JBUI.Borders.empty(8, 8, 0, 0)
add(mainPanel)
myTitle.mediumFontFunction()
myTitle.foreground = NotificationComponent.INFO_COLOR
if (mySuggestionType) {
myTitle.border = JBUI.Borders.emptyLeft(10)
mainPanel.add(myTitle, BorderLayout.NORTH)
}
else {
val panel = JPanel(BorderLayout())
panel.isOpaque = false
panel.border = JBUI.Borders.emptyLeft(10)
panel.add(myTitle, BorderLayout.WEST)
val clearAll = LinkLabel(IdeBundle.message("notifications.toolwindow.timeline.clear.all"), null) { _: LinkLabel<Unit>, _: Unit? ->
clearAll()
}
clearAll.mediumFontFunction()
clearAll.border = JBUI.Borders.emptyRight(20)
panel.add(clearAll, BorderLayout.EAST)
mainPanel.add(panel, BorderLayout.NORTH)
}
myList.isOpaque = true
myList.background = NotificationComponent.BG_COLOR
myList.border = JBUI.Borders.emptyRight(10)
myScrollPane.border = null
mainPanel.add(myScrollPane)
myScrollPane.verticalScrollBar.addAdjustmentListener {
val value = it.value
if (myScrollValue == 0 && value > 0 || myScrollValue > 0 && value == 0) {
myScrollValue = value
repaint()
}
else {
myScrollValue = value
}
}
myEventHandler.add(this)
}
fun updateLaf() {
updateComponents()
iterateComponents { it.updateLaf() }
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
if (myScrollValue > 0) {
g.color = JBColor.border()
val y = myScrollPane.y - 1
g.drawLine(0, y, width, y)
}
}
fun add(notification: Notification, singleSelectionHandler: SingleTextSelectionHandler) {
val component = NotificationComponent(myProject, notification, myTimeComponents, singleSelectionHandler)
component.setNew(true)
myList.add(component, 0)
updateLayout()
myEventHandler.add(component)
updateContent()
if (mySuggestionType) {
component.setDoNotAskHandler { forProject ->
component.myNotificationWrapper.notification!!
.setDoNotAskFor(if (forProject) myProject else null)
.also { myRemoveCallback.accept(it) }
.hideBalloon()
}
component.setRemoveCallback(myRemoveCallback)
}
}
private fun updateLayout() {
val layout = myList.layout
iterateComponents { component ->
layout.removeLayoutComponent(component)
layout.addLayoutComponent(null, component)
}
}
fun isEmpty(): Boolean {
val count = myList.componentCount
for (i in 0 until count) {
if (myList.getComponent(i) is NotificationComponent) {
return false
}
}
return true
}
fun setRemoveCallback(callback: Consumer<Notification>) {
myRemoveCallback = callback
}
fun remove(notification: Notification) {
val count = myList.componentCount
for (i in 0 until count) {
val component = myList.getComponent(i) as NotificationComponent
if (component.myNotificationWrapper.notification === notification) {
if (notification.isSuggestionType) {
component.removeFromParent()
myList.remove(i)
}
else {
component.expire()
}
break
}
}
updateContent()
}
fun setClearCallback(callback: (List<Notification>) -> Unit) {
myClearCallback = callback
}
private fun clearAll() {
myProject.closeAllBalloons()
val notifications = ArrayList<Notification>()
iterateComponents {
val notification = it.myNotificationWrapper.notification
if (notification != null) {
notifications.add(notification)
}
}
clear()
myClearCallback.invoke(notifications)
}
fun expireAll() {
if (mySuggestionType) {
clear()
}
else {
iterateComponents {
if (it.myNotificationWrapper.notification != null) {
it.expire()
}
}
updateContent()
}
}
fun clear() {
iterateComponents { it.removeFromParent() }
myList.removeAll()
updateContent()
}
fun clearNewState() {
iterateComponents { it.setNew(false) }
}
fun updateComponents() {
UIUtil.uiTraverser(this).filter(JComponent::class.java).forEach {
val value = it.getClientProperty(FONT_KEY)
if (value != null) {
(value as (JComponent) -> Unit).invoke(it)
}
}
myMainContent.fullRepaint()
}
inline fun iterateComponents(f: (NotificationComponent) -> Unit) {
val count = myList.componentCount
for (i in 0 until count) {
f.invoke(myList.getComponent(i) as NotificationComponent)
}
}
private fun updateContent() {
if (!mySuggestionType && !myTimeAlarm.isDisposed) {
myTimeAlarm.cancelAllRequests()
object : Runnable {
override fun run() {
for (timeComponent in myTimeComponents) {
timeComponent.text = formatPrettyDateTime(timeComponent.getClientProperty(NotificationComponent.TIME_KEY) as Long)
}
if (myTimeComponents.isNotEmpty() && !myTimeAlarm.isDisposed) {
myTimeAlarm.addRequest(this, 30000)
}
}
}.run()
}
myMainContent.fullRepaint()
}
private fun formatPrettyDateTime(time: Long): @NlsSafe String {
val c = Calendar.getInstance()
c.timeInMillis = Clock.getTime()
val currentYear = c[Calendar.YEAR]
val currentDayOfYear = c[Calendar.DAY_OF_YEAR]
c.timeInMillis = time
val year = c[Calendar.YEAR]
val dayOfYear = c[Calendar.DAY_OF_YEAR]
if (currentYear == year && currentDayOfYear == dayOfYear) {
return DateFormatUtil.formatTime(time)
}
val isYesterdayOnPreviousYear = currentYear == year + 1 && currentDayOfYear == 1 && dayOfYear == c.getActualMaximum(
Calendar.DAY_OF_YEAR)
val isYesterday = isYesterdayOnPreviousYear || currentYear == year && currentDayOfYear == dayOfYear + 1
if (isYesterday) {
return UtilBundle.message("date.format.yesterday")
}
return DateFormatUtil.formatDate(time)
}
override fun isVisible(): Boolean {
if (super.isVisible()) {
val count = myList.componentCount
for (i in 0 until count) {
if (myList.getComponent(i).isVisible) {
return true
}
}
}
return false
}
override fun isNull(): Boolean = !isVisible
}
private class NotificationComponent(val project: Project,
notification: Notification,
timeComponents: ArrayList<JLabel>,
val singleSelectionHandler: SingleTextSelectionHandler) :
JBPanel<NotificationComponent>() {
companion object {
val BG_COLOR: Color
get() {
if (ExperimentalUI.isNewUI()) {
return JBUI.CurrentTheme.ToolWindow.background()
}
return UIUtil.getListBackground()
}
val INFO_COLOR = JBColor.namedColor("Label.infoForeground", JBColor(Gray.x80, Gray.x8C))
internal const val NEW_COLOR_NAME = "NotificationsToolwindow.newNotification.background"
internal val NEW_DEFAULT_COLOR = JBColor(0xE6EEF7, 0x45494A)
val NEW_COLOR = JBColor.namedColor(NEW_COLOR_NAME, NEW_DEFAULT_COLOR)
val NEW_HOVER_COLOR = JBColor.namedColor("NotificationsToolwindow.newNotification.hoverBackground", JBColor(0xE6EEF7, 0x45494A))
val HOVER_COLOR = JBColor.namedColor("NotificationsToolwindow.Notification.hoverBackground", BG_COLOR)
const val TIME_KEY = "TimestampKey"
}
val myNotificationWrapper = NotificationWrapper(notification)
private var myIsNew = false
private var myHoverState = false
private val myMoreButton: Component?
private var myMorePopupVisible = false
private var myRoundColor = BG_COLOR
private lateinit var myDoNotAskHandler: (Boolean) -> Unit
private lateinit var myRemoveCallback: Consumer<Notification>
private var myMorePopup: JBPopup? = null
var myMoreAwtPopup: JPopupMenu? = null
var myDropDownPopup: JPopupMenu? = null
private var myLafUpdater: Runnable? = null
init {
isOpaque = true
background = BG_COLOR
border = JBUI.Borders.empty(10, 10, 10, 0)
layout = object : BorderLayout(JBUI.scale(7), 0) {
private var myEastComponent: Component? = null
override fun addLayoutComponent(name: String?, comp: Component) {
if (EAST == name) {
myEastComponent = comp
}
else {
super.addLayoutComponent(name, comp)
}
}
override fun layoutContainer(target: Container) {
super.layoutContainer(target)
if (myEastComponent != null && myEastComponent!!.isVisible) {
val insets = target.insets
val height = target.height - insets.bottom - insets.top
val component = myEastComponent!!
component.setSize(component.width, height)
val d = component.preferredSize
component.setBounds(target.width - insets.right - d.width, insets.top, d.width, height)
}
}
}
val iconPanel = JPanel(BorderLayout())
iconPanel.isOpaque = false
iconPanel.add(JBLabel(NotificationsUtil.getIcon(notification)), BorderLayout.NORTH)
add(iconPanel, BorderLayout.WEST)
val centerPanel = JPanel(VerticalLayout(JBUI.scale(8)))
centerPanel.isOpaque = false
centerPanel.border = JBUI.Borders.emptyRight(10)
var titlePanel: JPanel? = null
if (notification.hasTitle()) {
val titleContent = NotificationsUtil.buildHtml(notification, null, false, null, null)
val title = object : JBLabel(titleContent) {
override fun updateUI() {
val oldEditor = UIUtil.findComponentOfType(this, JEditorPane::class.java)
if (oldEditor != null) {
singleSelectionHandler.remove(oldEditor)
}
super.updateUI()
val newEditor = UIUtil.findComponentOfType(this, JEditorPane::class.java)
if (newEditor != null) {
singleSelectionHandler.add(newEditor, true)
}
}
}
try {
title.setCopyable(true)
}
catch (_: Exception) {
}
NotificationsManagerImpl.setTextAccessibleName(title, titleContent)
val editor = UIUtil.findComponentOfType(title, JEditorPane::class.java)
if (editor != null) {
singleSelectionHandler.add(editor, true)
}
if (notification.isSuggestionType) {
centerPanel.add(title)
}
else {
titlePanel = JPanel(BorderLayout())
titlePanel.isOpaque = false
titlePanel.add(title)
centerPanel.add(titlePanel)
}
}
if (notification.hasContent()) {
val textContent = NotificationsUtil.buildFullContent(notification)
val textComponent = createTextComponent(textContent)
NotificationsManagerImpl.setTextAccessibleName(textComponent, textContent)
singleSelectionHandler.add(textComponent, true)
if (!notification.hasTitle() && !notification.isSuggestionType) {
titlePanel = JPanel(BorderLayout())
titlePanel.isOpaque = false
titlePanel.add(textComponent)
centerPanel.add(titlePanel)
}
else {
centerPanel.add(textComponent)
}
}
val actions = notification.actions
val actionsSize = actions.size
val helpAction = notification.contextHelpAction
if (actionsSize > 0 || helpAction != null) {
val layout = HorizontalLayout(JBUIScale.scale(16))
val actionPanel = JPanel(if (!notification.isSuggestionType && actions.size > 1) DropDownActionLayout(layout) else layout)
actionPanel.isOpaque = false
if (notification.isSuggestionType) {
if (actionsSize > 0) {
val button = JButton(actions[0].templateText)
button.isOpaque = false
button.addActionListener {
runAction(actions[0], it.source)
}
actionPanel.add(button)
if (actionsSize == 2) {
actionPanel.add(createAction(actions[1]))
}
else if (actionsSize > 2) {
actionPanel.add(MoreAction(this, actions))
}
}
}
else {
if (actionsSize > 1 && notification.collapseDirection == Notification.CollapseActionsDirection.KEEP_RIGHTMOST) {
actionPanel.add(MyDropDownAction(this))
}
for (action in actions) {
actionPanel.add(createAction(action))
}
if (actionsSize > 1 && notification.collapseDirection == Notification.CollapseActionsDirection.KEEP_LEFTMOST) {
actionPanel.add(MyDropDownAction(this))
}
}
if (helpAction != null) {
val presentation = helpAction.templatePresentation
val helpLabel = ContextHelpLabel.create(StringUtil.defaultIfEmpty(presentation.text, ""), presentation.description)
helpLabel.foreground = UIUtil.getLabelDisabledForeground()
actionPanel.add(helpLabel)
}
if (!notification.hasTitle() && !notification.hasContent() && !notification.isSuggestionType) {
titlePanel = JPanel(BorderLayout())
titlePanel.isOpaque = false
actionPanel.add(titlePanel, HorizontalLayout.RIGHT)
}
centerPanel.add(actionPanel)
}
add(centerPanel)
if (notification.isSuggestionType) {
val group = DefaultActionGroup()
group.isPopup = true
if (NotificationsConfigurationImpl.getInstanceImpl().isRegistered(notification.groupId)) {
group.add(object : DumbAwareAction(IdeBundle.message("action.text.settings")) {
override fun actionPerformed(e: AnActionEvent) {
doShowSettings()
}
})
group.addSeparator()
}
val remindAction = RemindLaterManager.createAction(notification, DateFormatUtil.DAY)
if (remindAction != null) {
@Suppress("DialogTitleCapitalization")
group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.remind.tomorrow")) {
override fun actionPerformed(e: AnActionEvent) {
remindAction.run()
myRemoveCallback.accept(myNotificationWrapper.notification!!)
myNotificationWrapper.notification!!.hideBalloon()
}
})
}
@Suppress("DialogTitleCapitalization")
group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.dont.show.again.for.this.project")) {
override fun actionPerformed(e: AnActionEvent) {
myDoNotAskHandler.invoke(true)
}
})
@Suppress("DialogTitleCapitalization")
group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.dont.show.again")) {
override fun actionPerformed(e: AnActionEvent) {
myDoNotAskHandler.invoke(false)
}
})
val presentation = Presentation()
presentation.icon = AllIcons.Actions.More
presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, java.lang.Boolean.TRUE)
val button = object : ActionButton(group, presentation, ActionPlaces.UNKNOWN, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) {
override fun createAndShowActionGroupPopup(actionGroup: ActionGroup, event: AnActionEvent): JBPopup {
myMorePopupVisible = true
val popup = super.createAndShowActionGroupPopup(actionGroup, event)
myMorePopup = popup
popup.addListener(object : JBPopupListener {
override fun onClosed(event: LightweightWindowEvent) {
myMorePopup = null
ApplicationManager.getApplication().invokeLater {
myMorePopupVisible = false
isVisible = myHoverState
}
}
})
return popup
}
}
button.border = JBUI.Borders.emptyRight(5)
button.isVisible = false
myMoreButton = button
val eastPanel = JPanel(BorderLayout())
eastPanel.isOpaque = false
eastPanel.add(button, BorderLayout.NORTH)
add(eastPanel, BorderLayout.EAST)
setComponentZOrder(eastPanel, 0)
}
else {
val timeComponent = JBLabel(DateFormatUtil.formatPrettyDateTime(notification.timestamp))
timeComponent.putClientProperty(TIME_KEY, notification.timestamp)
timeComponent.verticalAlignment = SwingConstants.TOP
timeComponent.verticalTextPosition = SwingConstants.TOP
timeComponent.toolTipText = DateFormatUtil.formatDateTime(notification.timestamp)
timeComponent.border = JBUI.Borders.emptyRight(10)
timeComponent.smallFontFunction()
timeComponent.foreground = INFO_COLOR
timeComponents.add(timeComponent)
if (NotificationsConfigurationImpl.getInstanceImpl().isRegistered(notification.groupId)) {
val button = object: InplaceButton(IdeBundle.message("tooltip.turn.notification.off"), AllIcons.Ide.Notification.Gear,
ActionListener { doShowSettings() }) {
override fun setBounds(x: Int, y: Int, width: Int, height: Int) {
super.setBounds(x, y - 1, width, height)
}
}
button.setIcons(AllIcons.Ide.Notification.Gear, null, AllIcons.Ide.Notification.GearHover)
myMoreButton = button
val buttonWrapper = JPanel(BorderLayout())
buttonWrapper.isOpaque = false
buttonWrapper.border = JBUI.Borders.emptyRight(10)
buttonWrapper.add(button, BorderLayout.NORTH)
buttonWrapper.preferredSize = buttonWrapper.preferredSize
button.isVisible = false
val eastPanel = JPanel(BorderLayout())
eastPanel.isOpaque = false
eastPanel.add(buttonWrapper, BorderLayout.WEST)
eastPanel.add(timeComponent, BorderLayout.EAST)
titlePanel!!.add(eastPanel, BorderLayout.EAST)
}
else {
titlePanel!!.add(timeComponent, BorderLayout.EAST)
myMoreButton = null
}
}
}
private fun createAction(action: AnAction): JComponent {
return object : LinkLabel<AnAction>(action.templateText, action.templatePresentation.icon,
{ link, _action -> runAction(_action, link) }, action) {
override fun getTextColor() = JBUI.CurrentTheme.Link.Foreground.ENABLED
}
}
private fun doShowSettings() {
NotificationCollector.getInstance().logNotificationSettingsClicked(myNotificationWrapper.id, myNotificationWrapper.displayId,
myNotificationWrapper.groupId)
val configurable = NotificationsConfigurable()
ShowSettingsUtil.getInstance().editConfigurable(project, configurable, Runnable {
val runnable = configurable.enableSearch(myNotificationWrapper.groupId)
runnable?.run()
})
}
private fun runAction(action: AnAction, component: Any) {
setNew(false)
NotificationCollector.getInstance().logNotificationActionInvoked(null, myNotificationWrapper.notification!!, action,
NotificationCollector.NotificationPlace.ACTION_CENTER)
Notification.fire(myNotificationWrapper.notification!!, action, DataManager.getInstance().getDataContext(component as Component))
}
fun expire() {
closePopups()
myNotificationWrapper.notification = null
setNew(false)
for (component in UIUtil.findComponentsOfType(this, LinkLabel::class.java)) {
component.isEnabled = false
}
val dropDownAction = UIUtil.findComponentOfType(this, MyDropDownAction::class.java)
if (dropDownAction != null) {
DataManager.removeDataProvider(dropDownAction)
}
}
fun removeFromParent() {
closePopups()
for (component in UIUtil.findComponentsOfType(this, JTextComponent::class.java)) {
singleSelectionHandler.remove(component)
}
}
private fun closePopups() {
myMorePopup?.cancel()
myMoreAwtPopup?.isVisible = false
myDropDownPopup?.isVisible = false
}
private fun createTextComponent(text: @Nls String): JEditorPane {
val component = JEditorPane()
component.isEditable = false
component.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, java.lang.Boolean.TRUE)
component.contentType = "text/html"
component.isOpaque = false
component.border = null
NotificationsUtil.configureHtmlEditorKit(component, false)
if (myNotificationWrapper.notification!!.listener != null) {
component.addHyperlinkListener { e ->
val notification = myNotificationWrapper.notification
if (notification != null && e.eventType == HyperlinkEvent.EventType.ACTIVATED) {
val listener = notification.listener
if (listener != null) {
NotificationCollector.getInstance().logHyperlinkClicked(notification)
listener.hyperlinkUpdate(notification, e)
}
}
}
}
component.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, StringUtil.unescapeXmlEntities(StringUtil.stripHtml(text, " ")))
component.text = text
component.isEditable = false
if (component.caret != null) {
component.caretPosition = 0
}
myLafUpdater = Runnable {
NotificationsUtil.configureHtmlEditorKit(component, false)
component.text = text
component.revalidate()
component.repaint()
}
return component
}
fun updateLaf() {
myLafUpdater?.run()
updateColor()
}
fun setDoNotAskHandler(handler: (Boolean) -> Unit) {
myDoNotAskHandler = handler
}
fun setRemoveCallback(callback: Consumer<Notification>) {
myRemoveCallback = callback
}
fun isHover(): Boolean = myHoverState
fun setNew(state: Boolean) {
if (myIsNew != state) {
myIsNew = state
updateColor()
}
}
fun setHover(state: Boolean) {
myHoverState = state
if (myMoreButton != null) {
if (!myMorePopupVisible) {
myMoreButton.isVisible = state
}
}
updateColor()
}
private fun updateColor() {
if (myHoverState) {
if (myIsNew) {
setColor(NEW_HOVER_COLOR)
}
else {
setColor(HOVER_COLOR)
}
}
else if (myIsNew) {
if (UIManager.getColor(NEW_COLOR_NAME) != null) {
setColor(NEW_COLOR)
}
else {
setColor(NEW_DEFAULT_COLOR)
}
}
else {
setColor(BG_COLOR)
}
}
private fun setColor(color: Color) {
myRoundColor = color
repaint()
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
if (myRoundColor !== BG_COLOR) {
g.color = myRoundColor
val config = GraphicsUtil.setupAAPainting(g)
val cornerRadius = NotificationBalloonRoundShadowBorderProvider.CORNER_RADIUS.get()
g.fillRoundRect(0, 0, width, height, cornerRadius, cornerRadius)
config.restore()
}
}
fun applySearchQuery(query: String?): Boolean {
if (query == null) {
isVisible = true
return true
}
val result = matchQuery(query)
isVisible = result
return result
}
private fun matchQuery(query: @NlsSafe String): Boolean {
if (myNotificationWrapper.title.contains(query, true)) {
return true
}
val subtitle = myNotificationWrapper.subtitle
if (subtitle != null && subtitle.contains(query, true)) {
return true
}
if (myNotificationWrapper.content.contains(query, true)) {
return true
}
for (action in myNotificationWrapper.actions) {
if (action != null && action.contains(query, true)) {
return true
}
}
return false
}
}
private class MoreAction(val notificationComponent: NotificationComponent, actions: List<AnAction>) :
NotificationsManagerImpl.DropDownAction(null, null) {
val group = DefaultActionGroup()
init {
val size = actions.size
for (i in 1..size - 1) {
group.add(actions[i])
}
setListener(LinkListener { link, _ ->
val popup = NotificationsManagerImpl.showPopup(link, group)
notificationComponent.myMoreAwtPopup = popup
popup?.addPopupMenuListener(object: PopupMenuListenerAdapter() {
override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent?) {
notificationComponent.myMoreAwtPopup = null
}
})
}, null)
text = IdeBundle.message("notifications.action.more")
Notification.setDataProvider(notificationComponent.myNotificationWrapper.notification!!, this)
}
override fun getTextColor() = JBUI.CurrentTheme.Link.Foreground.ENABLED
}
private class MyDropDownAction(val notificationComponent: NotificationComponent) : NotificationsManagerImpl.DropDownAction(null, null) {
var collapseActionsDirection: Notification.CollapseActionsDirection = notificationComponent.myNotificationWrapper.notification!!.collapseDirection
init {
setListener(LinkListener { link, _ ->
val group = DefaultActionGroup()
val layout = link.parent.layout as DropDownActionLayout
for (action in layout.actions) {
if (!action.isVisible) {
group.add(action.linkData)
}
}
val popup = NotificationsManagerImpl.showPopup(link, group)
notificationComponent.myDropDownPopup = popup
popup?.addPopupMenuListener(object: PopupMenuListenerAdapter() {
override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent?) {
notificationComponent.myDropDownPopup = null
}
})
}, null)
text = notificationComponent.myNotificationWrapper.notification!!.dropDownText
isVisible = false
Notification.setDataProvider(notificationComponent.myNotificationWrapper.notification!!, this)
}
override fun getTextColor() = JBUI.CurrentTheme.Link.Foreground.ENABLED
}
private class NotificationWrapper(notification: Notification) {
val title = notification.title
val subtitle = notification.subtitle
val content = notification.content
val id = notification.id
val displayId = notification.displayId
val groupId = notification.groupId
val actions: List<String?> = notification.actions.stream().map { it.templateText }.toList()
var notification: Notification? = notification
}
private class DropDownActionLayout(layout: LayoutManager2) : FinalLayoutWrapper(layout) {
val actions = ArrayList<LinkLabel<AnAction>>()
private lateinit var myDropDownAction: MyDropDownAction
override fun addLayoutComponent(comp: Component, constraints: Any?) {
super.addLayoutComponent(comp, constraints)
add(comp)
}
override fun addLayoutComponent(name: String?, comp: Component) {
super.addLayoutComponent(name, comp)
add(comp)
}
private fun add(component: Component) {
if (component is MyDropDownAction) {
myDropDownAction = component
}
else if (component is LinkLabel<*>) {
@Suppress("UNCHECKED_CAST")
actions.add(component as LinkLabel<AnAction>)
}
}
override fun layoutContainer(parent: Container) {
val width = parent.width
myDropDownAction.isVisible = false
for (action in actions) {
action.isVisible = true
}
layout.layoutContainer(parent)
val keepRightmost = myDropDownAction.collapseActionsDirection == Notification.CollapseActionsDirection.KEEP_RIGHTMOST
val collapseStart = if (keepRightmost) 0 else actions.size - 1
val collapseDelta = if (keepRightmost) 1 else -1
var collapseIndex = collapseStart
if (parent.preferredSize.width > width) {
myDropDownAction.isVisible = true
actions[collapseIndex].isVisible = false
collapseIndex += collapseDelta
actions[collapseIndex].isVisible = false
collapseIndex += collapseDelta
layout.layoutContainer(parent)
while (parent.preferredSize.width > width && collapseIndex >= 0 && collapseIndex < actions.size) {
actions[collapseIndex].isVisible = false
collapseIndex += collapseDelta
layout.layoutContainer(parent)
}
}
}
}
private class ComponentEventHandler {
private var myHoverComponent: NotificationComponent? = null
private val myMouseHandler = object : MouseAdapter() {
override fun mouseMoved(e: MouseEvent) {
if (myHoverComponent == null) {
val component = ComponentUtil.getParentOfType(NotificationComponent::class.java, e.component)
if (component != null) {
if (!component.isHover()) {
component.setHover(true)
}
myHoverComponent = component
}
}
}
override fun mouseExited(e: MouseEvent) {
if (myHoverComponent != null) {
val component = myHoverComponent!!
if (component.isHover()) {
component.setHover(false)
}
myHoverComponent = null
}
}
}
fun add(component: Component) {
addAll(component) { c ->
c.addMouseListener(myMouseHandler)
c.addMouseMotionListener(myMouseHandler)
}
}
private fun addAll(component: Component, listener: (Component) -> Unit) {
listener.invoke(component)
if (component is JBOptionButton) {
component.addContainerListener(object : ContainerAdapter() {
override fun componentAdded(e: ContainerEvent) {
addAll(e.child, listener)
}
})
}
for (child in UIUtil.uiChildren(component)) {
addAll(child, listener)
}
}
}
internal class ApplicationNotificationModel {
private val myNotifications = ArrayList<Notification>()
private val myProjectToModel = HashMap<Project, ProjectNotificationModel>()
private val myLock = Object()
internal fun registerAndGetInitNotifications(content: NotificationContent, notifications: MutableList<Notification>) {
synchronized(myLock) {
notifications.addAll(myNotifications)
myNotifications.clear()
val model = myProjectToModel.getOrPut(content.project) { ProjectNotificationModel() }
model.registerAndGetInitNotifications(content, notifications)
}
}
internal fun unregister(content: NotificationContent) {
synchronized(myLock) {
myProjectToModel.remove(content.project)
}
}
fun addNotification(project: Project?, notification: Notification) {
val runnables = ArrayList<Runnable>()
synchronized(myLock) {
if (project == null) {
if (myProjectToModel.isEmpty()) {
myNotifications.add(notification)
}
else {
for ((_project, model) in myProjectToModel.entries) {
model.addNotification(_project, notification, myNotifications, runnables)
}
}
}
else {
val model = myProjectToModel.getOrPut(project) {
Disposer.register(project) {
synchronized(myLock) {
myProjectToModel.remove(project)
}
}
ProjectNotificationModel()
}
model.addNotification(project, notification, myNotifications, runnables)
}
}
for (runnable in runnables) {
runnable.run()
}
}
fun getStateNotifications(project: Project): List<Notification> {
synchronized(myLock) {
val model = myProjectToModel[project]
if (model != null) {
return model.getStateNotifications()
}
}
return emptyList()
}
fun getNotifications(project: Project?): List<Notification> {
synchronized(myLock) {
if (project == null) {
return ArrayList(myNotifications)
}
val model = myProjectToModel[project]
if (model == null) {
return ArrayList(myNotifications)
}
return model.getNotifications(myNotifications)
}
}
fun isEmptyContent(project: Project): Boolean {
val model = myProjectToModel[project]
return model == null || model.isEmptyContent()
}
fun expire(notification: Notification) {
val runnables = ArrayList<Runnable>()
synchronized(myLock) {
myNotifications.remove(notification)
for ((project , model) in myProjectToModel) {
model.expire(project, notification, runnables)
}
}
for (runnable in runnables) {
runnable.run()
}
}
fun expireAll() {
val notifications = ArrayList<Notification>()
val runnables = ArrayList<Runnable>()
synchronized(myLock) {
notifications.addAll(myNotifications)
myNotifications.clear()
for ((project, model) in myProjectToModel) {
model.expireAll(project, notifications, runnables)
}
}
for (runnable in runnables) {
runnable.run()
}
for (notification in notifications) {
notification.expire()
}
}
fun clearAll(project: Project?) {
synchronized(myLock) {
myNotifications.clear()
if (project != null) {
myProjectToModel[project]?.clearAll(project)
}
}
}
}
private class ProjectNotificationModel {
private val myNotifications = ArrayList<Notification>()
private var myContent: NotificationContent? = null
fun registerAndGetInitNotifications(content: NotificationContent, notifications: MutableList<Notification>) {
notifications.addAll(myNotifications)
myNotifications.clear()
myContent = content
}
fun addNotification(project: Project,
notification: Notification,
appNotifications: List<Notification>,
runnables: MutableList<Runnable>) {
if (myContent == null) {
myNotifications.add(notification)
val notifications = ArrayList(appNotifications)
notifications.addAll(myNotifications)
runnables.add(Runnable {
updateToolWindow(project, notification, notifications, false)
})
}
else {
runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.add(notification) } })
}
}
fun getStateNotifications(): List<Notification> {
if (myContent == null) {
return emptyList()
}
return myContent!!.getStateNotifications()
}
fun isEmptyContent(): Boolean {
return myContent == null || myContent!!.isEmpty()
}
fun getNotifications(appNotifications: List<Notification>): List<Notification> {
if (myContent == null) {
val notifications = ArrayList(appNotifications)
notifications.addAll(myNotifications)
return notifications
}
return myContent!!.getNotifications()
}
fun expire(project: Project, notification: Notification, runnables: MutableList<Runnable>) {
myNotifications.remove(notification)
if (myContent == null) {
runnables.add(Runnable {
updateToolWindow(project, null, myNotifications, false)
})
}
else {
runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.expire(notification) } })
}
}
fun expireAll(project: Project, notifications: MutableList<Notification>, runnables: MutableList<Runnable>) {
notifications.addAll(myNotifications)
myNotifications.clear()
if (myContent == null) {
updateToolWindow(project, null, emptyList(), false)
}
else {
runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.expire(null) } })
}
}
fun clearAll(project: Project) {
myNotifications.clear()
if (myContent == null) {
updateToolWindow(project, null, emptyList(), true)
}
else {
UIUtil.invokeLaterIfNeeded { myContent!!.clearAll() }
}
}
private fun updateToolWindow(project: Project,
stateNotification: Notification?,
notifications: List<Notification>,
closeBalloons: Boolean) {
UIUtil.invokeLaterIfNeeded {
if (project.isDisposed) {
return@invokeLaterIfNeeded
}
EventLog.getLogModel(project).setStatusMessage(stateNotification)
if (closeBalloons) {
project.closeAllBalloons()
}
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(NotificationsToolWindowFactory.ID)
toolWindow?.setIcon(IdeNotificationArea.getActionCenterNotificationIcon(notifications))
}
}
}
fun Project.closeAllBalloons() {
val ideFrame = WindowManager.getInstance().getIdeFrame(this)
val balloonLayout = ideFrame!!.balloonLayout as BalloonLayoutImpl
balloonLayout.closeAll()
}
class ClearAllNotificationsAction : DumbAwareAction(IdeBundle.message("clear.all.notifications"), null, AllIcons.Actions.GC) {
override fun update(e: AnActionEvent) {
val project = e.project
e.presentation.isEnabled = NotificationsToolWindowFactory.getNotifications(project).isNotEmpty() ||
(project != null && !NotificationsToolWindowFactory.myModel.isEmptyContent(project))
}
override fun getActionUpdateThread() = ActionUpdateThread.EDT
override fun actionPerformed(e: AnActionEvent) {
NotificationsToolWindowFactory.clearAll(e.project)
}
} | platform/platform-impl/src/com/intellij/notification/impl/NotificationsToolWindow.kt | 84133484 |
/**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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("unused")
package com.afollestad.assent.rationale
import com.afollestad.assent.AssentResult
import com.afollestad.assent.GrantResult.DENIED
import com.afollestad.assent.GrantResult.GRANTED
import com.afollestad.assent.Permission
class MockRequestResponder {
private val allow = mutableSetOf<Permission>()
private val requestLog = mutableListOf<Array<out Permission>>()
fun allow(vararg permissions: Permission) {
allow.addAll(permissions)
}
fun deny(vararg permissions: Permission) {
allow.removeAll(permissions)
}
fun reset() {
allow.clear()
requestLog.clear()
}
fun log(): List<Array<out Permission>> {
return requestLog
}
val requester: Requester = { permissions, _, _, callback ->
requestLog.add(permissions)
val grantResults = List(permissions.size) {
val permission: Permission = permissions[it]
if (allow.contains(permission)) {
GRANTED
} else {
DENIED
}
}
val result = AssentResult(
permissions.mapIndexed { index, permission ->
Pair(permission, grantResults[index])
}.toMap()
)
callback(result)
}
}
| rationales/src/test/java/com/afollestad/assent/rationale/MockRequestResponder.kt | 2583486716 |
package com.kickstarter.ui.viewholders
import android.util.Pair
import androidx.core.content.ContextCompat
import androidx.core.view.isGone
import com.kickstarter.R
import com.kickstarter.databinding.ItemRewardUnselectedCardBinding
import com.kickstarter.libs.rx.transformers.Transformers.observeForUI
import com.kickstarter.libs.utils.ViewUtils
import com.kickstarter.models.Project
import com.kickstarter.models.StoredCard
import com.kickstarter.viewmodels.RewardCardUnselectedViewHolderViewModel
class RewardCardUnselectedViewHolder(val binding: ItemRewardUnselectedCardBinding, val delegate: Delegate) : KSViewHolder(binding.root) {
interface Delegate {
fun cardSelected(storedCard: StoredCard, position: Int)
}
private val viewModel: RewardCardUnselectedViewHolderViewModel.ViewModel = RewardCardUnselectedViewHolderViewModel.ViewModel(environment())
private val ksString = requireNotNull(environment().ksString())
private val creditCardExpirationString = this.context().getString(R.string.Credit_card_expiration)
private val lastFourString = this.context().getString(R.string.payment_method_last_four)
init {
this.viewModel.outputs.expirationDate()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { setExpirationDateText(it) }
this.viewModel.outputs.expirationIsGone()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe {
this.binding.rewardCardDetailsLayout.rewardCardExpirationDate.isGone = it
}
this.viewModel.outputs.isClickable()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { this.binding.cardContainer.isClickable = it }
this.viewModel.outputs.issuerImage()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { this.binding.rewardCardDetailsLayout.rewardCardLogo.setImageResource(it) }
this.viewModel.outputs.issuer()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { this.binding.rewardCardDetailsLayout.rewardCardLogo.contentDescription = it }
this.viewModel.outputs.issuerImageAlpha()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { this.binding.rewardCardDetailsLayout.rewardCardLogo.alpha = it }
this.viewModel.outputs.lastFour()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { setLastFourText(it) }
this.viewModel.outputs.lastFourTextColor()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { this.binding.rewardCardDetailsLayout.rewardCardLastFour.setTextColor(ContextCompat.getColor(context(), it)) }
this.viewModel.outputs.notAvailableCopyIsVisible()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { ViewUtils.setGone(this.binding.cardNotAllowedWarning, !it) }
this.viewModel.outputs.notifyDelegateCardSelected()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { this.delegate.cardSelected(it.first, it.second) }
this.viewModel.outputs.retryCopyIsVisible()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { ViewUtils.setGone(this.binding.retryCardWarningLayout.retryCardWarning, !it) }
this.viewModel.outputs.selectImageIsVisible()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { ViewUtils.setInvisible(this.binding.selectImageView, !it) }
this.binding.cardContainer.setOnClickListener {
this.viewModel.inputs.cardSelected(adapterPosition)
}
}
override fun bindData(data: Any?) {
@Suppress("UNCHECKED_CAST")
val cardAndProject = requireNotNull(data) as Pair<StoredCard, Project>
this.viewModel.inputs.configureWith(cardAndProject)
}
private fun setExpirationDateText(date: String) {
this.binding.rewardCardDetailsLayout.rewardCardExpirationDate.text = this.ksString.format(
this.creditCardExpirationString,
"expiration_date", date
)
}
private fun setLastFourText(lastFour: String) {
this.binding.rewardCardDetailsLayout.rewardCardLastFour.text = this.ksString.format(
this.lastFourString,
"last_four",
lastFour
)
}
}
| app/src/main/java/com/kickstarter/ui/viewholders/RewardCardUnselectedViewHolder.kt | 2793840921 |
package com.korotyx.virtualentity.system
interface MessageProvider
{
fun getMessage() : String?
} | src/main/kotlin/com/korotyx/virtualentity/system/MessageProvider.kt | 2681272695 |
package ftl.args
import com.google.common.truth.Truth.assertThat
import ftl.args.yml.AppTestPair
import ftl.config.Device
import ftl.config.defaultAndroidConfig
import ftl.run.exception.FlankGeneralError
import ftl.run.platform.android.createAndroidTestContexts
import ftl.run.platform.android.getAndroidMatrixShards
import ftl.run.status.OutputStyle
import ftl.test.util.FlankTestRunner
import ftl.test.util.TestHelper.absolutePath
import ftl.test.util.TestHelper.assert
import ftl.test.util.TestHelper.getPath
import ftl.test.util.TestHelper.getString
import io.mockk.every
import io.mockk.mockkStatic
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.contrib.java.lang.system.SystemErrRule
import org.junit.contrib.java.lang.system.SystemOutRule
import org.junit.runner.RunWith
@RunWith(FlankTestRunner::class)
class AndroidArgsFileTest {
@get:Rule
val systemErrRule = SystemErrRule().muteForSuccessfulTests()
@get:Rule
val systemOutRule = SystemOutRule().muteForSuccessfulTests()
private val ymlNotFound = getPath("not_found.yml")
private val localYamlFile = getPath("src/test/kotlin/ftl/fixtures/flank.local.yml")
private val gcsYamlFile = getPath("src/test/kotlin/ftl/fixtures/flank.gcs.yml")
private val appApkLocal = getString("../test_projects/android/apks/app-debug.apk")
private val appApkGcs = "gs://tmp_bucket_2/app-debug.apk"
private val testApkLocal = getString("../test_projects/android/apks/app-debug-androidTest.apk")
private val testApkGcs = "gs://tmp_bucket_2/app-debug-androidTest.apk"
private val testName = "class com.example.app.ExampleUiTest#testPasses"
private val directoryToPull = "/sdcard/screenshots"
private val appApkAbsolutePath = appApkLocal.absolutePath()
private val testApkAbsolutePath = testApkLocal.absolutePath()
// NOTE: Change working dir to '%MODULE_WORKING_DIR%' in IntelliJ to match gradle for this test to pass.
@Test
fun localConfigLoadsSuccessfully() {
val config = AndroidArgs.load(localYamlFile)
checkConfig(config, true)
}
@Test
fun gcsConfigLoadsSuccessfully() {
val config = AndroidArgs.load(gcsYamlFile)
checkConfig(config, false)
}
private fun checkConfig(args: AndroidArgs, local: Boolean) {
with(args) {
if (local) assert(getString(testApk!!), getString(testApkAbsolutePath))
else assert(testApk, testApkGcs)
if (local) assert(getString(appApk!!), getString(appApkAbsolutePath))
else assert(appApk, appApkGcs)
assert(autoGoogleLogin, true)
assert(useOrchestrator, true)
assert(environmentVariables, mapOf("clearPackageData" to "true"))
assert(directoriesToPull, listOf(directoryToPull))
assert(resultsBucket, "tmp_bucket_2")
assert(performanceMetrics, true)
assert(recordVideo, true)
assert(testTimeout, "60m")
assert(async, true)
assert(testTargets, listOf(testName))
assert(
devices,
listOf(
Device("NexusLowRes", "23", "en", "portrait", isVirtual = true),
Device("NexusLowRes", "23", "en", "landscape", isVirtual = true),
Device("shamu", "22", "zh_CN", "default", isVirtual = false)
)
)
assert(maxTestShards, 1)
assert(repeatTests, 1)
}
}
private fun configWithTestMethods(
amount: Int,
maxTestShards: Int = 1
): AndroidArgs = createAndroidArgs(
defaultAndroidConfig().apply {
platform.apply {
gcloud.apply {
app = appApkLocal
test = getString("src/test/kotlin/ftl/fixtures/tmp/apk/app-debug-androidTest_$amount.apk")
}
}
common.flank.maxTestShards = maxTestShards
}
)
@Test
fun `should parse test-targets from env`() {
mockkStatic("ftl.args.ArgsHelperKt")
every { getEnv("FROM_ENV") } returns "class from.env.Class,notAnnotation from.env.Annotation"
val config = AndroidArgs.load(localYamlFile)
assertThat(config.testTargets).containsExactly(
"class from.env.Class",
"notAnnotation from.env.Annotation",
"class com.example.app.ExampleUiTest#testPasses"
)
}
@Test
fun `calculateShards additionalAppTestApks`() {
val test1 = "src/test/kotlin/ftl/fixtures/tmp/apk/app-debug-androidTest_1.apk"
val test155 = "src/test/kotlin/ftl/fixtures/tmp/apk/app-debug-androidTest_155.apk"
val config = createAndroidArgs(
defaultAndroidConfig().apply {
platform.apply {
gcloud.apply {
app = appApkLocal
test = getString(test1)
}
flank.apply {
additionalAppTestApks = mutableListOf(
AppTestPair(
app = appApkLocal,
test = getString(test155)
)
)
}
}
common.flank.maxTestShards = 3
}
)
with(runBlocking { config.getAndroidMatrixShards() }) {
assertEquals(1, get("matrix-0")!!.shards["shard-0"]!!.size)
assertEquals(51, get("matrix-1")!!.shards["shard-0"]!!.size)
assertEquals(52, get("matrix-1")!!.shards["shard-1"]!!.size)
assertEquals(52, get("matrix-1")!!.shards["shard-2"]!!.size)
}
}
@Test
fun `calculateShards additionalAppTestApks with override`() {
val test1 = "src/test/kotlin/ftl/fixtures/tmp/apk/app-debug-androidTest_1.apk"
val test155 = "src/test/kotlin/ftl/fixtures/tmp/apk/app-debug-androidTest_155.apk"
val config = createAndroidArgs(
defaultAndroidConfig().apply {
platform.apply {
gcloud.apply {
app = appApkLocal
test = getString(test1)
}
flank.apply {
additionalAppTestApks = mutableListOf(
AppTestPair(
app = appApkLocal,
test = getString(test155),
maxTestShards = 4
)
)
}
}
common.flank.maxTestShards = 3
}
)
with(runBlocking { config.getAndroidMatrixShards() }) {
assertEquals(1, get("matrix-0")!!.shards.size)
assertEquals(4, get("matrix-1")!!.shards.size)
assertEquals(1, get("matrix-0")!!.shards["shard-0"]!!.size)
// 155/4 = ~39
assertEquals(38, get("matrix-1")!!.shards["shard-0"]!!.size)
assertEquals(39, get("matrix-1")!!.shards["shard-1"]!!.size)
assertEquals(39, get("matrix-1")!!.shards["shard-2"]!!.size)
assertEquals(39, get("matrix-1")!!.shards["shard-3"]!!.size)
}
}
@Test
fun `calculateShards 0`() = runBlocking {
val config = configWithTestMethods(0)
val testShardChunks = config.createAndroidTestContexts()
with(config) {
assert(maxTestShards, 1)
assert(testShardChunks.size, 0)
}
}
@Test
fun `calculateShards 1`() {
val config = configWithTestMethods(1)
val testShardChunks = getAndroidShardChunks(config)
with(config) {
assert(maxTestShards, 1)
assert(testShardChunks.size, 1)
assert(testShardChunks.first().size, 1)
}
}
@Test
fun `calculateShards 155`() {
val config = configWithTestMethods(155)
val testShardChunks = getAndroidShardChunks(config)
with(config) {
assert(maxTestShards, 1)
assert(testShardChunks.size, 1)
assert(testShardChunks.first().size, 155)
}
}
@Test
fun `calculateShards 155 40`() {
val config = configWithTestMethods(155, maxTestShards = 40)
val testShardChunks = getAndroidShardChunks(config)
with(config) {
assert(maxTestShards, 40)
assert(testShardChunks.size, 40)
assert(testShardChunks.first().size, 3)
}
}
@Test
fun `should distribute equally to shards`() {
val config = configWithTestMethods(155, maxTestShards = 40)
val testShardChunks = getAndroidShardChunks(config)
with(config) {
assert(maxTestShards, 40)
assert(testShardChunks.size, 40)
testShardChunks.forEach { assertThat(it.size).isIn(3..4) }
}
}
@Test
fun platformDisplayConfig() {
val androidConfig = AndroidArgs.load(localYamlFile).toString()
assert(androidConfig.contains("xctestrunZip"), false)
assert(androidConfig.contains("xctestrunFile"), false)
}
@Test
fun assertGcsBucket() {
val oldConfig = AndroidArgs.load(localYamlFile)
// Need to set the project id to get the bucket info from StorageOptions
val config = createAndroidArgs(
defaultAndroidConfig().apply {
common.apply {
gcloud.resultsBucket = oldConfig.resultsBucket
flank.project = "ftl-flank-open-source"
}
platform.gcloud.apply {
app = oldConfig.appApk
test = oldConfig.testApk
}
}
)
assert(config.resultsBucket, "tmp_bucket_2")
}
@Test
fun `verify run timeout value from yml file`() {
val args = AndroidArgs.load(localYamlFile)
assertEquals(60 * 60 * 1000L, args.parsedTimeout)
}
@Test
fun `verify output style value from uml file`() {
val args = AndroidArgs.load(localYamlFile)
assertEquals(OutputStyle.Single, args.outputStyle)
}
@Test(expected = FlankGeneralError::class)
fun `should throw if load and yamlFile not found`() {
AndroidArgs.load(ymlNotFound)
}
@Test
fun `should not throw if loadOrDefault and yamlFile not found`() {
AndroidArgs.loadOrDefault(ymlNotFound)
}
}
| test_runner/src/test/kotlin/ftl/args/AndroidArgsFileTest.kt | 2755859175 |
package de.fabmax.kool
interface ApplicationCallbacks {
/**
* Called when the app (window / browser tab) is about to close. Can return true to proceed with closing the app
* or false to stop it.
* This is particular useful to implement a dialogs like "There is unsaved stuff, are you sure you want to close
* this app? Yes / no / maybe"
* The default implementation simply returns true.
*/
fun onWindowCloseRequest(ctx: KoolContext): Boolean = true
/**
* Called when the screen scale changes, e.g. because the window is moved onto another monitor with a different
* scale. Returns the actual screen scale to apply.
* This can be used to limit the actual screen scale to a reasonable value, e.g. something like
* return max(1f, newScale)
* The default implementation simply returns newScale.
*/
fun onWindowScaleChange(newScale: Float, ctx: KoolContext): Float = newScale
} | kool-core/src/commonMain/kotlin/de/fabmax/kool/ApplicationCallbacks.kt | 1009384480 |
package info.nightscout.androidaps.receivers
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.content.Intent
import dagger.android.DaggerBroadcastReceiver
import info.nightscout.androidaps.events.EventBTChange
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import javax.inject.Inject
class BTReceiver : DaggerBroadcastReceiver() {
@Inject lateinit var rxBus: RxBusWrapper
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
val device: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
when (intent.action) {
BluetoothDevice.ACTION_ACL_CONNECTED ->
rxBus.send(EventBTChange(EventBTChange.Change.CONNECT, deviceName = device.name, deviceAddress = device.address))
BluetoothDevice.ACTION_ACL_DISCONNECTED ->
rxBus.send(EventBTChange(EventBTChange.Change.DISCONNECT, deviceName = device.name, deviceAddress = device.address))
}
}
} | app/src/main/java/info/nightscout/androidaps/receivers/BTReceiver.kt | 2214116672 |
package uy.kohesive.iac.model.aws.clients
import com.amazonaws.services.directory.AbstractAWSDirectoryService
import com.amazonaws.services.directory.AWSDirectoryService
import com.amazonaws.services.directory.model.*
import uy.kohesive.iac.model.aws.IacContext
import uy.kohesive.iac.model.aws.proxy.makeProxy
open class BaseDeferredAWSDirectoryService(val context: IacContext) : AbstractAWSDirectoryService(), AWSDirectoryService {
override fun addIpRoutes(request: AddIpRoutesRequest): AddIpRoutesResult {
return with (context) {
request.registerWithAutoName()
AddIpRoutesResult().registerWithSameNameAs(request)
}
}
override fun addTagsToResource(request: AddTagsToResourceRequest): AddTagsToResourceResult {
return with (context) {
request.registerWithAutoName()
AddTagsToResourceResult().registerWithSameNameAs(request)
}
}
override fun createAlias(request: CreateAliasRequest): CreateAliasResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateAliasRequest, CreateAliasResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request,
copyFromReq = mapOf(
CreateAliasRequest::getDirectoryId to CreateAliasResult::getDirectoryId,
CreateAliasRequest::getAlias to CreateAliasResult::getAlias
)
)
}
}
override fun createComputer(request: CreateComputerRequest): CreateComputerResult {
return with (context) {
request.registerWithAutoName()
CreateComputerResult().withComputer(
makeProxy<CreateComputerRequest, Computer>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request,
copyFromReq = mapOf(
CreateComputerRequest::getComputerName to Computer::getComputerName,
CreateComputerRequest::getComputerAttributes to Computer::getComputerAttributes
)
)
).registerWithSameNameAs(request)
}
}
override fun createConditionalForwarder(request: CreateConditionalForwarderRequest): CreateConditionalForwarderResult {
return with (context) {
request.registerWithAutoName()
CreateConditionalForwarderResult().registerWithSameNameAs(request)
}
}
override fun createDirectory(request: CreateDirectoryRequest): CreateDirectoryResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateDirectoryRequest, CreateDirectoryResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createMicrosoftAD(request: CreateMicrosoftADRequest): CreateMicrosoftADResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateMicrosoftADRequest, CreateMicrosoftADResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createSnapshot(request: CreateSnapshotRequest): CreateSnapshotResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateSnapshotRequest, CreateSnapshotResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createTrust(request: CreateTrustRequest): CreateTrustResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateTrustRequest, CreateTrustResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
}
class DeferredAWSDirectoryService(context: IacContext) : BaseDeferredAWSDirectoryService(context)
| model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAWSDirectoryService.kt | 4168310719 |
// PROBLEM: Replace 'associateTo' with 'associateWithTo'
// FIX: Replace with 'associateWithTo'
// WITH_RUNTIME
fun getValue(i: Int): String = ""
fun associateWithTo() {
val destination = mutableMapOf<Int, String>()
listOf(1).<caret>associateTo(destination) { i -> i to getValue(i) }
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceAssociateFunction/associateWithTo/basic2.kt | 2344401982 |
internal class A // this is a primary constructor
// this is a secondary constructor 1
// end of primary constructor body
@JvmOverloads constructor(p: Int = 1) {
private val v = 1
// this is a secondary constructor 2
constructor(s: String) : this(s.length) {} // end of secondary constructor 2 body
// end of secondary constructor 1 body
}
internal class B // this constructor will disappear
// end of constructor body
(private val x: Int) {
fun foo() {}
}
internal class CtorComment /*
* The magic of comments
*/
// single line magic comments
{
var myA = "a"
}
internal class CtorComment2 /*
* The magic of comments
*/
// single line magic comments
| plugins/kotlin/j2k/new/tests/testData/newJ2k/comments/commentsForConstructors.kt | 308666672 |
package eu.kanade.tachiyomi.ui.library
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.data.database.models.Manga
class LibraryMangaEvent(val mangas: Map<Int, List<Manga>>) {
fun getMangaForCategory(category: Category): List<Manga>? {
return mangas[category.id]
}
}
| app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryMangaEvent.kt | 2099048879 |
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtTypeParameter
val <T<caret>> foo: T
// DISABLE-ERRORS | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findTypeParameterUsages/propertyWithTypeParameter.0.kt | 1251873262 |
package client
import server.Server
class Client(name: String = Server.NAME): Server() {
var nextServer: Server? = new Server()
val name = Server.NAME
fun foo(s: Server) {
val server: Server = s
println("Server: $server")
}
fun getNextServer(): Server? {
return nextServer
}
override fun work() {
super<Server>.work()
println("Client")
}
companion object: Server() {
}
}
object ClientObject: Server() {
}
fun Client.bar(s: Server = Server.NAME) {
foo(s)
}
fun Client.hasNextServer(): Boolean {
return getNextServer() != null
}
fun Any.asServer(): Server? {
return if (this is Server) this as Server else null
} | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findWithStructuralGrouping/kotlinClassAllUsages.1.kt | 3726118798 |
fun foo() {
open class T: A
object O1: A
fun bar() {
object O2: T()
}
}
| plugins/kotlin/idea/tests/testData/findUsages/java/findJavaClassUsages/JKInterfaceDerivedLocalObjects.1.kt | 1778033388 |
// 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.debugger.stepping
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.MethodFilter
import com.intellij.debugger.engine.SuspendContextImpl
import org.jetbrains.kotlin.idea.debugger.stepping.filter.KotlinStepOverFilter
import org.jetbrains.kotlin.idea.debugger.stepping.filter.LocationToken
import org.jetbrains.kotlin.idea.debugger.stepping.filter.StepOverCallerInfo
sealed class KotlinStepAction {
object JvmStepOver : KotlinStepAction() {
override fun apply(debugProcess: DebugProcessImpl, suspendContext: SuspendContextImpl, ignoreBreakpoints: Boolean) {
debugProcess.createStepOverCommand(suspendContext, ignoreBreakpoints).contextAction(suspendContext)
}
}
class StepInto(private val filter: MethodFilter?) : KotlinStepAction() {
override fun apply(debugProcess: DebugProcessImpl, suspendContext: SuspendContextImpl, ignoreBreakpoints: Boolean) {
debugProcess.createStepIntoCommand(suspendContext, ignoreBreakpoints, filter).contextAction(suspendContext)
}
}
object StepOut : KotlinStepAction() {
override fun apply(debugProcess: DebugProcessImpl, suspendContext: SuspendContextImpl, ignoreBreakpoints: Boolean) {
debugProcess.createStepOutCommand(suspendContext).contextAction(suspendContext)
}
}
class KotlinStepOver(private val tokensToSkip: Set<LocationToken>, private val callerInfo: StepOverCallerInfo) : KotlinStepAction() {
override fun apply(debugProcess: DebugProcessImpl, suspendContext: SuspendContextImpl, ignoreBreakpoints: Boolean) {
val filter = KotlinStepOverFilter(debugProcess.project, tokensToSkip, callerInfo)
KotlinStepActionFactory.createStepOverCommand(debugProcess, suspendContext, ignoreBreakpoints, filter).contextAction(suspendContext)
}
}
abstract fun apply(debugProcess: DebugProcessImpl, suspendContext: SuspendContextImpl, ignoreBreakpoints: Boolean)
}
| plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stepping/KotlinStepAction.kt | 1753156996 |
package org.schabi.newpipe.local.subscription.item
import android.view.View
import com.xwray.groupie.viewbinding.BindableItem
import org.schabi.newpipe.R
import org.schabi.newpipe.databinding.FeedGroupAddNewItemBinding
class FeedGroupAddNewItem : BindableItem<FeedGroupAddNewItemBinding>() {
override fun getLayout(): Int = R.layout.feed_group_add_new_item
override fun initializeViewBinding(view: View) = FeedGroupAddNewItemBinding.bind(view)
override fun bind(viewBinding: FeedGroupAddNewItemBinding, position: Int) {
// this is a static item, nothing to do here
}
}
| app/src/main/java/org/schabi/newpipe/local/subscription/item/FeedGroupAddNewItem.kt | 3144131741 |
// FIR_IDENTICAL
// FIR_COMPARISON
annotation class Anno
typealias TypedAnno = Anno
@Ty<caret>
fun usage() {
}
// INVOCATION_COUNT: 0
// EXIST: TypedAnno
| plugins/kotlin/completion/tests/testData/basic/common/annotations/TypeAliasToAnnotation.kt | 4138051095 |
package com.geo.geoquake
import android.app.Application
import android.content.Context
/**
* Created by George Stinson on 2017-03-28.
*/
class App : Application() {
override fun onCreate() {
super.onCreate()
appContext = applicationContext
}
companion object {
var appContext: Context? = null
private set
}
}
| geoquake/src/main/java/com/geo/geoquake/App.kt | 1734045839 |
package com.zenika.lunchPlace.restaurant
import org.junit.Test
import org.junit.Assert.*
/**
* Created by gwen on 26/10/16.
*/
class RestaurantControllerTest {
@Test
fun findAll() {
}
@Test
fun findByLastName() {
}
@Test
fun add() {
}
} | backend/src/test/kotlin/com/zenika/lunchPlace/restaurant/RestaurantControllerTest.kt | 513902915 |
package source
fun C.foo() {
} | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveFile/addExtensionImport/before/source/bar.kt | 4201805081 |
package ch.difty.scipamato.common.web
import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.checkboxx.CheckBoxX
import org.apache.wicket.bean.validation.PropertyValidator
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.form.FormComponent
import org.apache.wicket.markup.html.panel.GenericPanel
import org.apache.wicket.model.IModel
import org.apache.wicket.model.StringResourceModel
abstract class AbstractPanel<T> @JvmOverloads constructor(
id: String,
model: IModel<T>? = null,
open val mode: Mode = Mode.VIEW,
) : GenericPanel<T>(id, model) {
val isSearchMode: Boolean
get() = mode === Mode.SEARCH
val isEditMode: Boolean
get() = mode === Mode.EDIT
val isViewMode: Boolean
get() = mode === Mode.VIEW
val submitLinkResourceLabel: String
get() = when (mode) {
Mode.EDIT -> "button.save.label"
Mode.SEARCH -> "button.search.label"
Mode.VIEW -> "button.disabled.label"
}
@JvmOverloads
fun queueFieldAndLabel(field: FormComponent<*>, pv: PropertyValidator<*>? = null) {
field.labelled().apply {
outputMarkupId = true
}.also {
queue(it)
}
if (isEditMode) pv?.let { field.add(it) }
}
protected fun queueCheckBoxAndLabel(field: CheckBoxX) {
queue(field.labelled())
}
private fun FormComponent<*>.labelled(): FormComponent<*> {
val fieldId = id
val labelModel = StringResourceModel("$fieldId$LABEL_RESOURCE_TAG", this@AbstractPanel, null)
label = labelModel
[email protected](Label("$fieldId$LABEL_TAG", labelModel))
return this
}
companion object {
private const val serialVersionUID = 1L
const val SELECT_ALL_RESOURCE_TAG = "multiselect.selectAll"
const val DESELECT_ALL_RESOURCE_TAG = "multiselect.deselectAll"
}
}
enum class Mode {
EDIT, VIEW, SEARCH
}
| common/common-wicket/src/main/kotlin/ch/difty/scipamato/common/web/AbstractPanel.kt | 2482420051 |
package totoro.yui.actions
import totoro.yui.Yui
import totoro.yui.client.Command
import totoro.yui.client.IRCClient
import totoro.yui.util.F
class PlasmaAction : SensitivityAction("plasma") {
override fun handle(client: IRCClient, command: Command): Boolean {
client.send(command.chan,
F.Bold + command.content
.map { F.mix(F.Black, F.colors[Yui.Random.nextInt(F.colors.size - 2) + 2]) + it }
.joinToString("") + F.Reset
)
return true
}
}
| src/main/kotlin/totoro/yui/actions/PlasmaAction.kt | 2083537819 |
package de.droidcon.berlin2018
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| app/src/test/java/de/droidcon/berlin2018/ExampleUnitTest.kt | 1117782757 |
package tornadofx.testapps
import javafx.scene.paint.Color
import javafx.scene.text.FontWeight
import tornadofx.*
class AsyncProgressApp : App(AsyncProgressView::class)
class AsyncProgressView : View("Async Progress") {
override val root = borderpane {
setPrefSize(400.0, 300.0)
center {
button("Start") {
action {
runAsync {
updateTitle("Doing some work")
for (i in 1..10) {
updateMessage("Working $i...")
if (i == 5)
updateTitle("Dome something else")
Thread.sleep(200)
updateProgress(i.toLong(), 10)
}
}
}
}
}
bottom {
add<ProgressView>()
}
}
}
class ProgressView : View() {
val status: TaskStatus by inject()
override val root = vbox(4) {
visibleWhen { status.running }
style { borderColor += box(Color.LIGHTGREY, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT) }
label(status.title).style { fontWeight = FontWeight.BOLD }
hbox(4) {
label(status.message)
progressbar(status.progress)
visibleWhen { status.running }
}
}
}
class AsyncProgressButtonView : View() {
override val root = stackpane {
setPrefSize(400.0, 400.0)
button("Click me") {
action {
runAsyncWithProgress {
Thread.sleep(2000)
}
}
}
}
} | src/test/kotlin/tornadofx/testapps/AsyncProgressApp.kt | 1336446249 |
package com.sedsoftware.yaptalker.data.network.site.model
import com.google.gson.annotations.SerializedName
data class UserSmall(
@SerializedName("avatar_res")
var avatarRes: String? = null,
@SerializedName("avatar_type")
var avatarType: String? = null,
@SerializedName("avatar_url")
var avatarUrl: String? = null,
@SerializedName("id")
var id: String? = null,
@SerializedName("name")
var name: String? = null,
@SerializedName("new_mails")
var newMails: String? = null,
@SerializedName("rank")
var rank: Int? = null,
@SerializedName("read_only")
var readOnly: Int? = null,
@SerializedName("SID")
var sid: String? = null,
@SerializedName("validated")
var validated: String? = null
)
| data/src/main/java/com/sedsoftware/yaptalker/data/network/site/model/UserSmall.kt | 4113002446 |
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.benchmark
import android.os.Build
import androidx.benchmark.junit4.BenchmarkRule
import androidx.benchmark.junit4.measureRepeated
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.InvalidationTracker
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.test.core.app.ApplicationProvider
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import androidx.testutils.generateAllEnumerations
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@LargeTest
@RunWith(Parameterized::class)
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.JELLY_BEAN) // TODO Fix me for API 15 - b/120098504
class InvalidationTrackerBenchmark(private val sampleSize: Int, private val mode: Mode) {
@get:Rule
val benchmarkRule = BenchmarkRule()
val context = ApplicationProvider.getApplicationContext() as android.content.Context
@Before
fun setup() {
for (postfix in arrayOf("", "-wal", "-shm")) {
val dbFile = context.getDatabasePath(DB_NAME + postfix)
if (dbFile.exists()) {
assertTrue(dbFile.delete())
}
}
}
@Test
fun largeTransaction() {
val db = Room.databaseBuilder(context, TestDatabase::class.java, DB_NAME)
.setJournalMode(RoomDatabase.JournalMode.WRITE_AHEAD_LOGGING)
.build()
val observer = object : InvalidationTracker.Observer("user") {
override fun onInvalidated(tables: Set<String>) {}
}
db.invalidationTracker.addObserver(observer)
val users = List(sampleSize) { User(it, "name$it") }
benchmarkRule.measureRepeated {
runWithTimingConditional(pauseTiming = mode == Mode.MEASURE_DELETE) {
// Insert the sample size
db.runInTransaction {
for (user in users) {
db.getUserDao().insert(user)
}
}
}
runWithTimingConditional(pauseTiming = mode == Mode.MEASURE_INSERT) {
// Delete sample size (causing a large transaction)
assertEquals(db.getUserDao().deleteAll(), sampleSize)
}
}
db.close()
}
private inline fun runWithTimingConditional(
pauseTiming: Boolean = false,
block: () -> Unit
) {
if (pauseTiming) benchmarkRule.getState().pauseTiming()
block()
if (pauseTiming) benchmarkRule.getState().resumeTiming()
}
companion object {
@JvmStatic
@Parameterized.Parameters(name = "sampleSize={0}, mode={1}")
fun data(): List<Array<Any>> =
generateAllEnumerations(
listOf(100, 1000, 5000, 10000),
listOf(
Mode.MEASURE_INSERT,
Mode.MEASURE_DELETE,
Mode.MEASURE_INSERT_AND_DELETE
)
)
private const val DB_NAME = "invalidation-benchmark-test"
}
@Database(entities = [User::class], version = 1, exportSchema = false)
abstract class TestDatabase : RoomDatabase() {
abstract fun getUserDao(): UserDao
}
@Entity
data class User(@PrimaryKey val id: Int, val name: String)
@Dao
interface UserDao {
@Insert
fun insert(user: User)
@Query("DELETE FROM User")
fun deleteAll(): Int
}
enum class Mode {
MEASURE_INSERT,
MEASURE_DELETE,
MEASURE_INSERT_AND_DELETE
}
}
| room/benchmark/src/androidTest/java/androidx/room/benchmark/InvalidationTrackerBenchmark.kt | 2179085116 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.CacheDrawScope
import androidx.compose.ui.draw.DrawResult
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.isSimple
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.ClipOp
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.ImageBitmapConfig
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathOperation
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.drawscope.CanvasDrawScope
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.node.Ref
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.toSize
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
/**
* Modify element to add border with appearance specified with a [border] and a [shape] and clip it.
*
* @sample androidx.compose.foundation.samples.BorderSample()
*
* @param border [BorderStroke] class that specifies border appearance, such as size and color
* @param shape shape of the border
*/
fun Modifier.border(border: BorderStroke, shape: Shape = RectangleShape) =
border(width = border.width, brush = border.brush, shape = shape)
/**
* Modify element to add border with appearance specified with a [width], a [color] and a [shape]
* and clip it.
*
* @sample androidx.compose.foundation.samples.BorderSampleWithDataClass()
*
* @param width width of the border. Use [Dp.Hairline] for a hairline border.
* @param color color to paint the border with
* @param shape shape of the border
*/
fun Modifier.border(width: Dp, color: Color, shape: Shape = RectangleShape) =
border(width, SolidColor(color), shape)
/**
* Modify element to add border with appearance specified with a [width], a [brush] and a [shape]
* and clip it.
*
* @sample androidx.compose.foundation.samples.BorderSampleWithBrush()
*
* @param width width of the border. Use [Dp.Hairline] for a hairline border.
* @param brush brush to paint the border with
* @param shape shape of the border
*/
fun Modifier.border(width: Dp, brush: Brush, shape: Shape): Modifier = composed(
factory = {
// BorderCache object that is lazily allocated depending on the type of shape
// This object is only used for generic shapes and rounded rectangles with different corner
// radius sizes.
val borderCacheRef = remember { Ref<BorderCache>() }
this.then(
Modifier.drawWithCache {
val hasValidBorderParams = width.toPx() >= 0f && size.minDimension > 0f
if (!hasValidBorderParams) {
drawContentWithoutBorder()
} else {
val strokeWidthPx = min(
if (width == Dp.Hairline) 1f else ceil(width.toPx()),
ceil(size.minDimension / 2)
)
val halfStroke = strokeWidthPx / 2
val topLeft = Offset(halfStroke, halfStroke)
val borderSize = Size(
size.width - strokeWidthPx,
size.height - strokeWidthPx
)
// The stroke is larger than the drawing area so just draw a full shape instead
val fillArea = (strokeWidthPx * 2) > size.minDimension
when (val outline = shape.createOutline(size, layoutDirection, this)) {
is Outline.Generic ->
drawGenericBorder(
borderCacheRef,
brush,
outline,
fillArea,
strokeWidthPx
)
is Outline.Rounded ->
drawRoundRectBorder(
borderCacheRef,
brush,
outline,
topLeft,
borderSize,
fillArea,
strokeWidthPx
)
is Outline.Rectangle ->
drawRectBorder(
brush,
topLeft,
borderSize,
fillArea,
strokeWidthPx
)
}
}
}
)
},
inspectorInfo = debugInspectorInfo {
name = "border"
properties["width"] = width
if (brush is SolidColor) {
properties["color"] = brush.value
value = brush.value
} else {
properties["brush"] = brush
}
properties["shape"] = shape
}
)
private fun Ref<BorderCache>.obtain(): BorderCache =
this.value ?: BorderCache().also { value = it }
/**
* Helper object that handles lazily allocating and re-using objects
* to render the border into an offscreen ImageBitmap
*/
private data class BorderCache(
private var imageBitmap: ImageBitmap? = null,
private var canvas: androidx.compose.ui.graphics.Canvas? = null,
private var canvasDrawScope: CanvasDrawScope? = null,
private var borderPath: Path? = null
) {
inline fun CacheDrawScope.drawBorderCache(
borderSize: IntSize,
config: ImageBitmapConfig,
block: DrawScope.() -> Unit
): ImageBitmap {
var targetImageBitmap = imageBitmap
var targetCanvas = canvas
// If we previously had allocated a full Argb888 ImageBitmap but are only requiring
// an alpha mask, just re-use the same ImageBitmap instead of allocating a new one
val compatibleConfig = targetImageBitmap?.config == ImageBitmapConfig.Argb8888 ||
config == targetImageBitmap?.config
if (targetImageBitmap == null ||
targetCanvas == null ||
size.width > targetImageBitmap.width ||
size.height > targetImageBitmap.height ||
!compatibleConfig
) {
targetImageBitmap = ImageBitmap(
borderSize.width,
borderSize.height,
config = config
).also {
imageBitmap = it
}
targetCanvas = androidx.compose.ui.graphics.Canvas(targetImageBitmap).also {
canvas = it
}
}
val targetDrawScope = canvasDrawScope ?: CanvasDrawScope().also { canvasDrawScope = it }
val drawSize = borderSize.toSize()
targetDrawScope.draw(
this,
layoutDirection,
targetCanvas,
drawSize
) {
// Clear the previously rendered portion within this ImageBitmap as we could
// be re-using it
drawRect(
color = Color.Black,
size = drawSize,
blendMode = BlendMode.Clear
)
block()
}
targetImageBitmap.prepareToDraw()
return targetImageBitmap
}
fun obtainPath(): Path =
borderPath ?: Path().also { borderPath = it }
}
/**
* Border implementation for invalid parameters that just draws the content
* as the given border parameters are infeasible (ex. negative border width)
*/
private fun CacheDrawScope.drawContentWithoutBorder(): DrawResult =
onDrawWithContent {
drawContent()
}
/**
* Border implementation for generic paths. Note it is possible to be given paths
* that do not make sense in the context of a border (ex. a figure 8 path or a non-enclosed
* shape) We do not handle that here as we expect developers to give us enclosed, non-overlapping
* paths
*/
private fun CacheDrawScope.drawGenericBorder(
borderCacheRef: Ref<BorderCache>,
brush: Brush,
outline: Outline.Generic,
fillArea: Boolean,
strokeWidth: Float
): DrawResult =
if (fillArea) {
onDrawWithContent {
drawContent()
drawPath(outline.path, brush = brush)
}
} else {
// Optimization, if we are only drawing a solid color border, we only need an alpha8 mask
// as we can draw the mask with a tint.
// Otherwise we need to allocate a full ImageBitmap and draw it normally
val config: ImageBitmapConfig
val colorFilter: ColorFilter?
if (brush is SolidColor) {
config = ImageBitmapConfig.Alpha8
colorFilter = ColorFilter.tint(brush.value)
} else {
config = ImageBitmapConfig.Argb8888
colorFilter = null
}
val pathBounds = outline.path.getBounds()
val borderCache = borderCacheRef.obtain()
// Create a mask path that includes a rectangle with the original path cut out of it
val maskPath = borderCache.obtainPath().apply {
reset()
addRect(pathBounds)
op(this, outline.path, PathOperation.Difference)
}
val cacheImageBitmap: ImageBitmap
val pathBoundsSize = IntSize(
ceil(pathBounds.width).toInt(),
ceil(pathBounds.height).toInt()
)
with(borderCache) {
// Draw into offscreen bitmap with the size of the path
// We need to draw into this intermediate bitmap to act as a layer
// and make sure that the clearing logic does not generate underdraw
// into the target we are rendering into
cacheImageBitmap = drawBorderCache(
pathBoundsSize,
config
) {
// Paths can have offsets, so translate to keep the drawn path
// within the bounds of the mask bitmap
translate(-pathBounds.left, -pathBounds.top) {
// Draw the path with a stroke width twice the provided value.
// Because strokes are centered, this will draw both and inner and outer stroke
// with the desired stroke width
drawPath(path = outline.path, brush = brush, style = Stroke(strokeWidth * 2))
// Scale the canvas slightly to cover the background that may be visible
// after clearing the outer stroke
scale(
(size.width + 1) / size.width,
(size.height + 1) / size.height
) {
// Remove the outer stroke by clearing the inverted mask path
drawPath(path = maskPath, brush = brush, blendMode = BlendMode.Clear)
}
}
}
}
onDrawWithContent {
drawContent()
translate(pathBounds.left, pathBounds.top) {
drawImage(cacheImageBitmap, srcSize = pathBoundsSize, colorFilter = colorFilter)
}
}
}
/**
* Border implementation for simple rounded rects and those with different corner
* radii
*/
private fun CacheDrawScope.drawRoundRectBorder(
borderCacheRef: Ref<BorderCache>,
brush: Brush,
outline: Outline.Rounded,
topLeft: Offset,
borderSize: Size,
fillArea: Boolean,
strokeWidth: Float
): DrawResult {
return if (outline.roundRect.isSimple) {
val cornerRadius = outline.roundRect.topLeftCornerRadius
val halfStroke = strokeWidth / 2
val borderStroke = Stroke(strokeWidth)
onDrawWithContent {
drawContent()
when {
fillArea -> {
// If the drawing area is smaller than the stroke being drawn
// drawn all around it just draw a filled in rounded rect
drawRoundRect(brush, cornerRadius = cornerRadius)
}
cornerRadius.x < halfStroke -> {
// If the corner radius is smaller than half of the stroke width
// then the interior curvature of the stroke will be a sharp edge
// In this case just draw a normal filled in rounded rect with the
// desired corner radius but clipping out the interior rectangle
clipRect(
strokeWidth,
strokeWidth,
size.width - strokeWidth,
size.height - strokeWidth,
clipOp = ClipOp.Difference
) {
drawRoundRect(brush, cornerRadius = cornerRadius)
}
}
else -> {
// Otherwise draw a stroked rounded rect with the corner radius
// shrunk by half of the stroke width. This will ensure that the
// outer curvature of the rounded rectangle will have the desired
// corner radius.
drawRoundRect(
brush = brush,
topLeft = topLeft,
size = borderSize,
cornerRadius = cornerRadius.shrink(halfStroke),
style = borderStroke
)
}
}
}
} else {
val path = borderCacheRef.obtain().obtainPath()
val roundedRectPath = createRoundRectPath(path, outline.roundRect, strokeWidth, fillArea)
onDrawWithContent {
drawContent()
drawPath(roundedRectPath, brush = brush)
}
}
}
/**
* Border implementation for rectangular borders
*/
private fun CacheDrawScope.drawRectBorder(
brush: Brush,
topLeft: Offset,
borderSize: Size,
fillArea: Boolean,
strokeWidthPx: Float
): DrawResult {
// If we are drawing a rectangular stroke, just offset it by half the stroke
// width as strokes are always drawn centered on their geometry.
// If the border is larger than the drawing area, just fill the area with a
// solid rectangle
val rectTopLeft = if (fillArea) Offset.Zero else topLeft
val size = if (fillArea) size else borderSize
val style = if (fillArea) Fill else Stroke(strokeWidthPx)
return onDrawWithContent {
drawContent()
drawRect(
brush = brush,
topLeft = rectTopLeft,
size = size,
style = style
)
}
}
/**
* Helper method that creates a round rect with the inner region removed
* by the given stroke width
*/
private fun createRoundRectPath(
targetPath: Path,
roundedRect: RoundRect,
strokeWidth: Float,
fillArea: Boolean
): Path =
targetPath.apply {
reset()
addRoundRect(roundedRect)
if (!fillArea) {
val insetPath = Path().apply {
addRoundRect(createInsetRoundedRect(strokeWidth, roundedRect))
}
op(this, insetPath, PathOperation.Difference)
}
}
private fun createInsetRoundedRect(
widthPx: Float,
roundedRect: RoundRect
) = RoundRect(
left = widthPx,
top = widthPx,
right = roundedRect.width - widthPx,
bottom = roundedRect.height - widthPx,
topLeftCornerRadius = roundedRect.topLeftCornerRadius.shrink(widthPx),
topRightCornerRadius = roundedRect.topRightCornerRadius.shrink(widthPx),
bottomLeftCornerRadius = roundedRect.bottomLeftCornerRadius.shrink(widthPx),
bottomRightCornerRadius = roundedRect.bottomRightCornerRadius.shrink(widthPx)
)
/**
* Helper method to shrink the corner radius by the given value, clamping to 0
* if the resultant corner radius would be negative
*/
private fun CornerRadius.shrink(value: Float): CornerRadius = CornerRadius(
max(0f, this.x - value),
max(0f, this.y - value)
)
| compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/Border.kt | 1688806587 |
// ERROR: No value passed for parameter 'i'
package a
private fun f(p: A, t: T) {
g(A(c).ext())
O1.f()
O2
E.ENTRY
}
private fun f2(i: Outer.Inner, n: Outer.Nested, e: Outer.NestedEnum, o: Outer.NestedObj, t: Outer.NestedTrait, a: Outer.NestedAnnotation) {
ClassObject
} | plugins/kotlin/idea/tests/testData/copyPaste/imports/NoImportForSamePackage.expected.kt | 67182872 |
// 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.fir.fe10.binding
import com.intellij.lang.ASTNode
import org.jetbrains.kotlin.analysis.api.calls.*
import org.jetbrains.kotlin.analysis.api.diagnostics.KtDiagnostic
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.fir.fe10.Fe10WrapperContext
import org.jetbrains.kotlin.idea.fir.fe10.KtSymbolBasedConstructorDescriptor
import org.jetbrains.kotlin.idea.fir.fe10.toDeclarationDescriptor
import org.jetbrains.kotlin.idea.fir.fe10.toKotlinType
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.CallMaker
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.Receiver
import org.jetbrains.kotlin.types.expressions.ControlStructureTypingUtils
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class CallAndResolverCallWrappers(bindingContext: KtSymbolBasedBindingContext) {
private val context = bindingContext.context
init {
bindingContext.registerGetterByKey(BindingContext.CALL, this::getCall)
bindingContext.registerGetterByKey(BindingContext.RESOLVED_CALL, this::getResolvedCall)
bindingContext.registerGetterByKey(BindingContext.CONSTRUCTOR_RESOLVED_DELEGATION_CALL, this::getConstructorResolvedDelegationCall)
bindingContext.registerGetterByKey(BindingContext.REFERENCE_TARGET, this::getReferenceTarget)
}
private fun getCall(element: KtElement): Call? {
val call = createCall(element) ?: return null
/**
* In FE10 [org.jetbrains.kotlin.resolve.calls.tasks.TracingStrategyImpl.bindCall] happening to the calleeExpression
*/
check(call.calleeExpression == element) {
"${call.calleeExpression} != $element"
}
return call
}
private fun createCall(element: KtElement): Call? {
val parent = element.parent
if (parent is KtCallElement) {
val callParent = parent.parent
val callOperationNode: ASTNode?
val receiver: Receiver?
if (callParent is KtQualifiedExpression) {
callOperationNode = callParent.operationTokenNode
receiver = callParent.receiverExpression.toExpressionReceiverValue(context)
} else {
callOperationNode = null
receiver = null
}
return CallMaker.makeCall(receiver, callOperationNode, parent)
}
if (element is KtSimpleNameExpression && element !is KtOperationReferenceExpression) {
if (parent is KtQualifiedExpression) {
val receiver = parent.receiverExpression.toExpressionReceiverValue(context)
return CallMaker.makePropertyCall(receiver, parent.operationTokenNode, element)
}
return CallMaker.makePropertyCall(null, null, element)
}
if (element is KtArrayAccessExpression) {
val receiver = element.getArrayExpression()?.toExpressionReceiverValue(context) ?: return null
return CallMaker.makeArrayGetCall(receiver, element, Call.CallType.ARRAY_GET_METHOD)
}
when (parent) {
is KtBinaryExpression -> {
val receiver = parent.left?.toExpressionReceiverValue(context) ?: context.errorHandling()
return CallMaker.makeCall(receiver, parent)
}
is KtUnaryExpression -> {
if (element is KtOperationReferenceExpression && element.getReferencedNameElementType() == KtTokens.EXCLEXCL) {
return ControlStructureTypingUtils.createCallForSpecialConstruction(parent, element, listOf(parent.baseExpression))
}
val receiver = parent.baseExpression?.toExpressionReceiverValue(context) ?: context.errorHandling()
return CallMaker.makeCall(receiver, parent)
}
}
// todo support array get/set calls
return null
}
private fun KtExpression.toExpressionReceiverValue(context: Fe10WrapperContext): ExpressionReceiver {
val ktType = context.withAnalysisSession {
[email protected]() ?: context.implementationPostponed()
}
// TODO: implement THIS_TYPE_FOR_SUPER_EXPRESSION Binding slice
return ExpressionReceiver.create(this, ktType.toKotlinType(context), context.bindingContext)
}
private fun getResolvedCall(call: Call): ResolvedCall<*>? {
val ktElement = call.calleeExpression ?: call.callElement
val ktCallInfo = context.withAnalysisSession { ktElement.resolveCall() }
val diagnostic: KtDiagnostic?
val ktCall: KtCall = when (ktCallInfo) {
null -> return null
is KtSuccessCallInfo -> {
diagnostic = null
ktCallInfo.call
}
is KtErrorCallInfo -> {
diagnostic = ktCallInfo.diagnostic
ktCallInfo.candidateCalls.singleOrNull() ?: return null
}
}
when (ktCall) {
is KtFunctionCall<*> -> {
if (ktCall.safeAs<KtSimpleFunctionCall>()?.isImplicitInvoke == true) {
context.implementationPostponed("Variable + invoke resolved call")
}
return FunctionFe10WrapperResolvedCall(call, ktCall, diagnostic, context)
}
is KtVariableAccessCall -> {
return VariableFe10WrapperResolvedCall(call, ktCall, diagnostic, context)
}
is KtCheckNotNullCall -> {
val kotlinType = context.withAnalysisSession { ktCall.baseExpression.getKtType() }?.toKotlinType(context)
return Fe10BindingSpecialConstructionResolvedCall(
call,
kotlinType,
context.fe10BindingSpecialConstructionFunctions.EXCL_EXCL,
context
)
}
else -> context.implementationPostponed(ktCall.javaClass.canonicalName)
}
}
private fun getConstructorResolvedDelegationCall(constructor: ConstructorDescriptor): ResolvedCall<ConstructorDescriptor>? {
val constructorPSI = constructor.safeAs<KtSymbolBasedConstructorDescriptor>()?.ktSymbol?.psi
when (constructorPSI) {
is KtSecondaryConstructor -> {
val delegationCall = constructorPSI.getDelegationCall()
val ktCallInfo = context.withAnalysisSession { delegationCall.resolveCall() }
val diagnostic = ktCallInfo.safeAs<KtErrorCallInfo>()?.diagnostic
val constructorCall = ktCallInfo.calls.singleOrNull() ?: return null
if (constructorCall !is KtFunctionCall<*>) context.errorHandling(constructorCall::class.toString())
val psiCall = CallMaker.makeCall(null, null, delegationCall)
@Suppress("UNCHECKED_CAST")
return FunctionFe10WrapperResolvedCall(psiCall, constructorCall, diagnostic, context) as ResolvedCall<ConstructorDescriptor>
}
null -> return null
else -> context.implementationPlanned() // todo: Primary Constructor delegated call
}
}
private fun getReferenceTarget(key: KtReferenceExpression): DeclarationDescriptor? {
val ktSymbol = context.withAnalysisSession { key.mainReference.resolveToSymbols().singleOrNull() } ?: return null
return ktSymbol.toDeclarationDescriptor(context)
}
}
| plugins/kotlin/k2-fe10-bindings/src/org/jetbrains/kotlin/idea/fir/fe10/binding/CallAndResolverCallWrappers.kt | 2577524569 |
// language=HTML
val a =
"""
<html><caret>
</html>"""
// WITHOUT_CUSTOM_LINE_INDENT_PROVIDER | plugins/kotlin/idea/tests/testData/editor/enterHandler/multilineString/spaces/EnterInInjectedFragment.kt | 2470363887 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class DirectoryPackagingElementEntityImpl(val dataSource: DirectoryPackagingElementEntityData) : DirectoryPackagingElementEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java,
PackagingElementEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
internal val ARTIFACT_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java,
CompositePackagingElementEntity::class.java,
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true)
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java,
PackagingElementEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
ARTIFACT_CONNECTION_ID,
CHILDREN_CONNECTION_ID,
)
}
override val parentEntity: CompositePackagingElementEntity?
get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this)
override val artifact: ArtifactEntity?
get() = snapshot.extractOneToAbstractOneParent(ARTIFACT_CONNECTION_ID, this)
override val children: List<PackagingElementEntity>
get() = snapshot.extractOneToAbstractManyChildren<PackagingElementEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override val directoryName: String
get() = dataSource.directoryName
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: DirectoryPackagingElementEntityData?) : ModifiableWorkspaceEntityBase<DirectoryPackagingElementEntity, DirectoryPackagingElementEntityData>(
result), DirectoryPackagingElementEntity.Builder {
constructor() : this(DirectoryPackagingElementEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity DirectoryPackagingElementEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field CompositePackagingElementEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field CompositePackagingElementEntity#children should be initialized")
}
}
if (!getEntityData().isDirectoryNameInitialized()) {
error("Field DirectoryPackagingElementEntity#directoryName should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as DirectoryPackagingElementEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.directoryName != dataSource.directoryName) this.directoryName = dataSource.directoryName
if (parents != null) {
val parentEntityNew = parents.filterIsInstance<CompositePackagingElementEntity?>().singleOrNull()
if ((parentEntityNew == null && this.parentEntity != null) || (parentEntityNew != null && this.parentEntity == null) || (parentEntityNew != null && this.parentEntity != null && (this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id)) {
this.parentEntity = parentEntityNew
}
val artifactNew = parents.filterIsInstance<ArtifactEntity?>().singleOrNull()
if ((artifactNew == null && this.artifact != null) || (artifactNew != null && this.artifact == null) || (artifactNew != null && this.artifact != null && (this.artifact as WorkspaceEntityBase).id != (artifactNew as WorkspaceEntityBase).id)) {
this.artifact = artifactNew
}
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: CompositePackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var artifact: ArtifactEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneParent(ARTIFACT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
ARTIFACT_CONNECTION_ID)] as? ArtifactEntity
}
else {
this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] as? ArtifactEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToAbstractOneParentOfChild(ARTIFACT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] = value
}
changedProperty.add("artifact")
}
override var children: List<PackagingElementEntity>
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyChildren<PackagingElementEntity>(CHILDREN_CONNECTION_ID,
this)!!.toList() + (this.entityLinks[EntityLink(true,
CHILDREN_CONNECTION_ID)] as? List<PackagingElementEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as List<PackagingElementEntity> ?: emptyList()
}
}
set(value) {
// Set list of ref types for abstract entities
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *> && (item_value as? ModifiableWorkspaceEntityBase<*, *>)?.diff == null) {
// Backref setup before adding to store an abstract entity
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(item_value)
}
}
_diff.updateOneToAbstractManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value.asSequence())
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override var directoryName: String
get() = getEntityData().directoryName
set(value) {
checkModificationAllowed()
getEntityData(true).directoryName = value
changedProperty.add("directoryName")
}
override fun getEntityClass(): Class<DirectoryPackagingElementEntity> = DirectoryPackagingElementEntity::class.java
}
}
class DirectoryPackagingElementEntityData : WorkspaceEntityData<DirectoryPackagingElementEntity>() {
lateinit var directoryName: String
fun isDirectoryNameInitialized(): Boolean = ::directoryName.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<DirectoryPackagingElementEntity> {
val modifiable = DirectoryPackagingElementEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): DirectoryPackagingElementEntity {
return getCached(snapshot) {
val entity = DirectoryPackagingElementEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return DirectoryPackagingElementEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return DirectoryPackagingElementEntity(directoryName, entitySource) {
this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull()
this.artifact = parents.filterIsInstance<ArtifactEntity>().singleOrNull()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as DirectoryPackagingElementEntityData
if (this.entitySource != other.entitySource) return false
if (this.directoryName != other.directoryName) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as DirectoryPackagingElementEntityData
if (this.directoryName != other.directoryName) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + directoryName.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + directoryName.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/DirectoryPackagingElementEntityImpl.kt | 2341488943 |
// 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.openapi.roots
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.rules.ProjectModelRule
import org.assertj.core.api.Assertions.assertThat
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
abstract class LibraryTableTestCase {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
@Rule
@JvmField
val projectModel = ProjectModelRule()
@Rule
@JvmField
val disposableRule = DisposableRule()
protected abstract val libraryTable: LibraryTable
protected abstract fun createLibrary(name: String, setup: (LibraryEx.ModifiableModelEx) -> Unit = {}): LibraryEx
protected open fun createLibrary(name: String, model: LibraryTable.ModifiableModel) = model.createLibrary(name) as LibraryEx
@Test
fun `add remove library`() {
assertThat(libraryTable.libraries).isEmpty()
val library = createLibrary("a")
checkConsistency()
assertThat(libraryTable.libraries).containsExactly(library)
assertThat(library.isDisposed).isFalse()
runWriteActionAndWait { libraryTable.removeLibrary(library) }
checkConsistency()
assertThat(libraryTable.libraries).isEmpty()
assertThat(library.isDisposed).isTrue()
}
@Test
fun `rename library`() {
val library = createLibrary("a")
assertThat(libraryTable.getLibraryByName("a")).isSameAs(library)
projectModel.renameLibrary(library, "b")
assertThat(libraryTable.libraries.single()).isSameAs(library)
assertThat(libraryTable.getLibraryByName("a")).isNull()
assertThat(libraryTable.getLibraryByName("b")).isSameAs(library)
}
@Test
fun listener() {
val events = ArrayList<String>()
libraryTable.addListener(object : LibraryTable.Listener {
override fun afterLibraryAdded(newLibrary: Library) {
events += "added ${newLibrary.name}"
}
override fun afterLibraryRenamed(library: Library, oldName: String?) {
events += "renamed ${library.name}"
}
override fun beforeLibraryRemoved(library: Library) {
events += "before removed ${library.name}"
}
override fun afterLibraryRemoved(library: Library) {
events += "removed ${library.name}"
}
})
val library = createLibrary("a")
assertThat(events).containsExactly("added a")
events.clear()
projectModel.renameLibrary(library, "b")
assertThat(events).containsExactly("renamed b")
events.clear()
runWriteActionAndWait { libraryTable.removeLibrary(library) }
assertThat(events).containsExactly("before removed b", "removed b")
}
@Test
fun `remove library before committing`() {
val library = edit {
val library = createLibrary("a", it)
assertThat(it.isChanged).isTrue()
it.removeLibrary(library)
library
}
assertThat(libraryTable.libraries).isEmpty()
assertThat(library.isDisposed).isTrue()
}
@Test
fun `add library and dispose model`() {
val a = createLibrary("a")
val model = libraryTable.modifiableModel
val b = createLibrary("b", model)
Disposer.dispose(model)
assertThat(libraryTable.libraries).containsExactly(a)
assertThat(b.isDisposed).isTrue()
assertThat(a.isDisposed).isFalse()
}
@Test
fun `rename uncommitted library`() {
val library = edit {
val library = createLibrary("a", it)
val libraryModel = library.modifiableModel
libraryModel.name = "b"
assertThat(it.getLibraryByName("a")).isEqualTo(library)
assertThat(it.getLibraryByName("b")).isNull()
runWriteActionAndWait { libraryModel.commit() }
assertThat(it.getLibraryByName("a")).isNull()
assertThat(it.getLibraryByName("b")).isEqualTo(library)
assertThat(libraryTable.getLibraryByName("b")).isNull()
library
}
assertThat(libraryTable.getLibraryByName("b")).isEqualTo(library)
}
@Test
fun `remove library and dispose model`() {
val a = createLibrary("a")
val model = libraryTable.modifiableModel
model.removeLibrary(a)
Disposer.dispose(model)
assertThat(libraryTable.libraries).containsExactly(a)
assertThat(a.isDisposed).isFalse()
}
@Test
fun `merge add remove changes`() {
val a = createLibrary("a")
val model1 = libraryTable.modifiableModel
model1.removeLibrary(a)
val model2 = libraryTable.modifiableModel
val b = createLibrary("b", model2)
runWriteActionAndWait {
model1.commit()
model2.commit()
}
assertThat(libraryTable.libraries).containsExactly(b)
}
@Test
fun `merge add add changes`() {
val a = createLibrary("a")
val model1 = libraryTable.modifiableModel
val b = createLibrary("b", model1)
val model2 = libraryTable.modifiableModel
val c = createLibrary("c", model2)
runWriteActionAndWait {
model1.commit()
model2.commit()
}
assertThat(libraryTable.libraries).containsExactlyInAnyOrder(a, b, c)
}
@Test
fun `merge remove remove changes`() {
val a = createLibrary("a")
val b = createLibrary("b")
val model1 = libraryTable.modifiableModel
model1.removeLibrary(a)
val model2 = libraryTable.modifiableModel
model2.removeLibrary(b)
runWriteActionAndWait {
model1.commit()
model2.commit()
}
assertThat(libraryTable.libraries).isEmpty()
}
private fun <T> edit(action: (LibraryTable.ModifiableModel) -> T): T{
checkConsistency()
val model = libraryTable.modifiableModel
checkConsistency(model)
val result = action(model)
checkConsistency(model)
runWriteActionAndWait { model.commit() }
checkConsistency()
return result
}
private fun checkConsistency() {
val fromIterator = ArrayList<Library>()
libraryTable.libraryIterator.forEach { fromIterator += it }
assertThat(fromIterator).containsExactly(*libraryTable.libraries)
for (library in libraryTable.libraries) {
assertThat(libraryTable.getLibraryByName(library.name!!)).isEqualTo(library)
assertThat((library as LibraryEx).isDisposed).isFalse()
}
}
private fun checkConsistency(model: LibraryTable.ModifiableModel) {
val fromIterator = ArrayList<Library>()
model.libraryIterator.forEach { fromIterator += it }
assertThat(fromIterator).containsExactly(*model.libraries)
for (library in model.libraries) {
assertThat(model.getLibraryByName(library.name!!)).isEqualTo(library)
assertThat((library as LibraryEx).isDisposed).isFalse()
}
}
} | platform/lang-impl/testSources/com/intellij/openapi/roots/LibraryTableTestCase.kt | 2754666057 |
// 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.ide.projectView
import com.intellij.ide.projectView.impl.ModuleGroup
import com.intellij.ide.projectView.impl.ModuleGroupingImplementation
import com.intellij.ide.projectView.impl.ModuleGroupingTreeHelper
import com.intellij.openapi.util.Pair
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.UsefulTestCase
import com.intellij.ui.tree.TreeTestUtil
import com.intellij.ui.treeStructure.Tree
import com.intellij.util.ui.tree.TreeUtil
import junit.framework.TestCase
import java.util.*
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.DefaultTreeModel
class ModuleGroupingTreeHelperTest: UsefulTestCase() {
private lateinit var tree: Tree
private lateinit var root: MockModuleTreeNode
private lateinit var model: DefaultTreeModel
override fun setUp() {
super.setUp()
root = MockModuleTreeNode("root")
model = DefaultTreeModel(root)
tree = Tree(model)
TreeTestUtil.assertTreeUI(tree)
}
fun `test disabled grouping`() {
createHelper(false).createModuleNodes("a.main", "a.util")
assertTreeEqual("""
-root
a.main
a.util""")
createHelperFromTree(true).moveAllModuleNodesAndCheckResult("""
-root
-a
a.main
a.util""")
}
fun `test disabled grouping and compacting nodes`() {
createHelper(enableGrouping = false, compactGroupNodes = false).createModuleNodes("a.main", "a.util")
assertTreeEqual("""
-root
a.main
a.util""")
createHelperFromTree(enableGrouping = true, compactGroupNodes = false).moveAllModuleNodesAndCheckResult("""
-root
-a
a.main
a.util""")
}
fun `test single module`() {
createHelper().createModuleNodes("a.main")
assertTreeEqual("""
-root
a.main""")
createHelperFromTree(false).moveAllModuleNodesAndCheckResult("""
-root
a.main""")
}
fun `test single module with disabled compacting`() {
createHelper(compactGroupNodes = false).createModuleNodes("a.main")
assertTreeEqual("""
-root
-a
a.main""")
createHelperFromTree(false).moveAllModuleNodesAndCheckResult("""
-root
a.main""")
}
fun `test two modules`() {
createHelper().createModuleNodes("a.main", "a.util")
assertTreeEqual("""
-root
-a
a.main
a.util
""")
createHelperFromTree(false).moveAllModuleNodesAndCheckResult("""
-root
a.main
a.util""")
}
fun `test two modules with common prefix`() {
createHelper().createModuleNodes("com.a.main", "com.a.util")
assertTreeEqual("""
-root
-a
com.a.main
com.a.util
""")
createHelperFromTree(false).moveAllModuleNodesAndCheckResult("""
-root
com.a.main
com.a.util
""")
}
fun `test two modules with common prefix and parent module as a group`() {
createHelper().createModuleNodes("com.a.main", "com.a.util", "com.a")
assertTreeEqual("""
-root
-com.a
com.a.main
com.a.util
""")
createHelperFromTree(false).moveAllModuleNodesAndCheckResult("""
-root
com.a
com.a.main
com.a.util
""")
}
fun `test create two nested groups`() {
createHelper().createModuleNodes("com.a.foo.bar", "com.a.baz", "com.a.foo.baz")
assertTreeEqual("""
-root
-a
com.a.baz
-foo
com.a.foo.bar
com.a.foo.baz
""")
createHelperFromTree(false).moveAllModuleNodesAndCheckResult("""
-root
com.a.baz
com.a.foo.bar
com.a.foo.baz
""")
}
fun `test two groups`() {
createHelper().createModuleNodes("a.main", "b.util", "a.util", "b.main")
assertTreeEqual("""
-root
-a
a.main
a.util
-b
b.main
b.util
""")
createHelperFromTree(false).moveAllModuleNodesAndCheckResult("""
-root
a.main
a.util
b.main
b.util
""")
}
fun `test module as a group`() {
createHelper().createModuleNodes("a.impl", "a", "a.tests")
assertTreeEqual("""
-root
-a
a.impl
a.tests
""")
createHelperFromTree(false).moveAllModuleNodesAndCheckResult("""
-root
a
a.impl
a.tests""")
}
fun `test module as a group with inner modules`() {
createHelper().createModuleNodes("com.foo", "com.foo.bar", "com.foo.baz.zoo1", "com.foo.baz.zoo2")
assertTreeEqual("""
-root
-com.foo
-baz
com.foo.baz.zoo1
com.foo.baz.zoo2
com.foo.bar
""")
}
fun `test add prefix to module name`() {
val nodes = createHelper().createModuleNodes("main", "util")
assertTreeEqual("""
-root
main
util""")
val node = nodes.find { it.second.name == "main" }!!
node.second.name = "a.main"
moveModuleNodeToProperGroupAndCheckResult(node, """
-root
a.main
util""")
}
fun `test move module node to new group`() {
val nodes = createHelper().createModuleNodes("main", "util", "a.foo")
assertTreeEqual("""
-root
a.foo
main
util""")
val node = nodes.find { it.second.name == "main" }!!
node.second.name = "a.main"
moveModuleNodeToProperGroupAndCheckResult(node, """
-root
-a
a.foo
a.main
util""")
}
fun `test move module node from parent module`() {
val nodes = createHelper().createModuleNodes("a", "a.main")
assertTreeEqual("""
-root
-a
a.main""")
val node = nodes.find { it.second.name == "a.main" }!!
node.second.name = "main"
moveModuleNodeToProperGroupAndCheckResult(node, """
-root
a
main""")
}
fun `test move module node to parent module`() {
val nodes = createHelper().createModuleNodes("a", "main")
val node = nodes.find { it.second.name == "main" }!!
node.second.name = "a.main"
moveModuleNodeToProperGroupAndCheckResult(node, """
-root
-a
a.main""")
}
fun `test insert component into the middle of a module name`() {
val nodes = createHelper().createModuleNodes("a", "a.main")
val node = nodes.find { it.second.name == "a.main" }!!
node.second.name = "a.main.util"
moveModuleNodeToProperGroupAndCheckResult(node, """
-root
-a
a.main.util""")
}
fun `test move module node to child node`() {
val nodes = createHelper().createModuleNodes("a.main", "a.util")
val node = nodes.find { it.second.name == "a.util" }!!
node.second.name = "a.main.util"
moveModuleNodeToProperGroupAndCheckResult(node, """
-root
-a.main
a.main.util""")
}
fun `test remove component from the middle of a module name`() {
val nodes = createHelper().createModuleNodes("a.foo", "a.foo.bar.baz")
val node = nodes.find { it.second.name == "a.foo.bar.baz" }!!
node.second.name = "a.baz"
moveModuleNodeToProperGroupAndCheckResult(node, """
-root
-a
a.baz
a.foo""")
}
fun `test module node become parent module`() {
val nodes = createHelper().createModuleNodes("b", "a.main")
val node = nodes.find { it.second.name == "b" }!!
node.second.name = "a"
moveModuleNodeToProperGroupAndCheckResult(node, """
-root
-a
a.main""")
}
fun `test parent module become ordinary module`() {
val nodes = createHelper().createModuleNodes("a", "a.main")
val node = nodes.find { it.second.name == "a" }!!
node.second.name = "b"
moveModuleNodeToProperGroupAndCheckResult(node, """
-root
a.main
b""")
}
fun `test parent module become ordinary module with disabled compacting`() {
val nodes = createHelper(compactGroupNodes = false).createModuleNodes("a", "a.main")
val node = nodes.find { it.second.name == "a" }!!
node.second.name = "b"
moveModuleNodeToProperGroupAndCheckResult(node, """
-root
-a
a.main
b""", compactGroupNodes = false)
}
fun `test parent module become ordinary module but group remains`() {
val nodes = createHelper().createModuleNodes("a", "a.main", "a.util")
val node = nodes.find { it.second.name == "a" }!!
node.second.name = "b"
moveModuleNodeToProperGroupAndCheckResult(node, """
-root
-a
a.main
a.util
b""")
}
fun `test do not move node if its group wasn't changed`() {
val nodes = createHelper().createModuleNodes("a", "a.main")
nodes.forEach {
val node = it.first
val newNode = createHelperFromTree(nodeToBeMovedFilter = {it == node}).moveModuleNodeToProperGroup(node, it.second, root, model, tree)
assertSame(node, newNode)
}
}
fun `test do not move node if its virtual group wasn't changed`() {
val nodes = createHelper().createModuleNodes("a.util.foo", "a.main.bar")
nodes.forEach {
val node = it.first
val newNode = createHelperFromTree(nodeToBeMovedFilter = {it == node}).moveModuleNodeToProperGroup(node, it.second, root, model, tree)
assertSame(node, newNode)
}
}
fun `test add new module node`() {
val helper = createHelper()
helper.createModuleNodes("a", "a.main")
helper.createModuleNode(MockModule("a.b"), root, model)
assertTreeEqual("""
-root
-a
a.b
a.main
""")
}
fun `test remove module node`() {
val helper = createHelper()
val nodes = helper.createModuleNodes("a.main", "a.util", "b")
assertTreeEqual("""
-root
-a
a.main
a.util
b
""")
helper.removeNode(nodes[0].first, root, model)
assertTreeEqual("""
-root
a.util
b
""")
helper.removeNode(nodes[1].first, root, model)
assertTreeEqual("""
-root
b
""")
}
fun `test remove module node with disabled compacting`() {
val helper = createHelper(compactGroupNodes = false)
val nodes = helper.createModuleNodes("a.main", "a.util", "b")
assertTreeEqual("""
-root
-a
a.main
a.util
b
""")
helper.removeNode(nodes[0].first, root, model)
assertTreeEqual("""
-root
-a
a.util
b
""")
helper.removeNode(nodes[1].first, root, model)
assertTreeEqual("""
-root
b
""")
}
private fun moveModuleNodeToProperGroupAndCheckResult(node: Pair<MockModuleTreeNode, MockModule>,
expected: String, compactGroupNodes: Boolean = true) {
val thisNode: (MockModuleTreeNode) -> Boolean = { it == node.first }
val helper = createHelperFromTree(nodeToBeMovedFilter = thisNode, compactGroupNodes = compactGroupNodes)
helper.checkConsistency(nodeToBeMovedFilter = thisNode)
helper.moveModuleNodeToProperGroup(node.first, node.second, root, model, tree)
assertTreeEqual(expected)
helper.checkConsistency(nodeToBeMovedFilter = {false})
}
private fun ModuleGroupingTreeHelper<MockModule, MockModuleTreeNode>.moveAllModuleNodesAndCheckResult(expected: String) {
checkConsistency(nodeToBeMovedFilter = {true})
moveAllModuleNodesToProperGroups(root, model)
assertTreeEqual(expected)
checkConsistency(nodeToBeMovedFilter = {false})
}
private fun ModuleGroupingTreeHelper<MockModule, MockModuleTreeNode>.createModuleNodes(vararg names: String): List<Pair<MockModuleTreeNode, MockModule>> {
val nodes = createModuleNodes(names.map { MockModule(it) }, root, model)
checkConsistency { false }
return nodes.map { Pair(it, (it as MockModuleNode).module)}
}
private fun assertTreeEqual(expected: String) {
PlatformTestUtil.expandAll(tree)
PlatformTestUtil.assertTreeEqual(tree, expected.trimIndent() + "\n")
}
private fun createHelper(enableGrouping: Boolean = true, compactGroupNodes: Boolean = true): ModuleGroupingTreeHelper<MockModule, MockModuleTreeNode> {
return ModuleGroupingTreeHelper.forEmptyTree(enableGrouping, MockModuleGrouping(compactGroupNodes), ::MockModuleGroupNode, ::MockModuleNode, nodeComparator)
}
private fun createHelperFromTree(enableGrouping: Boolean = true, compactGroupNodes: Boolean = true, nodeToBeMovedFilter: (MockModuleTreeNode) -> Boolean = {true}): ModuleGroupingTreeHelper<MockModule, MockModuleTreeNode> {
return ModuleGroupingTreeHelper.forTree(root, { it.moduleGroup }, { (it as? MockModuleNode)?.module },
enableGrouping, MockModuleGrouping(compactGroupNodes), ::MockModuleGroupNode, ::MockModuleNode, nodeComparator,
nodeToBeMovedFilter)
}
private fun ModuleGroupingTreeHelper<MockModule, MockModuleTreeNode>.checkConsistency(nodeToBeMovedFilter: (MockModuleTreeNode) -> Boolean) {
val expectedNodeForGroup = HashMap<ModuleGroup, MockModuleTreeNode>(getNodeForGroupMap())
val expectedNodeVirtualGroupToChildNode = HashMap<ModuleGroup, MockModuleTreeNode>(getVirtualGroupToChildNodeMap())
val expectedGroupByNode = HashMap<MockModuleTreeNode, ModuleGroup>(getGroupByNodeMap())
val expectedModuleByNode = HashMap<MockModuleTreeNode, MockModule>(getModuleByNodeMap())
TreeUtil.treeNodeTraverser(root).postOrderDfsTraversal().forEach { o ->
val node = o as MockModuleTreeNode
if (node == root) return@forEach
if (node is MockModuleNode) {
TestCase.assertEquals(node.module, expectedModuleByNode[node])
expectedModuleByNode.remove(node)
}
if (!nodeToBeMovedFilter(node)) {
val parentGroupPath = when (node) {
is MockModuleNode -> MockModuleGrouping().getGroupPath(node.module)
is MockModuleGroupNode -> node.moduleGroup.groupPath.dropLast(1)
else -> emptyList()
}
for (i in parentGroupPath.size downTo 1) {
val parentGroup = ModuleGroup(parentGroupPath.subList(0, i))
val childNode = expectedNodeVirtualGroupToChildNode.remove(parentGroup)
if (childNode != null) {
TestCase.assertEquals(childNode, node)
TestCase.assertNull("There are both virtual and real nodes for '${parentGroup.qualifiedName}' group",
expectedNodeForGroup[parentGroup])
}
else if (isGroupingEnabled()) {
TestCase.assertNotNull("There is no virtual or real node for '${parentGroup.qualifiedName}' group",
expectedNodeForGroup[parentGroup])
break
}
}
}
val moduleGroup = node.moduleGroup
TestCase.assertSame(node, expectedNodeForGroup[moduleGroup])
expectedNodeForGroup.remove(moduleGroup)
TestCase.assertEquals(moduleGroup, expectedGroupByNode[node])
expectedGroupByNode.remove(node)
}
assertEmpty("Unexpected nodes in helper", expectedNodeForGroup.entries)
assertEmpty("Unexpected groups in helper", expectedGroupByNode.entries)
assertEmpty("Unexpected modules in helper", expectedModuleByNode.entries)
if (TreeUtil.treeNodeTraverser(root).none { nodeToBeMovedFilter(it as MockModuleTreeNode) }) {
assertEmpty("Unexpected virtual groups in helper", expectedNodeVirtualGroupToChildNode.entries)
}
}
}
private val nodeComparator = Comparator.comparing { node: MockModuleTreeNode -> node.text }
private open class MockModuleTreeNode(userObject: Any, val text: String = userObject.toString()): DefaultMutableTreeNode(text) {
open val moduleGroup: ModuleGroup? = null
override fun toString() = text
}
private class MockModuleGrouping(override val compactGroupNodes: Boolean = true) : ModuleGroupingImplementation<MockModule> {
override fun getGroupPath(m: MockModule) = m.name.split('.').dropLast(1)
override fun getModuleAsGroupPath(m: MockModule) = m.name.split('.')
}
private class MockModule(var name: String)
private class MockModuleNode(val module: MockModule): MockModuleTreeNode(module, module.name) {
override val moduleGroup = ModuleGroup(MockModuleGrouping().getModuleAsGroupPath(module))
}
private class MockModuleGroupNode(override val moduleGroup: ModuleGroup): MockModuleTreeNode(moduleGroup) | platform/lang-impl/testSources/com/intellij/ide/projectView/ModuleGroupingTreeHelperTest.kt | 3759068016 |
package com.onyxdevtools.server.entities
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.annotations.*
import com.onyx.persistence.annotations.values.CascadePolicy
import com.onyx.persistence.annotations.values.RelationshipType
@Entity
class Actor : Person(), IManagedEntity {
@Identifier
var actorId: Int = 0
@Relationship(type = RelationshipType.MANY_TO_ONE, cascadePolicy = CascadePolicy.NONE, inverseClass = Movie::class, inverse = "actors")
@Suppress("unused")
var movie: Movie? = null
}
| onyx-database-tests/src/main/kotlin/com/onyxdevtools/server/entities/Actor.kt | 2247971017 |
class ConvertToInit {
fun foo() {}
fun bar() {}
constructor(<caret>) {
foo()
bar()
}
fun baz() {}
} | plugins/kotlin/idea/tests/testData/intentions/convertSecondaryConstructorToPrimary/init.kt | 1161076827 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.inference.common
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
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.KotlinType
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
abstract class ContextCollector(private val resolutionFacade: ResolutionFacade) {
private fun KotlinType.classReference(): ClassReference? =
when (val descriptor = constructor.declarationDescriptor) {
is ClassDescriptor -> descriptor.classReference
is TypeParameterDescriptor -> TypeParameterReference(descriptor)
else -> null
}
private fun KtTypeElement.toData(): TypeElementData? {
val typeReference = parent as? KtTypeReference ?: return null
val type = analyze(resolutionFacade)[BindingContext.TYPE, typeReference] ?: return null
val typeParameterDescriptor = type.constructor
.declarationDescriptor
?.safeAs<TypeParameterDescriptor>() ?: return TypeElementDataImpl(this, type)
return TypeParameterElementData(this, type, typeParameterDescriptor)
}
fun collectTypeVariables(elements: List<KtElement>): InferenceContext {
val declarationToTypeVariable = mutableMapOf<KtNamedDeclaration, TypeVariable>()
val typeElementToTypeVariable = mutableMapOf<KtTypeElement, TypeVariable>()
val typeBasedTypeVariables = mutableListOf<TypeBasedTypeVariable>()
fun KtTypeReference.toBoundType(
owner: TypeVariableOwner,
alreadyCalculatedType: KotlinType? = null,
defaultState: State? = null
): BoundType? {
val typeElement = typeElement ?: return null
val type = alreadyCalculatedType ?: analyze(resolutionFacade, BodyResolveMode.PARTIAL)[BindingContext.TYPE, this]
val classReference = type?.classReference() ?: NoClassReference
val state = defaultState ?: classReference.getState(typeElement)
val typeArguments =
if (classReference is DescriptorClassReference) {
val typeParameters = classReference.descriptor.declaredTypeParameters
typeElement.typeArgumentsAsTypes.mapIndexed { index, typeArgument ->
TypeParameter(
typeArgument?.toBoundType(
owner,
alreadyCalculatedType = type?.arguments?.getOrNull(index)?.type
) ?: BoundType.STAR_PROJECTION,
typeParameters.getOrNull(index)?.variance ?: Variance.INVARIANT
)
}
} else emptyList()
val typeVariable = TypeElementBasedTypeVariable(
classReference,
typeArguments,
typeElement.toData() ?: return null,
owner,
state
)
typeElementToTypeVariable[typeElement] = typeVariable
return typeVariable.asBoundType()
}
fun KotlinType.toBoundType(): BoundType? {
val classReference = classReference() ?: NoClassReference
val state = classReference.getState(typeElement = null)
val typeArguments =
if (classReference is DescriptorClassReference) {
arguments.zip(classReference.descriptor.declaredTypeParameters) { typeArgument, typeParameter ->
TypeParameter(
typeArgument.type.toBoundType() ?: BoundType.STAR_PROJECTION,
typeParameter.variance
)
}
} else emptyList()
val typeVariable = TypeBasedTypeVariable(
classReference,
typeArguments,
this,
state
)
typeBasedTypeVariables += typeVariable
return typeVariable.asBoundType()
}
val substitutors = mutableMapOf<ClassDescriptor, SuperTypesSubstitutor>()
fun isOrAsExpression(typeReference: KtTypeReference) {
val typeElement = typeReference.typeElement ?: return
val typeVariable = typeReference.toBoundType(OtherTarget)?.typeVariable ?: return
typeElementToTypeVariable[typeElement] = typeVariable
}
for (element in elements) {
element.forEachDescendantOfType<KtExpression> { expression ->
if (expression is KtCallableDeclaration
&& (expression is KtParameter
|| expression is KtProperty
|| expression is KtNamedFunction)
) run {
val typeReference = expression.typeReference ?: return@run
val typeVariable = typeReference.toBoundType(
when (expression) {
is KtParameter -> expression.getStrictParentOfType<KtFunction>()?.let(::FunctionParameter)
is KtFunction -> FunctionReturnType(expression)
is KtProperty -> Property(expression)
else -> null
} ?: OtherTarget
)?.typeVariable ?: return@run
declarationToTypeVariable[expression] = typeVariable
}
if (expression is KtTypeParameterListOwner) {
for (typeParameter in expression.typeParameters) {
typeParameter.extendsBound?.toBoundType(OtherTarget, defaultState = State.UPPER)
}
for (constraint in expression.typeConstraints) {
constraint.boundTypeReference?.toBoundType(OtherTarget, defaultState = State.UPPER)
}
}
when (expression) {
is KtClassOrObject -> {
for (entry in expression.superTypeListEntries) {
for (argument in entry.typeReference?.typeElement?.typeArgumentsAsTypes ?: continue) {
argument?.toBoundType(OtherTarget)
}
}
val descriptor =
expression.resolveToDescriptorIfAny(resolutionFacade) ?: return@forEachDescendantOfType
substitutors[descriptor] =
SuperTypesSubstitutor.createFromKtClass(expression, resolutionFacade) ?: return@forEachDescendantOfType
for (typeParameter in expression.typeParameters) {
val typeVariable = typeParameter.resolveToDescriptorIfAny(resolutionFacade)
?.safeAs<TypeParameterDescriptor>()
?.defaultType
?.toBoundType()
?.typeVariable
?: continue
declarationToTypeVariable[typeParameter] = typeVariable
}
}
is KtCallExpression ->
for (typeArgument in expression.typeArguments) {
typeArgument.typeReference?.toBoundType(TypeArgument)
}
is KtLambdaExpression -> {
val context = expression.analyze(resolutionFacade)
val returnType = expression.getType(context)?.arguments?.lastOrNull()?.type ?: return@forEachDescendantOfType
val typeVariable = returnType.toBoundType()?.typeVariable ?: return@forEachDescendantOfType
declarationToTypeVariable[expression.functionLiteral] = typeVariable
}
is KtBinaryExpressionWithTypeRHS -> {
isOrAsExpression(expression.right ?: return@forEachDescendantOfType)
}
is KtIsExpression -> {
isOrAsExpression(expression.typeReference ?: return@forEachDescendantOfType)
}
}
}
}
val typeVariables =
(typeElementToTypeVariable.values + declarationToTypeVariable.values + typeBasedTypeVariables).distinct()
return InferenceContext(
elements,
typeVariables,
typeElementToTypeVariable,
declarationToTypeVariable,
declarationToTypeVariable.mapNotNull { (key, value) ->
key.resolveToDescriptorIfAny(resolutionFacade)?.let { it to value }
}.toMap(),
substitutors
)
}
abstract fun ClassReference.getState(typeElement: KtTypeElement?): State
} | plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/inference/common/ContextCollector.kt | 2269533465 |
package com.apkfuns.circleprogressview
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.apkfuns.circleprogressview", appContext.packageName)
}
}
| HenCoderSample/circleprogressview/src/androidTest/java/com/apkfuns/circleprogressview/ExampleInstrumentedTest.kt | 3222467120 |
/*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.sleuth.instrument.kotlin
import kotlinx.coroutines.reactor.ReactorContext
import org.springframework.cloud.sleuth.CurrentTraceContext
import org.springframework.cloud.sleuth.Span
import org.springframework.cloud.sleuth.TraceContext
import org.springframework.cloud.sleuth.Tracer
import org.springframework.util.ClassUtils
import kotlin.coroutines.CoroutineContext
import kotlin.reflect.jvm.internal.impl.load.kotlin.KotlinClassFinder
/**
* Returns a [CoroutineContext] which will make this [Context] current when resuming a coroutine
* and restores the previous [Context] on suspension.
*
* Inspired by OpenTelemetry's asContextElement.
* @since 3.1.0
*/
fun Tracer.asContextElement(): CoroutineContext {
return KotlinContextElement(this)
}
/**
* Returns the [Span] in this [CoroutineContext] if present, or null otherwise.
*
* Inspired by OpenTelemetry's asContextElement.
* @since 3.1.0
*/
fun CoroutineContext.currentSpan(): Span? {
val element = get(KotlinContextElement.KEY)
if (element is KotlinContextElement) {
return element.span
}
if (!ClassUtils.isPresent("kotlinx.coroutines.reactor.ReactorContext", null)) {
return null
}
val reactorContext = get(ReactorContext.Key)
if (reactorContext != null) {
if (reactorContext.context.hasKey(Span::class.java)) {
return reactorContext.context.get(Span::class.java)
}
else if (reactorContext.context.hasKey(TraceContext::class.java) && reactorContext.context.hasKey(Tracer::class.java) && reactorContext.context.hasKey(CurrentTraceContext::class.java)) {
val traceContext = reactorContext.context.get(TraceContext::class.java)
reactorContext.context.get(CurrentTraceContext::class.java).maybeScope(traceContext).use {
return reactorContext.context.get(Tracer::class.java).currentSpan()
}
}
else if (reactorContext.context.hasKey(Tracer::class.java)) {
return reactorContext.context.get(Tracer::class.java).currentSpan()
}
}
return null
}
| spring-cloud-sleuth-instrumentation/src/main/kotlin/org/springframework/cloud/sleuth/instrument/kotlin/asContextElement.kt | 2106181151 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.diff.tools.combined
import com.intellij.diff.editor.DiffRequestProcessorEditorBase
import javax.swing.JComponent
class CombinedDiffRequestProcessorEditor(file: CombinedDiffVirtualFile<*>, private val processor: CombinedDiffRequestProcessor) :
DiffRequestProcessorEditorBase(file, processor.component, processor.ourDisposable, processor.context) {
override fun getPreferredFocusedComponent(): JComponent? = processor.preferedFocusedComponent
}
| platform/diff-impl/src/com/intellij/diff/tools/combined/CombinedDiffRequestProcessorEditor.kt | 2713984347 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.logging
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.ui.ListTable
import com.intellij.codeInspection.ui.ListWrappingTableModel
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.Accessor
import com.intellij.util.xmlb.SerializationFilterBase
import com.intellij.util.xmlb.XmlSerializer
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.ui.UiUtils
import org.jdom.Element
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import javax.swing.JComponent
class KotlinLoggerInitializedWithForeignClassInspection : AbstractKotlinInspection() {
companion object {
private val DEFAULT_LOGGER_FACTORIES = listOf(
"java.util.logging.Logger" to "getLogger",
"org.slf4j.LoggerFactory" to "getLogger",
"org.apache.commons.logging.LogFactory" to "getLog",
"org.apache.log4j.Logger" to "getLogger",
"org.apache.logging.log4j.LogManager" to "getLogger",
)
private val DEFAULT_LOGGER_FACTORY_CLASS_NAMES = DEFAULT_LOGGER_FACTORIES.map { it.first }
private val DEFAULT_LOGGER_FACTORY_METHOD_NAMES = DEFAULT_LOGGER_FACTORIES.map { it.second }
private val DEFAULT_LOGGER_FACTORY_CLASS_NAME = BaseInspection.formatString(DEFAULT_LOGGER_FACTORY_CLASS_NAMES)
private val DEFAULT_LOGGER_FACTORY_METHOD_NAME = BaseInspection.formatString(DEFAULT_LOGGER_FACTORY_METHOD_NAMES)
}
@Suppress("MemberVisibilityCanBePrivate")
var loggerFactoryClassName: String = DEFAULT_LOGGER_FACTORY_CLASS_NAME
@Suppress("MemberVisibilityCanBePrivate")
var loggerFactoryMethodName: String = DEFAULT_LOGGER_FACTORY_METHOD_NAME
private val loggerFactoryClassNames = DEFAULT_LOGGER_FACTORY_CLASS_NAMES.toMutableList()
private val loggerFactoryMethodNames = DEFAULT_LOGGER_FACTORY_METHOD_NAMES.toMutableList()
private val loggerFactoryFqNames
get() = loggerFactoryClassNames.zip(loggerFactoryMethodNames).groupBy(
{ (_, methodName) -> methodName },
{ (className, methodName) -> FqName("${className}.${methodName}") }
)
@Suppress("DialogTitleCapitalization")
override fun createOptionsPanel(): JComponent? {
val table = ListTable(
ListWrappingTableModel(
listOf(loggerFactoryClassNames, loggerFactoryMethodNames),
KotlinBundle.message("title.logger.factory.class.name"),
KotlinBundle.message("title.logger.factory.method.name")
)
)
return UiUtils.createAddRemoveTreeClassChooserPanel(table, KotlinBundle.message("title.choose.logger.factory.class"))
}
override fun readSettings(element: Element) {
super.readSettings(element)
BaseInspection.parseString(loggerFactoryClassName, loggerFactoryClassNames)
BaseInspection.parseString(loggerFactoryMethodName, loggerFactoryMethodNames)
if (loggerFactoryClassNames.isEmpty() || loggerFactoryClassNames.size != loggerFactoryMethodNames.size) {
BaseInspection.parseString(DEFAULT_LOGGER_FACTORY_CLASS_NAME, loggerFactoryClassNames)
BaseInspection.parseString(DEFAULT_LOGGER_FACTORY_METHOD_NAME, loggerFactoryMethodNames)
}
}
override fun writeSettings(element: Element) {
loggerFactoryClassName = BaseInspection.formatString(loggerFactoryClassNames)
loggerFactoryMethodName = BaseInspection.formatString(loggerFactoryMethodNames)
XmlSerializer.serializeInto(this, element, object : SerializationFilterBase() {
override fun accepts(accessor: Accessor, bean: Any, beanValue: Any?): Boolean {
if (accessor.name == "loggerFactoryClassName" && beanValue == DEFAULT_LOGGER_FACTORY_CLASS_NAME) return false
if (accessor.name == "loggerFactoryMethodName" && beanValue == DEFAULT_LOGGER_FACTORY_METHOD_NAME) return false
return true
}
})
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = callExpressionVisitor(fun(call) {
val containingClassNames = call.containingClassNames()
if (containingClassNames.isEmpty()) return
val callee = call.calleeExpression ?: return
val loggerMethodFqNames = loggerFactoryFqNames[callee.text] ?: return
val argument = call.valueArguments.singleOrNull()?.getArgumentExpression() as? KtDotQualifiedExpression ?: return
val argumentSelector = argument.selectorExpression ?: return
val classLiteral = when (val argumentReceiver = argument.receiverExpression) {
// Foo::class.java, Foo::class.qualifiedName, Foo::class.simpleName
is KtClassLiteralExpression -> {
val selectorText = argumentSelector.safeAs<KtNameReferenceExpression>()?.text
if (selectorText !in listOf("java", "qualifiedName", "simpleName")) return
argumentReceiver
}
// Foo::class.java.name, Foo::class.java.simpleName, Foo::class.java.canonicalName
is KtDotQualifiedExpression -> {
val classLiteral = argumentReceiver.receiverExpression as? KtClassLiteralExpression ?: return
if (argumentReceiver.selectorExpression.safeAs<KtNameReferenceExpression>()?.text != "java") return
val selectorText = argumentSelector.safeAs<KtNameReferenceExpression>()?.text
?: argumentSelector.safeAs<KtCallExpression>()?.calleeExpression?.text
if (selectorText !in listOf("name", "simpleName", "canonicalName", "getName", "getSimpleName", "getCanonicalName")) return
classLiteral
}
else -> return
}
val classLiteralName = classLiteral.receiverExpression?.text ?: return
if (classLiteralName in containingClassNames) return
if (call.resolveToCall()?.resultingDescriptor?.fqNameOrNull() !in loggerMethodFqNames) return
holder.registerProblem(
classLiteral,
KotlinBundle.message("logger.initialized.with.foreign.class", "$classLiteralName::class"),
ReplaceForeignFix(containingClassNames.last())
)
})
private fun KtCallExpression.containingClassNames(): List<String> {
val classOrObject = getStrictParentOfType<KtClassOrObject>() ?: return emptyList()
return if (classOrObject is KtObjectDeclaration && classOrObject.isCompanion()) {
listOfNotNull(classOrObject.name, classOrObject.getStrictParentOfType<KtClass>()?.name)
} else {
listOfNotNull(classOrObject.name)
}
}
private class ReplaceForeignFix(private val containingClassName: String) : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.0", "$containingClassName::class")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val argument = descriptor.psiElement.getStrictParentOfType<KtValueArgument>()?.getArgumentExpression()
as? KtDotQualifiedExpression ?: return
val receiver = argument.receiverExpression
val selector = argument.selectorExpression ?: return
val psiFactory = KtPsiFactory(argument)
val newArgument = when (receiver) {
is KtClassLiteralExpression -> {
psiFactory.createExpressionByPattern("${containingClassName}::class.$0", selector)
}
is KtDotQualifiedExpression -> {
psiFactory.createExpressionByPattern("${containingClassName}::class.java.$0", selector)
}
else -> return
}
argument.replace(newArgument)
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/logging/KotlinLoggerInitializedWithForeignClassInspection.kt | 3586958987 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.execution.impl
import com.intellij.CommonBundle
import com.intellij.build.BuildContentManager
import com.intellij.execution.*
import com.intellij.execution.configuration.CompatibilityAwareRunProfile
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.configurations.RunConfiguration.RestartSingletonResult
import com.intellij.execution.configurations.RunProfile
import com.intellij.execution.configurations.RunProfileState
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.filters.TextConsoleBuilderFactory
import com.intellij.execution.impl.ExecutionManagerImpl.Companion.DELEGATED_RUN_PROFILE_KEY
import com.intellij.execution.impl.statistics.RunConfigurationUsageTriggerCollector
import com.intellij.execution.impl.statistics.RunConfigurationUsageTriggerCollector.RunConfigurationFinishType
import com.intellij.execution.impl.statistics.RunConfigurationUsageTriggerCollector.UI_SHOWN_STAGE
import com.intellij.execution.process.*
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ExecutionEnvironmentBuilder
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.execution.runners.ProgramRunner
import com.intellij.execution.target.TargetEnvironmentAwareRunProfile
import com.intellij.execution.target.TargetProgressIndicator
import com.intellij.execution.target.getEffectiveTargetName
import com.intellij.execution.ui.ConsoleView
import com.intellij.execution.ui.RunContentDescriptor
import com.intellij.execution.ui.RunContentManager
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.internal.statistic.StructuredIdeActivity
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.components.service
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.*
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.ToolWindow
import com.intellij.ui.AppUIUtil
import com.intellij.ui.UIBundle
import com.intellij.ui.content.ContentManager
import com.intellij.ui.content.impl.ContentImpl
import com.intellij.util.Alarm
import com.intellij.util.SmartList
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.annotations.*
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.resolvedPromise
import java.awt.BorderLayout
import java.io.OutputStream
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.Consumer
import javax.swing.JPanel
import javax.swing.SwingUtilities
class ExecutionManagerImpl(private val project: Project) : ExecutionManager(), Disposable {
companion object {
val LOG = logger<ExecutionManagerImpl>()
private val EMPTY_PROCESS_HANDLERS = emptyArray<ProcessHandler>()
internal val DELEGATED_RUN_PROFILE_KEY = Key.create<RunProfile>("DELEGATED_RUN_PROFILE_KEY")
@JvmField
val EXECUTION_SESSION_ID_KEY = ExecutionManager.EXECUTION_SESSION_ID_KEY
@JvmField
val EXECUTION_SKIP_RUN = ExecutionManager.EXECUTION_SKIP_RUN
@JvmStatic
fun getInstance(project: Project) = project.service<ExecutionManager>() as ExecutionManagerImpl
@JvmStatic
fun isProcessRunning(descriptor: RunContentDescriptor?): Boolean {
val processHandler = descriptor?.processHandler
return processHandler != null && !processHandler.isProcessTerminated
}
@JvmStatic
fun stopProcess(descriptor: RunContentDescriptor?) {
stopProcess(descriptor?.processHandler)
}
@JvmStatic
fun stopProcess(processHandler: ProcessHandler?) {
if (processHandler == null) {
return
}
processHandler.putUserData(ProcessHandler.TERMINATION_REQUESTED, true)
if (processHandler is KillableProcess && processHandler.isProcessTerminating) {
// process termination was requested, but it's still alive
// in this case 'force quit' will be performed
processHandler.killProcess()
return
}
if (!processHandler.isProcessTerminated) {
if (processHandler.detachIsDefault()) {
processHandler.detachProcess()
}
else {
processHandler.destroyProcess()
}
}
}
@JvmStatic
fun getAllDescriptors(project: Project): List<RunContentDescriptor> {
return project.serviceIfCreated<RunContentManager>()?.allDescriptors ?: emptyList()
}
@ApiStatus.Internal
@JvmStatic
fun setDelegatedRunProfile(runProfile: RunProfile, runProfileToDelegate: RunProfile) {
if (runProfile !== runProfileToDelegate && runProfile is UserDataHolder) {
DELEGATED_RUN_PROFILE_KEY[runProfile] = runProfileToDelegate
}
}
}
init {
val connection = ApplicationManager.getApplication().messageBus.connect(this)
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectClosed(project: Project) {
if (project === [email protected]) {
inProgress.clear()
}
}
})
}
@set:TestOnly
@Volatile
var forceCompilationInTests = false
private val awaitingTerminationAlarm = Alarm()
private val awaitingRunProfiles = HashMap<RunProfile, ExecutionEnvironment>()
private val runningConfigurations: MutableList<RunningConfigurationEntry> = ContainerUtil.createLockFreeCopyOnWriteList()
private val inProgress = Collections.synchronizedSet(HashSet<InProgressEntry>())
private fun processNotStarted(environment: ExecutionEnvironment, activity: StructuredIdeActivity?, e : Throwable? = null) {
RunConfigurationUsageTriggerCollector.logProcessFinished(activity, RunConfigurationFinishType.FAILED_TO_START)
val executorId = environment.executor.id
inProgress.remove(InProgressEntry(executorId, environment.runner.runnerId))
project.messageBus.syncPublisher(EXECUTION_TOPIC).processNotStarted(executorId, environment, e)
}
/**
* Internal usage only. Maybe removed or changed in any moment. No backward compatibility.
*/
@ApiStatus.Internal
override fun startRunProfile(environment: ExecutionEnvironment, starter: () -> Promise<RunContentDescriptor?>) {
doStartRunProfile(environment) {
// errors are handled by startRunProfile
starter()
.then { descriptor ->
if (descriptor != null) {
descriptor.executionId = environment.executionId
val toolWindowId = RunContentManager.getInstance(environment.project).getContentDescriptorToolWindowId(environment)
if (toolWindowId != null) {
descriptor.contentToolWindowId = toolWindowId
}
environment.runnerAndConfigurationSettings?.let {
descriptor.isActivateToolWindowWhenAdded = it.isActivateToolWindowBeforeRun
}
}
environment.callback?.let {
it.processStarted(descriptor)
environment.callback = null
}
descriptor
}
}
}
override fun startRunProfile(starter: RunProfileStarter, environment: ExecutionEnvironment) {
doStartRunProfile(environment) {
starter.executeAsync(environment)
}
}
private fun doStartRunProfile(environment: ExecutionEnvironment, task: () -> Promise<RunContentDescriptor>) {
val activity = triggerUsage(environment)
RunManager.getInstance(environment.project).refreshUsagesList(environment.runProfile)
val project = environment.project
val reuseContent = RunContentManager.getInstance(project).getReuseContent(environment)
if (reuseContent != null) {
reuseContent.executionId = environment.executionId
environment.contentToReuse = reuseContent
}
val executor = environment.executor
inProgress.add(InProgressEntry(executor.id, environment.runner.runnerId))
project.messageBus.syncPublisher(EXECUTION_TOPIC).processStartScheduled(executor.id, environment)
val startRunnable = Runnable {
if (project.isDisposed) {
return@Runnable
}
project.messageBus.syncPublisher(EXECUTION_TOPIC).processStarting(executor.id, environment)
fun handleError(e: Throwable) {
processNotStarted(environment, activity, e)
if (e !is ProcessCanceledException) {
ProgramRunnerUtil.handleExecutionError(project, environment, e, environment.runProfile)
LOG.debug(e)
}
}
try {
task()
.onSuccess { descriptor ->
AppUIUtil.invokeLaterIfProjectAlive(project) {
if (descriptor == null) {
processNotStarted(environment, activity)
return@invokeLaterIfProjectAlive
}
val entry = RunningConfigurationEntry(descriptor, environment.runnerAndConfigurationSettings, executor)
runningConfigurations.add(entry)
Disposer.register(descriptor, Disposable { runningConfigurations.remove(entry) })
if (!descriptor.isHiddenContent && !environment.isHeadless) {
RunContentManager.getInstance(project).showRunContent(executor, descriptor, environment.contentToReuse)
}
activity?.stageStarted(UI_SHOWN_STAGE)
environment.contentToReuse = descriptor
val processHandler = descriptor.processHandler
if (processHandler != null) {
if (!processHandler.isStartNotified) {
project.messageBus.syncPublisher(EXECUTION_TOPIC).processStarting(executor.id, environment, processHandler)
processHandler.startNotify()
}
inProgress.remove(InProgressEntry(executor.id, environment.runner.runnerId))
project.messageBus.syncPublisher(EXECUTION_TOPIC).processStarted(executor.id, environment, processHandler)
val listener = ProcessExecutionListener(project, executor.id, environment, processHandler, descriptor, activity)
processHandler.addProcessListener(listener)
// Since we cannot guarantee that the listener is added before process handled is start notified,
// we have to make sure the process termination events are delivered to the clients.
// Here we check the current process state and manually deliver events, while
// the ProcessExecutionListener guarantees each such event is only delivered once
// either by this code, or by the ProcessHandler.
val terminating = processHandler.isProcessTerminating
val terminated = processHandler.isProcessTerminated
if (terminating || terminated) {
listener.processWillTerminate(ProcessEvent(processHandler), false /* doesn't matter */)
if (terminated) {
val exitCode = if (processHandler.isStartNotified) processHandler.exitCode ?: -1 else -1
listener.processTerminated(ProcessEvent(processHandler, exitCode))
}
}
}
}
}
.onError(::handleError)
}
catch (e: Throwable) {
handleError(e)
}
}
if (!forceCompilationInTests && ApplicationManager.getApplication().isUnitTestMode) {
startRunnable.run()
}
else {
compileAndRun(Runnable {
ApplicationManager.getApplication().invokeLater(startRunnable, project.disposed)
}, environment, Runnable {
if (!project.isDisposed) {
processNotStarted(environment, activity)
}
})
}
}
override fun dispose() {
for (entry in runningConfigurations) {
Disposer.dispose(entry.descriptor)
}
runningConfigurations.clear()
}
@Suppress("OverridingDeprecatedMember")
override fun getContentManager() = RunContentManager.getInstance(project)
override fun getRunningProcesses(): Array<ProcessHandler> {
var handlers: MutableList<ProcessHandler>? = null
for (descriptor in getAllDescriptors(project)) {
val processHandler = descriptor.processHandler ?: continue
if (handlers == null) {
handlers = SmartList()
}
handlers.add(processHandler)
}
return handlers?.toTypedArray() ?: EMPTY_PROCESS_HANDLERS
}
override fun compileAndRun(startRunnable: Runnable, environment: ExecutionEnvironment, onCancelRunnable: Runnable?) {
var id = environment.executionId
if (id == 0L) {
id = environment.assignNewExecutionId()
}
val profile = environment.runProfile
if (profile !is RunConfiguration) {
startRunnable.run()
return
}
val beforeRunTasks = doGetBeforeRunTasks(profile)
if (beforeRunTasks.isEmpty()) {
startRunnable.run()
return
}
val context = environment.dataContext
val projectContext = context ?: SimpleDataContext.getProjectContext(project)
val runBeforeRunExecutorMap = Collections.synchronizedMap(linkedMapOf<BeforeRunTask<*>, Executor>())
ApplicationManager.getApplication().executeOnPooledThread {
for (task in beforeRunTasks) {
val provider = BeforeRunTaskProvider.getProvider(project, task.providerId)
if (provider == null || task !is RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask) {
continue
}
val settings = task.settings
if (settings != null) {
// as side-effect here we setup runners list ( required for com.intellij.execution.impl.RunManagerImpl.canRunConfiguration() )
var executor = if (Registry.`is`("lock.run.executor.for.before.run.tasks", false)) {
DefaultRunExecutor.getRunExecutorInstance()
}
else {
environment.executor
}
val builder = ExecutionEnvironmentBuilder.createOrNull(executor, settings)
if (builder == null || !RunManagerImpl.canRunConfiguration(settings, executor)) {
executor = DefaultRunExecutor.getRunExecutorInstance()
if (!RunManagerImpl.canRunConfiguration(settings, executor)) {
// we should stop here as before run task cannot be executed at all (possibly it's invalid)
onCancelRunnable?.run()
ExecutionUtil.handleExecutionError(environment, ExecutionException(
ExecutionBundle.message("dialog.message.cannot.start.before.run.task", settings)))
return@executeOnPooledThread
}
}
runBeforeRunExecutorMap[task] = executor
}
}
for (task in beforeRunTasks) {
if (project.isDisposed) {
return@executeOnPooledThread
}
@Suppress("UNCHECKED_CAST")
val provider = BeforeRunTaskProvider.getProvider(project, task.providerId) as BeforeRunTaskProvider<BeforeRunTask<*>>?
if (provider == null) {
LOG.warn("Cannot find BeforeRunTaskProvider for id='${task.providerId}'")
continue
}
val builder = ExecutionEnvironmentBuilder(environment).contentToReuse(null)
val executor = runBeforeRunExecutorMap[task]
if (executor != null) {
builder.executor(executor)
}
val taskEnvironment = builder.build()
taskEnvironment.executionId = id
EXECUTION_SESSION_ID_KEY.set(taskEnvironment, id)
try {
if (!provider.executeTask(projectContext, profile, taskEnvironment, task)) {
if (onCancelRunnable != null) {
SwingUtilities.invokeLater(onCancelRunnable)
}
return@executeOnPooledThread
}
}
catch (e: ProcessCanceledException) {
if (onCancelRunnable != null) {
SwingUtilities.invokeLater(onCancelRunnable)
}
return@executeOnPooledThread
}
}
doRun(environment, startRunnable)
}
}
private fun doRun(environment: ExecutionEnvironment, startRunnable: Runnable) {
val allowSkipRun = environment.getUserData(EXECUTION_SKIP_RUN)
if (allowSkipRun != null && allowSkipRun) {
processNotStarted(environment, null)
return
}
// important! Do not use DumbService.smartInvokeLater here because it depends on modality state
// and execution of startRunnable could be skipped if modality state check fails
SwingUtilities.invokeLater {
if (project.isDisposed) {
return@invokeLater
}
val settings = environment.runnerAndConfigurationSettings
if (settings != null && !settings.type.isDumbAware && DumbService.isDumb(project)) {
DumbService.getInstance(project).runWhenSmart(startRunnable)
}
else {
try {
startRunnable.run()
}
catch (ignored: IndexNotReadyException) {
ExecutionUtil.handleExecutionError(environment, ExecutionException(
ExecutionBundle.message("dialog.message.cannot.start.while.indexing.in.progress")))
}
}
}
}
override fun restartRunProfile(project: Project,
executor: Executor,
target: ExecutionTarget,
configuration: RunnerAndConfigurationSettings?,
processHandler: ProcessHandler?,
environmentCustomization: Consumer<ExecutionEnvironment>?) {
val builder = createEnvironmentBuilder(project, executor, configuration)
if (processHandler != null) {
for (descriptor in getAllDescriptors(project)) {
if (descriptor.processHandler === processHandler) {
builder.contentToReuse(descriptor)
break
}
}
}
val environment = builder.target(target).build()
environmentCustomization?.accept(environment)
restartRunProfile(environment)
}
override fun restartRunProfile(environment: ExecutionEnvironment) {
val configuration = environment.runnerAndConfigurationSettings
val runningIncompatible: List<RunContentDescriptor>
if (configuration == null) {
runningIncompatible = emptyList()
}
else {
runningIncompatible = getIncompatibleRunningDescriptors(configuration)
}
val contentToReuse = environment.contentToReuse
val runningOfTheSameType = if (configuration != null && !configuration.configuration.isAllowRunningInParallel) {
getRunningDescriptors(Condition { it.isOfSameType(configuration) })
}
else if (isProcessRunning(contentToReuse)) {
listOf(contentToReuse!!)
}
else {
emptyList()
}
val runningToStop = ContainerUtil.concat(runningOfTheSameType, runningIncompatible)
if (runningToStop.isNotEmpty()) {
if (configuration != null) {
if (runningOfTheSameType.isNotEmpty() && (runningOfTheSameType.size > 1 || contentToReuse == null || runningOfTheSameType.first() !== contentToReuse)) {
val result = configuration.configuration.restartSingleton(environment)
if (result == RestartSingletonResult.NO_FURTHER_ACTION) {
return
}
if (result == RestartSingletonResult.ASK_AND_RESTART && !userApprovesStopForSameTypeConfigurations(environment.project, configuration.name, runningOfTheSameType.size)) {
return
}
}
if (runningIncompatible.isNotEmpty() && !userApprovesStopForIncompatibleConfigurations(project, configuration.name, runningIncompatible)) {
return
}
}
for (descriptor in runningToStop) {
stopProcess(descriptor)
}
}
if (awaitingRunProfiles[environment.runProfile] === environment) {
// defense from rerunning exactly the same ExecutionEnvironment
return
}
awaitingRunProfiles[environment.runProfile] = environment
awaitTermination(object : Runnable {
override fun run() {
if (awaitingRunProfiles[environment.runProfile] !== environment) {
// a new rerun has been requested before starting this one, ignore this rerun
return
}
if ((configuration != null && !configuration.type.isDumbAware && DumbService.getInstance(project).isDumb)
|| inProgress.contains(InProgressEntry(environment.executor.id, environment.runner.runnerId))) {
awaitTermination(this, 100)
return
}
for (descriptor in runningOfTheSameType) {
val processHandler = descriptor.processHandler
if (processHandler != null && !processHandler.isProcessTerminated) {
awaitTermination(this, 100)
return
}
}
awaitingRunProfiles.remove(environment.runProfile)
// start() can be called during restartRunProfile() after pretty long 'awaitTermination()' so we have to check if the project is still here
if (environment.project.isDisposed) {
return
}
val settings = environment.runnerAndConfigurationSettings
executeConfiguration(environment, settings != null && settings.isEditBeforeRun)
}
}, 50)
}
private class MyProcessHandler : ProcessHandler() {
override fun destroyProcessImpl() {}
override fun detachProcessImpl() {}
override fun detachIsDefault(): Boolean {
return false
}
override fun getProcessInput(): OutputStream? = null
public override fun notifyProcessTerminated(exitCode: Int) {
super.notifyProcessTerminated(exitCode)
}
}
override fun executePreparationTasks(environment: ExecutionEnvironment, currentState: RunProfileState): Promise<Any?> {
if (!(environment.runProfile is TargetEnvironmentAwareRunProfile)) {
return resolvedPromise()
}
val targetEnvironmentAwareRunProfile = environment.runProfile as TargetEnvironmentAwareRunProfile
if (!targetEnvironmentAwareRunProfile.needPrepareTarget()) {
return resolvedPromise()
}
val processHandler = MyProcessHandler()
val consoleView = TextConsoleBuilderFactory.getInstance().createBuilder(environment.project).console
ProcessTerminatedListener.attach(processHandler)
consoleView.attachToProcess(processHandler)
val component = TargetPrepareComponent(consoleView)
val buildContentManager = BuildContentManager.getInstance(environment.project)
val contentName = targetEnvironmentAwareRunProfile.getEffectiveTargetName(environment.project)?.let {
ExecutionBundle.message("tab.title.prepare.environment", it, environment.runProfile.name)
} ?: ExecutionBundle.message("tab.title.prepare.target.environment", environment.runProfile.name)
val toolWindow = buildContentManager.orCreateToolWindow
val contentManager: ContentManager = toolWindow.contentManager
val contentImpl = ContentImpl(component, contentName, true)
contentImpl.putUserData(ToolWindow.SHOW_CONTENT_ICON, java.lang.Boolean.TRUE)
contentImpl.icon = environment.runProfile.icon
for (content in contentManager.contents) {
if (contentName != content.displayName) continue
if (content.isPinned) continue
val contentComponent = content.component
if (contentComponent !is TargetPrepareComponent) continue
if (contentComponent.isPreparationFinished()) {
contentManager.removeContent(content, true)
}
}
contentManager.addContent(contentImpl)
contentManager.setSelectedContent(contentImpl)
toolWindow.activate(null)
val promise = AsyncPromise<Any?>()
ApplicationManager.getApplication().executeOnPooledThread {
try {
processHandler.startNotify()
val targetProgressIndicator = object : TargetProgressIndicator {
@Volatile
var stopped = false
override fun addText(text: @Nls String, key: Key<*>) {
processHandler.notifyTextAvailable(text, key)
}
override fun isCanceled(): Boolean {
return false
}
override fun stop() {
stopped = true
}
override fun isStopped(): Boolean = stopped
}
promise.setResult(environment.prepareTargetEnvironment(currentState, targetProgressIndicator))
}
catch (t: Throwable) {
LOG.warn(t)
promise.setError(ExecutionBundle.message("message.error.happened.0", t.localizedMessage))
processHandler.notifyTextAvailable(StringUtil.notNullize(t.localizedMessage), ProcessOutputType.STDERR)
processHandler.notifyTextAvailable("\n", ProcessOutputType.STDERR)
}
finally {
val exitCode = if (promise.isSucceeded) 0 else -1
processHandler.notifyProcessTerminated(exitCode)
component.setPreparationFinished()
}
}
return promise
}
@ApiStatus.Internal
fun executeConfiguration(environment: ExecutionEnvironment, showSettings: Boolean, assignNewId: Boolean = true) {
val runnerAndConfigurationSettings = environment.runnerAndConfigurationSettings
val project = environment.project
var runner = environment.runner
if (runnerAndConfigurationSettings != null) {
val targetManager = ExecutionTargetManager.getInstance(project)
if (!targetManager.doCanRun(runnerAndConfigurationSettings.configuration, environment.executionTarget)) {
ExecutionUtil.handleExecutionError(environment, ExecutionException(ProgramRunnerUtil.getCannotRunOnErrorMessage( environment.runProfile, environment.executionTarget)))
processNotStarted(environment, null)
return
}
if (!DumbService.isDumb(project)) {
if (showSettings && runnerAndConfigurationSettings.isEditBeforeRun) {
if (!RunDialog.editConfiguration(environment, ExecutionBundle.message("dialog.title.edit.configuration", 0))) {
processNotStarted(environment, null)
return
}
editConfigurationUntilSuccess(environment, assignNewId)
}
else {
inProgress.add(InProgressEntry(environment.executor.id, environment.runner.runnerId))
ReadAction.nonBlocking(Callable { RunManagerImpl.canRunConfiguration(environment) })
.finishOnUiThread(ModalityState.NON_MODAL) { canRun ->
inProgress.remove(InProgressEntry(environment.executor.id, environment.runner.runnerId))
if (canRun) {
executeConfiguration(environment, environment.runner, assignNewId, this.project, environment.runnerAndConfigurationSettings)
return@finishOnUiThread
}
if (!RunDialog.editConfiguration(environment, ExecutionBundle.message("dialog.title.edit.configuration", 0))) {
processNotStarted(environment, null)
return@finishOnUiThread
}
editConfigurationUntilSuccess(environment, assignNewId)
}
.expireWith(this)
.submit(AppExecutorUtil.getAppExecutorService())
}
return
}
}
executeConfiguration(environment, runner, assignNewId, project, runnerAndConfigurationSettings)
}
private fun editConfigurationUntilSuccess(environment: ExecutionEnvironment, assignNewId: Boolean) {
ReadAction.nonBlocking(Callable { RunManagerImpl.canRunConfiguration(environment) })
.finishOnUiThread(ModalityState.NON_MODAL) { canRun ->
val runAnyway = if (!canRun) {
val message = ExecutionBundle.message("dialog.message.configuration.still.incorrect.do.you.want.to.edit.it.again")
val title = ExecutionBundle.message("dialog.title.change.configuration.settings")
Messages.showYesNoDialog(project, message, title, CommonBundle.message("button.edit"), ExecutionBundle.message("run.continue.anyway"), Messages.getErrorIcon()) != Messages.YES
} else true
if (canRun || runAnyway) {
val runner = ProgramRunner.getRunner(environment.executor.id, environment.runnerAndConfigurationSettings!!.configuration)
if (runner == null) {
ExecutionUtil.handleExecutionError(environment,
ExecutionException(ExecutionBundle.message("dialog.message.cannot.find.runner",
environment.runProfile.name)))
}
else {
executeConfiguration(environment, runner, assignNewId, project, environment.runnerAndConfigurationSettings)
}
return@finishOnUiThread
}
if (!RunDialog.editConfiguration(environment, ExecutionBundle.message("dialog.title.edit.configuration", 0))) {
processNotStarted(environment, null)
return@finishOnUiThread
}
editConfigurationUntilSuccess(environment, assignNewId)
}
.expireWith(this)
.submit(AppExecutorUtil.getAppExecutorService())
}
private fun executeConfiguration(environment: ExecutionEnvironment,
runner: @NotNull ProgramRunner<*>,
assignNewId: Boolean,
project: @NotNull Project,
runnerAndConfigurationSettings: @Nullable RunnerAndConfigurationSettings?) {
try {
var effectiveEnvironment = environment
if (runner != effectiveEnvironment.runner) {
effectiveEnvironment = ExecutionEnvironmentBuilder(effectiveEnvironment).runner(runner).build()
}
if (assignNewId) {
effectiveEnvironment.assignNewExecutionId()
}
runner.execute(effectiveEnvironment)
}
catch (e: ExecutionException) {
ProgramRunnerUtil.handleExecutionError(project, environment, e, runnerAndConfigurationSettings?.configuration)
}
}
override fun isStarting(executorId: String, runnerId: String): Boolean {
return inProgress.contains(InProgressEntry(executorId, runnerId))
}
private fun awaitTermination(request: Runnable, delayMillis: Long) {
val app = ApplicationManager.getApplication()
if (app.isUnitTestMode) {
app.invokeLater(request, ModalityState.any())
}
else {
awaitingTerminationAlarm.addRequest(request, delayMillis)
}
}
private fun getIncompatibleRunningDescriptors(configurationAndSettings: RunnerAndConfigurationSettings): List<RunContentDescriptor> {
val configurationToCheckCompatibility = configurationAndSettings.configuration
return getRunningDescriptors(Condition { runningConfigurationAndSettings ->
val runningConfiguration = runningConfigurationAndSettings.configuration
if (runningConfiguration is CompatibilityAwareRunProfile) {
runningConfiguration.mustBeStoppedToRun(configurationToCheckCompatibility)
}
else {
false
}
})
}
fun getRunningDescriptors(condition: Condition<in RunnerAndConfigurationSettings>): List<RunContentDescriptor> {
val result = SmartList<RunContentDescriptor>()
for (entry in runningConfigurations) {
if (entry.settings != null && condition.value(entry.settings)) {
val processHandler = entry.descriptor.processHandler
if (processHandler != null /*&& !processHandler.isProcessTerminating()*/ && !processHandler.isProcessTerminated) {
result.add(entry.descriptor)
}
}
}
return result
}
fun getDescriptors(condition: Condition<in RunnerAndConfigurationSettings>): List<RunContentDescriptor> {
val result = SmartList<RunContentDescriptor>()
for (entry in runningConfigurations) {
if (entry.settings != null && condition.value(entry.settings)) {
result.add(entry.descriptor)
}
}
return result
}
fun getExecutors(descriptor: RunContentDescriptor): Set<Executor> {
val result = HashSet<Executor>()
for (entry in runningConfigurations) {
if (descriptor === entry.descriptor) {
result.add(entry.executor)
}
}
return result
}
fun getConfigurations(descriptor: RunContentDescriptor): Set<RunnerAndConfigurationSettings> {
val result = HashSet<RunnerAndConfigurationSettings>()
for (entry in runningConfigurations) {
if (descriptor === entry.descriptor && entry.settings != null) {
result.add(entry.settings)
}
}
return result
}
}
@ApiStatus.Internal
fun RunnerAndConfigurationSettings.isOfSameType(runnerAndConfigurationSettings: RunnerAndConfigurationSettings): Boolean {
if (this === runnerAndConfigurationSettings) return true
val thisConfiguration = configuration
val thatConfiguration = runnerAndConfigurationSettings.configuration
if (thisConfiguration === thatConfiguration) return true
if (this is RunnerAndConfigurationSettingsImpl &&
runnerAndConfigurationSettings is RunnerAndConfigurationSettingsImpl &&
this.filePathIfRunningCurrentFile != null) {
// These are special run configurations, which are used for running 'Current File' (a special item in the combobox). They are not stored in RunManager.
return this.filePathIfRunningCurrentFile == runnerAndConfigurationSettings.filePathIfRunningCurrentFile
}
if (thisConfiguration is UserDataHolder) {
val originalRunProfile = DELEGATED_RUN_PROFILE_KEY[thisConfiguration] ?: return false
if (originalRunProfile === thatConfiguration) return true
if (thatConfiguration is UserDataHolder) return originalRunProfile === DELEGATED_RUN_PROFILE_KEY[thatConfiguration]
}
return false
}
private fun triggerUsage(environment: ExecutionEnvironment): StructuredIdeActivity? {
val runConfiguration = environment.runnerAndConfigurationSettings?.configuration
val configurationFactory = runConfiguration?.factory ?: return null
return RunConfigurationUsageTriggerCollector.trigger(environment.project, configurationFactory, environment.executor, runConfiguration)
}
private fun createEnvironmentBuilder(project: Project,
executor: Executor,
configuration: RunnerAndConfigurationSettings?): ExecutionEnvironmentBuilder {
val builder = ExecutionEnvironmentBuilder(project, executor)
val runner = configuration?.let { ProgramRunner.getRunner(executor.id, it.configuration) }
if (runner == null && configuration != null) {
ExecutionManagerImpl.LOG.error("Cannot find runner for ${configuration.name}")
}
else if (runner != null) {
builder.runnerAndSettings(runner, configuration)
}
return builder
}
private fun userApprovesStopForSameTypeConfigurations(project: Project, configName: String, instancesCount: Int): Boolean {
val config = RunManagerImpl.getInstanceImpl(project).config
if (!config.isRestartRequiresConfirmation) {
return true
}
@Suppress("DuplicatedCode")
val option = object : DialogWrapper.DoNotAskOption {
override fun isToBeShown() = config.isRestartRequiresConfirmation
override fun setToBeShown(value: Boolean, exitCode: Int) {
config.isRestartRequiresConfirmation = value
}
override fun canBeHidden() = true
override fun shouldSaveOptionsOnCancel() = false
override fun getDoNotShowMessage(): String {
return UIBundle.message("dialog.options.do.not.show")
}
}
return Messages.showOkCancelDialog(
project,
ExecutionBundle.message("rerun.singleton.confirmation.message", configName, instancesCount),
ExecutionBundle.message("process.is.running.dialog.title", configName),
ExecutionBundle.message("rerun.confirmation.button.text"),
CommonBundle.getCancelButtonText(),
Messages.getQuestionIcon(), option) == Messages.OK
}
private fun userApprovesStopForIncompatibleConfigurations(project: Project,
configName: String,
runningIncompatibleDescriptors: List<RunContentDescriptor>): Boolean {
@Suppress("DuplicatedCode")
val config = RunManagerImpl.getInstanceImpl(project).config
@Suppress("DuplicatedCode")
if (!config.isStopIncompatibleRequiresConfirmation) {
return true
}
@Suppress("DuplicatedCode")
val option = object : DialogWrapper.DoNotAskOption {
override fun isToBeShown() = config.isStopIncompatibleRequiresConfirmation
override fun setToBeShown(value: Boolean, exitCode: Int) {
config.isStopIncompatibleRequiresConfirmation = value
}
override fun canBeHidden() = true
override fun shouldSaveOptionsOnCancel() = false
override fun getDoNotShowMessage(): String {
return UIBundle.message("dialog.options.do.not.show")
}
}
val names = StringBuilder()
for (descriptor in runningIncompatibleDescriptors) {
val name = descriptor.displayName
if (names.isNotEmpty()) {
names.append(", ")
}
names.append(if (name.isNullOrEmpty()) ExecutionBundle.message("run.configuration.no.name") else String.format("'%s'", name))
}
return Messages.showOkCancelDialog(
project,
ExecutionBundle.message("stop.incompatible.confirmation.message",
configName, names.toString(), runningIncompatibleDescriptors.size),
ExecutionBundle.message("incompatible.configuration.is.running.dialog.title", runningIncompatibleDescriptors.size),
ExecutionBundle.message("stop.incompatible.confirmation.button.text"),
CommonBundle.getCancelButtonText(),
Messages.getQuestionIcon(), option) == Messages.OK
}
private class ProcessExecutionListener(private val project: Project,
private val executorId: String,
private val environment: ExecutionEnvironment,
private val processHandler: ProcessHandler,
private val descriptor: RunContentDescriptor,
private val activity: StructuredIdeActivity?) : ProcessAdapter() {
private val willTerminateNotified = AtomicBoolean()
private val terminateNotified = AtomicBoolean()
override fun processTerminated(event: ProcessEvent) {
if (project.isDisposed || !terminateNotified.compareAndSet(false, true)) {
return
}
ApplicationManager.getApplication().invokeLater(Runnable {
val ui = descriptor.runnerLayoutUi
if (ui != null && !ui.isDisposed) {
ui.updateActionsNow()
}
}, ModalityState.any(), project.disposed)
project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processTerminated(executorId, environment, processHandler, event.exitCode)
val runConfigurationFinishType =
if (event.processHandler.getUserData(ProcessHandler.TERMINATION_REQUESTED) == true) RunConfigurationFinishType.TERMINATED
else RunConfigurationFinishType.UNKNOWN
RunConfigurationUsageTriggerCollector.logProcessFinished(activity, runConfigurationFinishType)
processHandler.removeProcessListener(this)
SaveAndSyncHandler.getInstance().scheduleRefresh()
}
override fun processWillTerminate(event: ProcessEvent, shouldNotBeUsed: Boolean) {
if (project.isDisposed || !willTerminateNotified.compareAndSet(false, true)) {
return
}
project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processTerminating(executorId, environment, processHandler)
}
}
private data class InProgressEntry(val executorId: String, val runnerId: String)
private data class RunningConfigurationEntry(val descriptor: RunContentDescriptor,
val settings: RunnerAndConfigurationSettings?,
val executor: Executor)
private class TargetPrepareComponent(val console: ConsoleView) : JPanel(BorderLayout()), Disposable {
init {
add(console.component, BorderLayout.CENTER)
}
@Volatile
private var finished = false
fun isPreparationFinished() = finished
fun setPreparationFinished() {
finished = true
}
override fun dispose() {
Disposer.dispose(console)
}
}
| platform/execution-impl/src/com/intellij/execution/impl/ExecutionManagerImpl.kt | 2360704914 |
package org.jetbrains.completion.full.line.kotlin
import com.intellij.ui.IconManager
import org.jetbrains.completion.full.line.language.IconSet
import org.jetbrains.kotlin.idea.KotlinIcons
import javax.swing.Icon
class KotlinIconSet : IconSet {
override val regular: Icon = KotlinIcons.SMALL_LOGO
override val redCode: Icon = IconManager.getInstance().getIcon("/icons/kotlin/redCode.svg", this::class.java)
}
| plugins/full-line/kotlin/src/org/jetbrains/completion/full/line/kotlin/KotlinIconSet.kt | 3716821055 |
// 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.openapi.vcs.changes
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.util.NullableFunction
import com.intellij.util.PairConsumer
/**
* Contains specific commit data used in the commit flow.
*
* It can be used to pass data between
* [com.intellij.openapi.vcs.changes.CommitExecutor] or [com.intellij.openapi.vcs.checkin.CheckinHandler] and
* [com.intellij.openapi.vcs.changes.CommitSession] or [com.intellij.openapi.vcs.checkin.CheckinEnvironment].
*
* For example:
* - if "amend commit" should be performed instead of the usual commit (`CommitContext.isAmendCommitMode`).
* - if "commit and push" was invoked and so push should start right after commit (`CommitContext.isPushAfterCommit`)
* - if "commit renames separately" mode should be used (`CommitContext.isCommitRenamesSeparately`)
*
* @see com.intellij.vcs.commit.commitProperty
*/
class CommitContext : UserDataHolderBase() {
private val _additionalData = HashMap<Any, Any>()
/**
* See [com.intellij.openapi.vcs.checkin.CheckinHandler.beforeCheckin] for (... additionalDataConsumer: PairConsumer<> ...)
*/
@Deprecated("Use CommitContext")
val additionalDataConsumer: PairConsumer<Any, Any> = PairConsumer { key, value -> _additionalData[key] = value }
/**
* See [com.intellij.openapi.vcs.checkin.CheckinEnvironment.commit] for (... parametersHolder: NullableFunction<> ...)
*/
@Deprecated("Use CommitContext")
val additionalData: NullableFunction<Any, Any> = NullableFunction { key -> _additionalData[key] }
}
| platform/vcs-api/vcs-api-core/src/com/intellij/openapi/vcs/changes/CommitContext.kt | 1965124160 |
package other
class SpecificStream
class SimpleStream
| plugins/kotlin/completion/tests/testData/weighers/basic/parameterNameAndType/MoreWordsMatchFirst.Data.kt | 3322501608 |
// "Add non-null asserted (!!) call" "true"
fun foo(a: Int?) {
a.<caret>plus(1)
}
| plugins/kotlin/idea/tests/testData/quickfix/expressions/unsafeCall3.kt | 361048903 |
// "Convert 'Int.() -> Int' to '(Int) -> Int'" "true"
expect fun foo(n: Int, action: <caret>Int.() -> Int): Int
fun test() {
foo(1) { this + 1 }
} | plugins/kotlin/idea/tests/testData/multiModuleQuickFix/other/functionTypeReceiverToParameterByHeader/header/header.kt | 4262518302 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.