content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.projectRoots.impl.jdkDownloader import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction class RuntimeChooserAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { RuntimeChooserUtil.showRuntimeChooserPopup() } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } }
platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/RuntimeChooser.kt
2583056682
/** * Some documentation * on two lines. */ fun testMethod() { } fun test() { <caret>testMethod() } //INFO: <div class='definition'><pre><span style="color:#000080;font-weight:bold;">public</span> <span style="color:#000080;font-weight:bold;">fun</span> <span style="color:#000000;">testMethod</span>()<span style="">: </span><span style="color:#000000;">Unit</span></pre></div><div class='content'><p style='margin-top:0;padding-top:0;'>Some documentation on two lines.</p></div><table class='sections'></table><div class='bottom'><icon src="/org/jetbrains/kotlin/idea/icons/kotlin_file.svg"/>&nbsp;OnMethodUsageMultiline.kt<br/></div>
plugins/kotlin/idea/tests/testData/editor/quickDoc/OnMethodUsageMultiline.kt
169564983
package org.thoughtcrime.securesms.notifications.v2 import androidx.annotation.WorkerThread import org.signal.core.util.CursorUtil import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.database.MmsSmsColumns import org.thoughtcrime.securesms.database.MmsSmsDatabase import org.thoughtcrime.securesms.database.RecipientDatabase import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.database.model.MessageId import org.thoughtcrime.securesms.database.model.MessageRecord import org.thoughtcrime.securesms.database.model.ReactionRecord import org.thoughtcrime.securesms.notifications.profiles.NotificationProfile import org.thoughtcrime.securesms.recipients.Recipient /** * Queries the message databases to determine messages that should be in notifications. */ object NotificationStateProvider { private val TAG = Log.tag(NotificationStateProvider::class.java) @WorkerThread fun constructNotificationState(stickyThreads: Map<ConversationId, MessageNotifierV2.StickyThread>, notificationProfile: NotificationProfile?): NotificationStateV2 { val messages: MutableList<NotificationMessage> = mutableListOf() SignalDatabase.mmsSms.getMessagesForNotificationState(stickyThreads.values).use { unreadMessages -> if (unreadMessages.count == 0) { return NotificationStateV2.EMPTY } MmsSmsDatabase.readerFor(unreadMessages).use { reader -> var record: MessageRecord? = reader.next while (record != null) { val threadRecipient: Recipient? = SignalDatabase.threads.getRecipientForThreadId(record.threadId) if (threadRecipient != null) { val hasUnreadReactions = CursorUtil.requireInt(unreadMessages, MmsSmsColumns.REACTIONS_UNREAD) == 1 val conversationId = ConversationId.fromMessageRecord(record) val parentRecord = conversationId.groupStoryId?.let { SignalDatabase.mms.getMessageRecord(it) } val hasSelfRepliedToGroupStory = conversationId.groupStoryId?.let { SignalDatabase.mms.hasSelfReplyInGroupStory(it) } messages += NotificationMessage( messageRecord = record, reactions = if (hasUnreadReactions) SignalDatabase.reactions.getReactions(MessageId(record.id, record.isMms)) else emptyList(), threadRecipient = threadRecipient, thread = conversationId, stickyThread = stickyThreads.containsKey(conversationId), isUnreadMessage = CursorUtil.requireInt(unreadMessages, MmsSmsColumns.READ) == 0, hasUnreadReactions = hasUnreadReactions, lastReactionRead = CursorUtil.requireLong(unreadMessages, MmsSmsColumns.REACTIONS_LAST_SEEN), isParentStorySentBySelf = parentRecord?.isOutgoing ?: false, hasSelfRepliedToStory = hasSelfRepliedToGroupStory ?: false ) } try { record = reader.next } catch (e: IllegalStateException) { // XXX Weird SQLCipher bug that's being investigated record = null Log.w(TAG, "Failed to read next record!", e) } } } } val conversations: MutableList<NotificationConversation> = mutableListOf() val muteFilteredMessages: MutableList<NotificationStateV2.FilteredMessage> = mutableListOf() val profileFilteredMessages: MutableList<NotificationStateV2.FilteredMessage> = mutableListOf() messages.groupBy { it.thread } .forEach { (thread, threadMessages) -> var notificationItems: MutableList<NotificationItemV2> = mutableListOf() for (notification: NotificationMessage in threadMessages) { when (notification.includeMessage(notificationProfile)) { MessageInclusion.INCLUDE -> notificationItems.add(MessageNotification(notification.threadRecipient, notification.messageRecord)) MessageInclusion.EXCLUDE -> Unit MessageInclusion.MUTE_FILTERED -> muteFilteredMessages += NotificationStateV2.FilteredMessage(notification.messageRecord.id, notification.messageRecord.isMms) MessageInclusion.PROFILE_FILTERED -> profileFilteredMessages += NotificationStateV2.FilteredMessage(notification.messageRecord.id, notification.messageRecord.isMms) } if (notification.hasUnreadReactions) { notification.reactions.forEach { when (notification.includeReaction(it, notificationProfile)) { MessageInclusion.INCLUDE -> notificationItems.add(ReactionNotification(notification.threadRecipient, notification.messageRecord, it)) MessageInclusion.EXCLUDE -> Unit MessageInclusion.MUTE_FILTERED -> muteFilteredMessages += NotificationStateV2.FilteredMessage(notification.messageRecord.id, notification.messageRecord.isMms) MessageInclusion.PROFILE_FILTERED -> profileFilteredMessages += NotificationStateV2.FilteredMessage(notification.messageRecord.id, notification.messageRecord.isMms) } } } } notificationItems.sort() if (notificationItems.isNotEmpty() && stickyThreads.containsKey(thread) && !notificationItems.last().individualRecipient.isSelf) { val indexOfOldestNonSelfMessage: Int = notificationItems.indexOfLast { it.individualRecipient.isSelf } + 1 notificationItems = notificationItems.slice(indexOfOldestNonSelfMessage..notificationItems.lastIndex).toMutableList() } if (notificationItems.isNotEmpty()) { conversations += NotificationConversation(notificationItems[0].threadRecipient, thread, notificationItems) } } return NotificationStateV2(conversations, muteFilteredMessages, profileFilteredMessages) } private data class NotificationMessage( val messageRecord: MessageRecord, val reactions: List<ReactionRecord>, val threadRecipient: Recipient, val thread: ConversationId, val stickyThread: Boolean, val isUnreadMessage: Boolean, val hasUnreadReactions: Boolean, val lastReactionRead: Long, val isParentStorySentBySelf: Boolean, val hasSelfRepliedToStory: Boolean ) { private val isGroupStoryReply: Boolean = thread.groupStoryId != null private val isUnreadIncoming: Boolean = isUnreadMessage && !messageRecord.isOutgoing && !isGroupStoryReply private val isNotifiableGroupStoryMessage: Boolean = isUnreadMessage && !messageRecord.isOutgoing && isGroupStoryReply && (isParentStorySentBySelf || hasSelfRepliedToStory) fun includeMessage(notificationProfile: NotificationProfile?): MessageInclusion { return if (isUnreadIncoming || stickyThread || isNotifiableGroupStoryMessage) { if (threadRecipient.isMuted && (threadRecipient.isDoNotNotifyMentions || !messageRecord.hasSelfMention())) { MessageInclusion.MUTE_FILTERED } else if (notificationProfile != null && !notificationProfile.isRecipientAllowed(threadRecipient.id) && !(notificationProfile.allowAllMentions && messageRecord.hasSelfMention())) { MessageInclusion.PROFILE_FILTERED } else { MessageInclusion.INCLUDE } } else { MessageInclusion.EXCLUDE } } fun includeReaction(reaction: ReactionRecord, notificationProfile: NotificationProfile?): MessageInclusion { return if (threadRecipient.isMuted) { MessageInclusion.MUTE_FILTERED } else if (notificationProfile != null && !notificationProfile.isRecipientAllowed(threadRecipient.id)) { MessageInclusion.PROFILE_FILTERED } else if (reaction.author != Recipient.self().id && messageRecord.isOutgoing && reaction.dateReceived > lastReactionRead) { MessageInclusion.INCLUDE } else { MessageInclusion.EXCLUDE } } private val Recipient.isDoNotNotifyMentions: Boolean get() = mentionSetting == RecipientDatabase.MentionSetting.DO_NOT_NOTIFY } private enum class MessageInclusion { INCLUDE, EXCLUDE, MUTE_FILTERED, PROFILE_FILTERED } }
app/src/main/java/org/thoughtcrime/securesms/notifications/v2/NotificationStateProvider.kt
1321849173
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.types.ty import org.rust.lang.core.resolve.ImplLookup data class TyTuple(val types: List<Ty>) : Ty { override fun unifyWith(other: Ty, lookup: ImplLookup): UnifyResult { return if (other is TyTuple && types.size == other.types.size) { UnifyResult.mergeAll(types.zip(other.types).map { (type1, type2) -> type1.unifyWith(type2, lookup) }) } else { UnifyResult.fail } } override fun substitute(subst: Substitution): TyTuple = TyTuple(types.map { it.substitute(subst) }) override fun toString(): String = types.joinToString(", ", "(", ")") }
src/main/kotlin/org/rust/lang/core/types/ty/TyTuple.kt
1568969952
/* * Copyright 2022, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.testing import com.google.common.truth.Truth.assertThat import java.io.File import java.lang.AssertionError import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.io.TempDir @DisplayName("`MoreAssertions` (`Assertions.kt`) should") internal class AssertionsKtSpec { companion object { lateinit var dir: File lateinit var file: File val missingFile = File("nowhere-near") @JvmStatic @BeforeAll fun createDirectory(@TempDir tempDir: File) { dir = tempDir file = dir.resolve("test.txt") file.writeText("Foo bar") } } @Nested inner class `assert existence of a 'File'` { @Nested inner class `not throwing when exists` { @Test fun file() = assertDoesNotThrow { assertExists(file) } @Test fun directory() = assertDoesNotThrow { assertExists(dir) } @Test fun `file as 'Path'`() = assertDoesNotThrow { assertExists(file.toPath()) } @Test fun `directory as 'Path'`() = assertDoesNotThrow { assertExists(dir.toPath()) } } @Nested inner class `throwing when does not exist with` { @Test fun `default message`() { val exception = assertThrows<AssertionError> { assertExists(missingFile) } assertThat(exception).hasMessageThat().run { contains(missingFile.name) contains("expected to exist") contains("but it does not") } } @Test fun `custom message`() { val exception = assertThrows<AssertionError> { assertExists(missingFile, "Could not locate `$missingFile`.") } assertThat(exception).hasMessageThat().run { contains(missingFile.name) contains("Could not locate") contains("`.") } } } } }
testlib/src/test/kotlin/io/spine/testing/AssertionsKtSpec.kt
3078061034
package lt.markmerkk.widgets import com.jfoenix.controls.JFXPopup import com.jfoenix.svg.SVGGlyph import javafx.scene.Node import javafx.scene.Parent import javafx.scene.layout.VBox import lt.markmerkk.Styles import lt.markmerkk.ui_2.views.jfxButton import tornadofx.* interface PopUpDisplay { fun show() /** * Generates and shows popup with predefined actions */ fun createPopUpDisplay( actions: List<PopUpAction>, attachTo: Node ) { val viewPopUp = JFXPopup() val viewContainer = object : View() { override val root: Parent = vbox(spacing = 4) { style { padding = box(4.px) } actions.forEach { popUpAction -> jfxButton(popUpAction.title) { addClass(Styles.popUpLabel) graphic = popUpAction.graphic action { popUpAction.action.invoke() viewPopUp.hide() } } } } } viewPopUp.popupContent = viewContainer.root as VBox viewPopUp.show(attachTo, JFXPopup.PopupVPosition.BOTTOM, JFXPopup.PopupHPosition.LEFT) } } class PopUpAction( val title: String, val graphic: SVGGlyph, val action: () -> Unit )
app/src/main/java/lt/markmerkk/widgets/PopUpDisplay.kt
2088262971
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.netty import io.netty.buffer.* import io.netty.channel.* import io.netty.handler.codec.* import io.netty.handler.codec.http.* internal class NettyDirectEncoder : MessageToByteEncoder<HttpContent>() { override fun encode(ctx: ChannelHandlerContext, msg: HttpContent, out: ByteBuf) { out.writeBytes(msg.content()) } override fun allocateBuffer(ctx: ChannelHandlerContext, msg: HttpContent?, preferDirect: Boolean): ByteBuf { val size = msg?.content()?.readableBytes() ?: 0 return if (size == 0) Unpooled.EMPTY_BUFFER else if (preferDirect) ctx.alloc().ioBuffer(size) else ctx.alloc().heapBuffer(size) } }
ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyDirectEncoder.kt
3673030870
/* * Copyright © 2013 dvbviewer-controller 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 org.dvbviewer.controller.ui.fragments import android.app.Dialog import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import org.dvbviewer.controller.R import org.dvbviewer.controller.data.entities.IEPG import org.dvbviewer.controller.ui.base.BaseDialogFragment import org.dvbviewer.controller.utils.DateUtils /** * Fragment for EPG details or Timer details. */ class EPGDetails : BaseDialogFragment() { /** * Gets the epg. * * @return the epg */ var epg: IEPG? = null internal set private var channel: TextView? = null private var date: TextView? = null private var title: TextView? = null private var subTitle: TextView? = null private var desc: TextView? = null /* (non-Javadoc) * @see android.support.v4.app.Fragment#onCreate(android.os.Bundle) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) epg = arguments!!.getParcelable(IEPG::class.java.simpleName) } /* (non-Javadoc) * @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle) */ override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) if (epg != null) { var dateString = DateUtils.getDateInLocalFormat(epg!!.start) if (DateUtils.isToday(epg!!.start.time)) { dateString = resources.getString(R.string.today) } else if (DateUtils.isTomorrow(epg!!.start.time)) { dateString = resources.getString(R.string.tomorrow) } val start = DateUtils.getTimeInLocalFormat(context, epg!!.start) val end = DateUtils.getTimeInLocalFormat(context, epg!!.end) date!!.text = "$dateString $start - $end" channel!!.text = epg!!.channel title!!.text = epg!!.title if (TextUtils.isEmpty(epg!!.subTitle)) { subTitle!!.visibility = View.GONE } else { subTitle!!.text = epg!!.subTitle } desc!!.text = epg!!.description } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.setTitle(R.string.details) return dialog } /* (non-Javadoc) * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) */ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = activity!!.layoutInflater.inflate(R.layout.fragment_epg_details, container, false) channel = v.findViewById<View>(R.id.channel) as TextView date = v.findViewById<View>(R.id.date) as TextView title = v.findViewById<View>(R.id.title) as TextView subTitle = v.findViewById<View>(R.id.subTitle) as TextView desc = v.findViewById<View>(R.id.desc) as TextView return v } }
dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/EPGDetails.kt
1608247130
package com.darrenatherton.droidcommunity.features.subscriptiondrawer import com.darrenatherton.droidcommunity.base.presentation.BasePresenter import com.darrenatherton.droidcommunity.base.presentation.BaseView import com.darrenatherton.droidcommunity.common.injection.scope.PerScreen import javax.inject.Inject @PerScreen class SubscriptionDrawerPresenter @Inject constructor() : BasePresenter<SubscriptionDrawerPresenter.View>() { //=================================================================================== // View attach/detach //=================================================================================== override fun onViewAttached() { loadSubscriptions() } override fun onViewDetached() { } //=================================================================================== // Domain actions to execute //=================================================================================== private fun loadSubscriptions() { // performDomainAction { // // } } interface View : BaseView { } }
app/src/main/kotlin/com/darrenatherton/droidcommunity/features/subscriptiondrawer/SubscriptionDrawerPresenter.kt
795751884
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particleswallpaper.framework.opengl import android.opengl.GLES20 import com.doctoror.particlesdrawable.opengl.GlException import com.doctoror.particlesdrawable.opengl.chooser.NoMatchingConfigsException import com.doctoror.particleswallpaper.framework.util.OpenGlEnabledStateChanger import com.doctoror.particleswallpaper.userprefs.data.DeviceSettings import io.reactivex.exceptions.OnErrorNotImplementedException class KnownOpenglIssuesHandler( private val deviceSettings: DeviceSettings, private val openGlEnabledStateChanger: OpenGlEnabledStateChanger ) { fun handleGlError(tag: String) { val error = GLES20.glGetError() if (error != GLES20.GL_NO_ERROR) { // There are reports of GL_OUT_OF_MEMORY on glUseProgram for unknown reasons. // Since there is not enough data to handle it, disable opengl support. // https://bugs.chromium.org/p/webrtc/issues/detail?id=8154 // https://developer.samsung.com/forum/thread/bug-in-opengl-driver--samsung-opengl-shader-linking-with-out_of_memory-on-sm-g930fd/201/307111 if (error == GLES20.GL_OUT_OF_MEMORY) { deviceSettings.openglSupported = false openGlEnabledStateChanger.setOpenglGlEnabled( openGlEnabled = false, shouldKillApp = true ) } else { throw GlException(error, tag) } } } /** * Handles the uncaught exception. * * @return true if handled and must not be propagated. */ fun handleUncaughtException(throwable: Throwable): Boolean = when (throwable) { /* * On some devices it is impossible to choose any config. Disable OpenGL in this case. */ is NoMatchingConfigsException -> { deviceSettings.openglSupported = false openGlEnabledStateChanger.setOpenglGlEnabled( openGlEnabled = false, shouldKillApp = true ) true } is OnErrorNotImplementedException -> { val cause = throwable.cause if (cause != null) { handleUncaughtException(cause) } else { false } } else -> false } }
app/src/main/java/com/doctoror/particleswallpaper/framework/opengl/KnownOpenglIssuesHandler.kt
1944925845
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengles.templates import org.lwjgl.generator.* import opengles.* val DMP_program_binary = "DMPProgramBinary".nativeClassGLES("DMP_program_binary", postfix = DMP) { documentation = """ Native bindings to the $registryLink extension. This extension enables loading precompiled program binaries compatible with chips designed by Digital Media Professionals Inc. Requires ${GLES20.core} and ${OES_get_program_binary.link}. """ IntConstant( "Accepted by the {@code binaryFormat} parameter of ProgramBinaryOES.", "SMAPHS30_PROGRAM_BINARY_DMP"..0x9251, "SMAPHS_PROGRAM_BINARY_DMP"..0x9252, "DMP_PROGRAM_BINARY_DMP"..0x9253 ) }
modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/DMP_program_binary.kt
2515047288
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.datacapture.views import android.view.View import android.widget.FrameLayout import android.widget.TextView import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.RootMatchers.isDialog import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.google.android.fhir.datacapture.R import com.google.android.fhir.datacapture.TestActivity import com.google.android.fhir.datacapture.utilities.clickIcon import com.google.android.fhir.datacapture.validation.NotValidated import com.google.common.truth.Truth.assertThat import org.hamcrest.CoreMatchers.allOf import org.hl7.fhir.r4.model.Questionnaire import org.hl7.fhir.r4.model.QuestionnaireResponse import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class QuestionnaireItemDateTimePickerViewHolderFactoryEspressoTest { @Rule @JvmField var activityScenarioRule: ActivityScenarioRule<TestActivity> = ActivityScenarioRule(TestActivity::class.java) private lateinit var parent: FrameLayout private lateinit var viewHolder: QuestionnaireItemViewHolder @Before fun setup() { activityScenarioRule.getScenario().onActivity { activity -> parent = FrameLayout(activity) } viewHolder = QuestionnaireItemDateTimePickerViewHolderFactory.create(parent) setTestLayout(viewHolder.itemView) } @Test fun shouldSetFirstDateInputThenTimeInput() { val questionnaireItemView = QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) runOnUI { viewHolder.bind(questionnaireItemView) } assertThat( viewHolder.itemView.findViewById<TextView>(R.id.date_input_edit_text).text.toString() ) .isEmpty() assertThat( viewHolder.itemView.findViewById<TextView>(R.id.time_input_edit_text).text.toString() ) .isEmpty() onView(withId(R.id.date_input_layout)).perform(clickIcon(true)) onView(allOf(withText("OK"))) .inRoot(isDialog()) .check(matches(isDisplayed())) .perform(ViewActions.click()) onView(withId(R.id.time_input_layout)).perform(clickIcon(true)) onView(allOf(withText("OK"))) .inRoot(isDialog()) .check(matches(isDisplayed())) .perform(ViewActions.click()) assertThat( viewHolder.itemView.findViewById<TextView>(R.id.date_input_edit_text).text.toString() ) .isNotEmpty() assertThat( viewHolder.itemView.findViewById<TextView>(R.id.time_input_edit_text).text.toString() ) .isNotEmpty() } @Test fun shouldSetFirstTimeInputThenDateInput() { val questionnaireItemView = QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) runOnUI { viewHolder.bind(questionnaireItemView) } assertThat( viewHolder.itemView.findViewById<TextView>(R.id.date_input_edit_text).text.toString() ) .isEmpty() assertThat( viewHolder.itemView.findViewById<TextView>(R.id.time_input_edit_text).text.toString() ) .isEmpty() onView(withId(R.id.time_input_layout)).perform(clickIcon(true)) onView(allOf(withText("OK"))) .inRoot(isDialog()) .check(matches(isDisplayed())) .perform(ViewActions.click()) onView(withId(R.id.date_input_layout)).perform(clickIcon(true)) onView(allOf(withText("OK"))) .inRoot(isDialog()) .check(matches(isDisplayed())) .perform(ViewActions.click()) assertThat( viewHolder.itemView.findViewById<TextView>(R.id.date_input_edit_text).text.toString() ) .isNotEmpty() assertThat( viewHolder.itemView.findViewById<TextView>(R.id.time_input_edit_text).text.toString() ) .isNotEmpty() } /** Method to run code snippet on UI/main thread */ private fun runOnUI(action: () -> Unit) { activityScenarioRule.getScenario().onActivity { activity -> action() } } /** Method to set content view for test activity */ private fun setTestLayout(view: View) { activityScenarioRule.getScenario().onActivity { activity -> activity.setContentView(view) } InstrumentationRegistry.getInstrumentation().waitForIdleSync() } }
datacapture/src/androidTest/java/com/google/android/fhir/datacapture/views/QuestionnaireItemDateTimePickerViewHolderFactoryEspressoTest.kt
4044398349
package graphics.scenery.backends import graphics.scenery.Settings import org.joml.Matrix4f import graphics.scenery.backends.vulkan.VulkanDevice import org.joml.Vector2i import org.lwjgl.vulkan.VkInstance import org.lwjgl.vulkan.VkPhysicalDevice import org.lwjgl.vulkan.VkQueue /** * <Description> * * @author Ulrik Günther <hello@ulrik.is> */ interface Display { /** * Returns the per-eye projection matrix * * @param[eye] The index of the eye * @return Matrix4f containing the per-eye projection matrix */ fun getEyeProjection(eye: Int, nearPlane: Float = 1.0f, farPlane: Float = 1000.0f): Matrix4f /** * Returns the inter-pupillary distance (IPD) * * @return IPD as Float */ fun getIPD(): Float /** * Query the HMD whether a compositor is used or the renderer should take * care of displaying on the HMD on its own. * * @return True if the HMD has a compositor */ fun hasCompositor(): Boolean /** * Submit OpenGL texture IDs to the compositor. The texture is assumed to have the left eye in the * left half, right eye in the right half. * * @param[textureId] OpenGL Texture ID of the left eye texture */ fun submitToCompositor(textureId: Int) /** * Submit a Vulkan texture handle to the compositor * * @param[width] Texture width * @param[height] Texture height * @param[format] Vulkan texture format * @param[instance] Vulkan Instance * @param[device] Vulkan device * @param[queue] Vulkan queue * @param[queueFamilyIndex] Queue family index * @param[image] The Vulkan texture image to be presented to the compositor */ fun submitToCompositorVulkan(width: Int, height: Int, format: Int, instance: VkInstance, device: VulkanDevice, queue: VkQueue, image: Long) /** * Returns the optimal render target size for the HMD as 2D vector * * @return Render target size as 2D vector */ fun getRenderTargetSize(): Vector2i /** * Check whether the HMD is initialized and working * * @return True if HMD is initialiased correctly and working properly */ fun initializedAndWorking(): Boolean /** * update state */ fun update() /** * Returns a [List] of Vulkan instance extensions required by the device. * * @return [List] of strings containing the required instance extensions */ fun getVulkanInstanceExtensions(): List<String> /** * Returns a [List] of Vulkan device extensions required by the device. * * @return [List] of strings containing the required device extensions */ fun getVulkanDeviceExtensions(physicalDevice: VkPhysicalDevice): List<String> /** * Returns a [Display] instance, if working currently * * @return Either a [Display] instance, or null. */ fun getWorkingDisplay(): Display? /** * Returns the per-eye transform that moves from head to eye * * @param[eye] The eye index * @return Matrix4f containing the transform */ fun getHeadToEyeTransform(eye: Int): Matrix4f fun wantsVR(settings: Settings): Display? { return if (settings.get("vr.Active")) { this } else { null } } }
src/main/kotlin/graphics/scenery/backends/Display.kt
2287285704
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <git@axavier.org> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.core.ui.screens.habits.list import org.isoron.uhabits.core.commands.CommandRunner import org.isoron.uhabits.core.commands.CreateRepetitionCommand import org.isoron.uhabits.core.models.Habit import org.isoron.uhabits.core.models.HabitList import org.isoron.uhabits.core.models.HabitType import org.isoron.uhabits.core.models.PaletteColor import org.isoron.uhabits.core.models.Timestamp import org.isoron.uhabits.core.preferences.Preferences import org.isoron.uhabits.core.tasks.ExportCSVTask import org.isoron.uhabits.core.tasks.TaskRunner import org.isoron.uhabits.core.utils.DateUtils.Companion.getToday import java.io.File import java.io.IOException import java.util.LinkedList import javax.inject.Inject import kotlin.math.roundToInt open class ListHabitsBehavior @Inject constructor( private val habitList: HabitList, private val dirFinder: DirFinder, private val taskRunner: TaskRunner, private val screen: Screen, private val commandRunner: CommandRunner, private val prefs: Preferences, private val bugReporter: BugReporter ) { fun onClickHabit(h: Habit) { screen.showHabitScreen(h) } fun onEdit(habit: Habit, timestamp: Timestamp?) { val entry = habit.computedEntries.get(timestamp!!) if (habit.type == HabitType.NUMERICAL) { val oldValue = entry.value.toDouble() / 1000 screen.showNumberPopup(oldValue, entry.notes) { newValue: Double, newNotes: String -> val value = (newValue * 1000).roundToInt() commandRunner.run(CreateRepetitionCommand(habitList, habit, timestamp, value, newNotes)) } } else { screen.showCheckmarkPopup( entry.value, entry.notes, habit.color, ) { newValue, newNotes -> commandRunner.run(CreateRepetitionCommand(habitList, habit, timestamp, newValue, newNotes)) } } } fun onExportCSV() { val selected: MutableList<Habit> = LinkedList() for (h in habitList) selected.add(h) val outputDir = dirFinder.getCSVOutputDir() taskRunner.execute( ExportCSVTask(habitList, selected, outputDir) { filename: String? -> if (filename != null) screen.showSendFileScreen(filename) else screen.showMessage( Message.COULD_NOT_EXPORT ) } ) } fun onFirstRun() { prefs.isFirstRun = false prefs.updateLastHint(-1, getToday()) screen.showIntroScreen() } fun onReorderHabit(from: Habit, to: Habit) { taskRunner.execute { habitList.reorder(from, to) } } fun onRepairDB() { taskRunner.execute { habitList.repair() screen.showMessage(Message.DATABASE_REPAIRED) } } fun onSendBugReport() { bugReporter.dumpBugReportToFile() try { val log = bugReporter.getBugReport() screen.showSendBugReportToDeveloperScreen(log) } catch (e: IOException) { e.printStackTrace() screen.showMessage(Message.COULD_NOT_GENERATE_BUG_REPORT) } } fun onStartup() { prefs.incrementLaunchCount() if (prefs.isFirstRun) onFirstRun() } fun onToggle(habit: Habit, timestamp: Timestamp, value: Int, notes: String) { commandRunner.run( CreateRepetitionCommand(habitList, habit, timestamp, value, notes) ) } enum class Message { COULD_NOT_EXPORT, IMPORT_SUCCESSFUL, IMPORT_FAILED, DATABASE_REPAIRED, COULD_NOT_GENERATE_BUG_REPORT, FILE_NOT_RECOGNIZED, } interface BugReporter { fun dumpBugReportToFile() @Throws(IOException::class) fun getBugReport(): String } interface DirFinder { fun getCSVOutputDir(): File } fun interface NumberPickerCallback { fun onNumberPicked(newValue: Double, notes: String) fun onNumberPickerDismissed() {} } fun interface CheckMarkDialogCallback { fun onNotesSaved(value: Int, notes: String) fun onNotesDismissed() {} } interface Screen { fun showHabitScreen(h: Habit) fun showIntroScreen() fun showMessage(m: Message) fun showNumberPopup( value: Double, notes: String, callback: NumberPickerCallback ) fun showCheckmarkPopup( selectedValue: Int, notes: String, color: PaletteColor, callback: CheckMarkDialogCallback ) fun showSendBugReportToDeveloperScreen(log: String) fun showSendFileScreen(filename: String) } }
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/ui/screens/habits/list/ListHabitsBehavior.kt
3722392373
package org.wikipedia.language import android.content.Context import android.content.Intent import android.os.Bundle import android.view.* import android.widget.TextView import androidx.appcompat.view.ActionMode import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.schedulers.Schedulers import org.apache.commons.lang3.StringUtils import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.activity.BaseActivity import org.wikipedia.analytics.AppLanguageSearchingFunnel import org.wikipedia.databinding.ActivityLanguagesListBinding import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.mwapi.SiteMatrix import org.wikipedia.history.SearchActionModeCallback import org.wikipedia.settings.languages.WikipediaLanguagesFragment import org.wikipedia.util.DeviceUtil import org.wikipedia.util.log.L import java.util.* class LanguagesListActivity : BaseActivity() { private lateinit var binding: ActivityLanguagesListBinding private lateinit var searchActionModeCallback: LanguageSearchCallback private lateinit var searchingFunnel: AppLanguageSearchingFunnel private var app = WikipediaApp.getInstance() private var currentSearchQuery: String? = null private var actionMode: ActionMode? = null private var interactionsCount = 0 private var isLanguageSearched = false private val disposables = CompositeDisposable() private var siteInfoList: List<SiteMatrix.SiteInfo>? = null public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLanguagesListBinding.inflate(layoutInflater) setContentView(binding.root) binding.languagesListEmptyView.setEmptyText(R.string.langlinks_no_match) binding.languagesListEmptyView.visibility = View.GONE binding.languagesListRecycler.adapter = LanguagesListAdapter(app.language().appMruLanguageCodes, app.language().remainingAvailableLanguageCodes) binding.languagesListRecycler.layoutManager = LinearLayoutManager(this) binding.languagesListLoadProgress.visibility = View.VISIBLE searchActionModeCallback = LanguageSearchCallback() searchingFunnel = AppLanguageSearchingFunnel(intent.getStringExtra(WikipediaLanguagesFragment.SESSION_TOKEN).orEmpty()) requestLanguages() } public override fun onDestroy() { disposables.clear() super.onDestroy() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_languages_list, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_search_language -> { if (actionMode == null) { actionMode = startSupportActionMode(searchActionModeCallback) } true } else -> super.onOptionsItemSelected(item) } } override fun onBackPressed() { DeviceUtil.hideSoftKeyboard(this) val returnIntent = Intent() returnIntent.putExtra(LANGUAGE_SEARCHED, isLanguageSearched) setResult(RESULT_OK, returnIntent) searchingFunnel.logNoLanguageAdded(false, currentSearchQuery) super.onBackPressed() } private inner class LanguageSearchCallback : SearchActionModeCallback() { private val languageAdapter = binding.languagesListRecycler.adapter as LanguagesListAdapter override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { // currentSearchQuery is cleared here, instead of onDestroyActionMode // in order to make the most recent search string available to analytics currentSearchQuery = "" isLanguageSearched = true actionMode = mode return super.onCreateActionMode(mode, menu) } override fun onQueryChange(s: String) { currentSearchQuery = s.trim() languageAdapter.setFilterText(currentSearchQuery) if (binding.languagesListRecycler.adapter?.itemCount == 0) { binding.languagesListEmptyView.visibility = View.VISIBLE } else { binding.languagesListEmptyView.visibility = View.GONE } } override fun onDestroyActionMode(mode: ActionMode) { super.onDestroyActionMode(mode) binding.languagesListEmptyView.visibility = View.GONE languageAdapter.reset() actionMode = null } override fun getSearchHintString(): String { return resources.getString(R.string.search_hint_search_languages) } override fun getParentContext(): Context { return this@LanguagesListActivity } } private inner class LanguagesListAdapter(languageCodes: List<String>, private val suggestedLanguageCodes: List<String>) : RecyclerView.Adapter<DefaultViewHolder>() { private val originalLanguageCodes = languageCodes.toMutableList() private val languageCodes = mutableListOf<String>() private var isSearching = false // To remove the already selected languages and suggested languages from all languages list private val nonDuplicateLanguageCodesList get() = originalLanguageCodes.toMutableList().apply { removeAll(app.language().appLanguageCodes) removeAll(suggestedLanguageCodes) } init { reset() } override fun getItemViewType(position: Int): Int { return if (shouldShowSectionHeader(position)) Companion.VIEW_TYPE_HEADER else Companion.VIEW_TYPE_ITEM } override fun getItemCount(): Int { return languageCodes.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DefaultViewHolder { val inflater = LayoutInflater.from(parent.context) return if (viewType == Companion.VIEW_TYPE_HEADER) { val view = inflater.inflate(R.layout.view_section_header, parent, false) DefaultViewHolder(languageCodes, view) } else { val view = inflater.inflate(R.layout.item_language_list_entry, parent, false) LanguagesListItemHolder(languageCodes, view) } } override fun onBindViewHolder(holder: DefaultViewHolder, pos: Int) { holder.bindItem(pos) (holder as? LanguagesListItemHolder)?.itemView?.setOnClickListener { val lang = languageCodes[pos] if (lang != app.appOrSystemLanguageCode) { app.language().addAppLanguageCode(lang) } interactionsCount++ searchingFunnel.logLanguageAdded(true, lang, currentSearchQuery) DeviceUtil.hideSoftKeyboard(this@LanguagesListActivity) val returnIntent = Intent() returnIntent.putExtra(WikipediaLanguagesFragment.ADD_LANGUAGE_INTERACTIONS, interactionsCount) returnIntent.putExtra(LANGUAGE_SEARCHED, isLanguageSearched) setResult(RESULT_OK, returnIntent) finish() } } fun shouldShowSectionHeader(position: Int): Boolean { return !isSearching && (position == 0 || (suggestedLanguageCodes.isNotEmpty() && position == suggestedLanguageCodes.size + 1)) } fun setFilterText(filterText: String?) { isSearching = true languageCodes.clear() val filter = StringUtils.stripAccents(filterText).toLowerCase(Locale.getDefault()) for (code in originalLanguageCodes) { val localizedName = StringUtils.stripAccents(app.language().getAppLanguageLocalizedName(code).orEmpty()) val canonicalName = StringUtils.stripAccents(getCanonicalName(code).orEmpty()) if (code.contains(filter) || localizedName.toLowerCase(Locale.getDefault()).contains(filter) || canonicalName.toLowerCase(Locale.getDefault()).contains(filter)) { languageCodes.add(code) } } notifyDataSetChanged() } fun reset() { isSearching = false languageCodes.clear() if (suggestedLanguageCodes.isNotEmpty()) { languageCodes.add(getString(R.string.languages_list_suggested_text)) languageCodes.addAll(suggestedLanguageCodes) } languageCodes.add(getString(R.string.languages_list_all_text)) languageCodes.addAll(nonDuplicateLanguageCodesList) // should not be able to be searched while the languages are selected originalLanguageCodes.removeAll(app.language().appLanguageCodes) notifyDataSetChanged() } } private fun getCanonicalName(code: String): String? { var canonicalName = siteInfoList?.find { it.code() == code }?.localName() if (canonicalName.isNullOrEmpty()) { canonicalName = app.language().getAppLanguageCanonicalName(code) } return canonicalName } // TODO: optimize and reuse the header view holder? private open inner class DefaultViewHolder constructor(private val languageCodes: List<String>, itemView: View) : RecyclerView.ViewHolder(itemView) { open fun bindItem(position: Int) { itemView.findViewById<TextView>(R.id.section_header_text).text = languageCodes[position] } } private inner class LanguagesListItemHolder constructor(private val languageCodes: List<String>, itemView: View) : DefaultViewHolder(languageCodes, itemView) { private val localizedNameTextView = itemView.findViewById<TextView>(R.id.localized_language_name) private val canonicalNameTextView = itemView.findViewById<TextView>(R.id.language_subtitle) override fun bindItem(position: Int) { val languageCode = languageCodes[position] localizedNameTextView.text = app.language().getAppLanguageLocalizedName(languageCode).orEmpty().capitalize(Locale.getDefault()) val canonicalName = getCanonicalName(languageCode) if (binding.languagesListLoadProgress.visibility != View.VISIBLE) { canonicalNameTextView.text = if (canonicalName.isNullOrEmpty()) app.language().getAppLanguageCanonicalName(languageCode) else canonicalName } } } private fun requestLanguages() { disposables.add(ServiceFactory.get(app.wikiSite).siteMatrix .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map { siteMatrix -> SiteMatrix.getSites(siteMatrix) } .doAfterTerminate { binding.languagesListLoadProgress.visibility = View.INVISIBLE binding.languagesListRecycler.adapter?.notifyDataSetChanged() } .subscribe({ sites -> siteInfoList = sites }) { t -> L.e(t) }) } companion object { private const val VIEW_TYPE_HEADER = 0 private const val VIEW_TYPE_ITEM = 1 const val LANGUAGE_SEARCHED = "language_searched" } }
app/src/main/java/org/wikipedia/language/LanguagesListActivity.kt
3840185357
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.codeinsight import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase class EditorConfigFoldingBuilderTest : LightPlatformCodeInsightFixtureTestCase() { override fun getTestDataPath() = "${PathManagerEx.getCommunityHomePath()}/plugins/editorconfig/testSrc/org/editorconfig/language/codeinsight/folding/" fun testSection() = doTest() fun testSimpleComment() = doTest() fun testBlankLineBetweenComments() = doTest() fun testCommentInsideSection() = doTest() fun testCommentBetweenHeaderAndOption() = doTest() fun testMultipleSections() = doTest() fun testTrailingComment() = doTest() fun testLongComment() = doTest() private fun doTest() = myFixture.testFolding("${testDataPath}${getTestName(true)}/.editorconfig") }
plugins/editorconfig/test/org/editorconfig/language/codeinsight/EditorConfigFoldingBuilderTest.kt
439125730
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.debugger.actions import com.intellij.debugger.impl.DebuggerUtilsEx import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.util.Key import com.intellij.openapi.util.registry.Registry import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.impl.XDebugSessionImpl import com.intellij.xdebugger.impl.ui.DebuggerUIUtil /** * @author egor */ class AsyncStacksToggleAction : ToggleAction() { override fun isSelected(e: AnActionEvent): Boolean { return ASYNC_STACKS_ENABLED.get(DebuggerUIUtil.getSessionData(e), true) } override fun setSelected(e: AnActionEvent, state: Boolean) { ASYNC_STACKS_ENABLED.set(DebuggerUIUtil.getSessionData(e), state) DebuggerAction.refreshViews(e.getData(XDebugSession.DATA_KEY)) } override fun update(e: AnActionEvent) { super.update(e) e.presentation.isEnabledAndVisible = DebuggerUtilsEx.isInJavaSession(e) } companion object { private val ASYNC_STACKS_ENABLED = Key.create<Boolean>("ASYNC_STACKS_ENABLED") @JvmStatic fun isAsyncStacksEnabled(session: XDebugSessionImpl): Boolean { return ASYNC_STACKS_ENABLED.get(session.sessionData, true) } } }
java/debugger/impl/src/com/intellij/debugger/actions/AsyncStacksToggleAction.kt
471235169
KtClass: A KtClass: I1 KtClass: I2
plugins/kotlin/fir/testData/codeInsight/handlers/gotoSuperActionHandler/classes/classImplemeningInterfaces.result.kt
2138550259
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <jonathan.scripter@programmer.net> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.jonathanxd.kores.base.comment import com.github.jonathanxd.kores.KoresPart /** * Hold comments and documentation. */ interface CommentHolder : KoresPart { /** * All comments of this element. */ val comments: Comments interface Builder<out T : CommentHolder, S : Builder<T, S>> : com.github.jonathanxd.kores.builder.Builder<T, S> { /** * See [CommentHolder.comments] */ fun comments(value: Comments): S } }
src/main/kotlin/com/github/jonathanxd/kores/base/comment/CommentHolder.kt
4245337335
// WITH_STDLIB fun test(list: List<Int>) { val contains: Boolean = list.<caret>filter { it > 1 }.contains(1) }
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination/contains.kt
469275958
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isFalseConstant import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isTrueConstant import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression class SimplifyWhenWithBooleanConstantConditionInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return whenExpressionVisitor(fun(expression) { if (expression.closeBrace == null) return if (expression.subjectExpression != null) return if (expression.entries.none { it.isTrueConstantCondition() || it.isFalseConstantCondition() }) return holder.registerProblem( expression.whenKeyword, KotlinBundle.message("this.when.is.simplifiable"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, SimplifyWhenFix() ) }) } } private class SimplifyWhenFix : LocalQuickFix { override fun getName() = KotlinBundle.message("simplify.when.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement.getStrictParentOfType<KtWhenExpression>() ?: return val closeBrace = element.closeBrace ?: return val factory = KtPsiFactory(project) val usedAsExpression = element.isUsedAsExpression(element.analyze()) element.deleteFalseEntries(usedAsExpression) element.replaceTrueEntry(usedAsExpression, closeBrace, factory) } } private fun KtWhenExpression.deleteFalseEntries(usedAsExpression: Boolean) { for (entry in entries) { if (entry.isFalseConstantCondition()) { entry.delete() } } val entries = entries if (entries.isEmpty() && !usedAsExpression) { delete() } else if (entries.singleOrNull()?.isElse == true) { elseExpression?.let { replaceWithBranch(it, usedAsExpression) } } } private fun KtWhenExpression.replaceTrueEntry(usedAsExpression: Boolean, closeBrace: PsiElement, factory: KtPsiFactory) { val entries = entries val trueIndex = entries.indexOfFirst { it.isTrueConstantCondition() } if (trueIndex == -1) return val expression = entries[trueIndex].expression ?: return if (trueIndex == 0) { replaceWithBranch(expression, usedAsExpression) } else { val elseEntry = factory.createWhenEntry("else -> ${expression.text}") for (entry in entries.subList(trueIndex, entries.size)) { entry.delete() } addBefore(elseEntry, closeBrace) } } private fun KtWhenEntry.isTrueConstantCondition(): Boolean = (conditions.singleOrNull() as? KtWhenConditionWithExpression)?.expression.isTrueConstant() private fun KtWhenEntry.isFalseConstantCondition(): Boolean = (conditions.singleOrNull() as? KtWhenConditionWithExpression)?.expression.isFalseConstant()
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SimplifyWhenWithBooleanConstantConditionInspection.kt
2793447548
package com.jcs.suadeome.main import com.google.gson.Gson import com.google.gson.GsonBuilder import com.jcs.suadeome.context.RouteFactory import com.jcs.suadeome.professionals.Professional import com.jcs.suadeome.professionals.ProfessionalJsonSerializer import com.jcs.suadeome.professionals.ProfessionalResource import com.jcs.suadeome.services.Service import com.jcs.suadeome.services.ServiceResource import com.jcs.suadeome.types.EntityConstructionFailed import org.flywaydb.core.Flyway import org.postgresql.ds.PGPoolingDataSource import org.skife.jdbi.v2.DBI import spark.Filter import spark.ResponseTransformer import spark.Route import spark.Spark import spark.Spark.* import java.lang.Integer.parseInt import java.util.Optional.ofNullable import java.util.logging.Logger object App { private val logger: Logger = Logger.getLogger(this.javaClass.name) val toJson : ResponseTransformer = ResponseTransformer { model: Any -> createGson().toJson(model) } private fun createGson(): Gson { val builder = GsonBuilder() builder.registerTypeAdapter(Professional::class.java, ProfessionalJsonSerializer()) builder.registerTypeAdapter(Service::class.java, Service.ServiceJsonSerializer()) return builder.create() } @JvmStatic fun main(args: Array<String>) { upgradeDB() configureSpark() val dbi = configureDB() defineRoutes(dbi) } private fun upgradeDB() { val flyway = Flyway() flyway.setDataSource(DbConfig.url(), DbConfig.username(), DbConfig.password()) flyway.migrate() } private fun configureSpark() { val ipAddress = getEnv("OPENSHIFT_DIY_IP", "localhost") val port = getIntEnv("OPENSHIFT_DIY_PORT", 4567) Spark.ipAddress(ipAddress) Spark.port(port) Spark.threadPool(14); } private fun defineRoutes(dbi: DBI) { val routeFactory = RouteFactory(dbi) enableCors() get("/", Route { request, response -> //TODO: list of endpoints, needs to learn how to fetch from Spark listOf("professionals", "services") }, toJson) ProfessionalResource.routesForProfessionals(routeFactory) ServiceResource.routesForResource(routeFactory) exception(EntityConstructionFailed::class.java, { exception, request, response -> response.status(400) response.body(exception.message) }) exception(Exception::class.java, { exception, request, response -> response.status(500) response.body("Something bad happened! Sorry") exception.printStackTrace() logger.severe { exception.message } }) } private fun enableCors() { options("/*", { request, response -> val accessControlRequestHeaders = request.headers("Access-Control-Request-Headers") if (accessControlRequestHeaders != null) { response.header("Access-Control-Allow-Headers", accessControlRequestHeaders); } val accessControlRequestMethod = request.headers("Access-Control-Request-Method"); if (accessControlRequestMethod != null) { response.header("Access-Control-Allow-Methods", accessControlRequestMethod); } response; }) before(Filter { request, response -> response.header("Access-Control-Allow-Origin", "*"); response.header("Access-Control-Request-Method", "POST"); response.header("Access-Control-Request-Method", "GET"); response.header("Access-Control-Request-Method", "OPTIONS"); response.type("application/json"); }) } private fun configureDB(): DBI { val connectionPool = PGPoolingDataSource() connectionPool.applicationName = "suadeome" connectionPool.url = DbConfig.url() connectionPool.user = DbConfig.username() connectionPool.password = DbConfig.password() connectionPool.maxConnections = 10 return DBI(connectionPool) } private fun getIntEnv(property: String, defaultValue: Int): Int { return parseInt(ofNullable(System.getenv(property)).orElse(Integer.toString(defaultValue))) } private fun getEnv(property: String, defaultValue: String): String { return ofNullable(System.getenv(property)).orElse(defaultValue) } object DbConfig { fun url(): String { val host = getEnv("OPENSHIFT_POSTGRESQL_DB_HOST", "localhost") val port = getEnv("OPENSHIFT_POSTGRESQL_DB_PORT", "5432") return "jdbc:postgresql://$host:$port/suadeome" } fun username(): String = getEnv("OPENSHIFT_POSTGRESQL_DB_APP_USER", "suadeome") fun password(): String = getEnv("OPENSHIFT_POSTGRESQL_DB_APP_PASSWORD", "suadeome") } }
src/main/kotlin/com/jcs/suadeome/main/App.kt
1708054105
package co.smartreceipts.android.workers import android.content.Context import android.graphics.* import android.graphics.Bitmap.CompressFormat import android.graphics.Paint.Align import co.smartreceipts.analytics.log.Logger import co.smartreceipts.android.R import co.smartreceipts.android.date.DateFormatter import co.smartreceipts.android.filters.LegacyReceiptFilter import co.smartreceipts.android.model.* import co.smartreceipts.android.model.comparators.ReceiptDateComparator import co.smartreceipts.android.model.converters.DistanceToReceiptsConverter import co.smartreceipts.android.model.factory.PriceBuilderFactory import co.smartreceipts.android.model.impl.columns.categories.CategoryColumnDefinitions import co.smartreceipts.android.model.impl.columns.distance.DistanceColumnDefinitions import co.smartreceipts.android.persistence.DatabaseHelper import co.smartreceipts.android.persistence.database.controllers.grouping.GroupingController import co.smartreceipts.android.purchases.wallet.PurchaseWallet import co.smartreceipts.android.settings.UserPreferenceManager import co.smartreceipts.android.settings.catalog.UserPreference import co.smartreceipts.android.workers.EmailAssistant.EmailOptions import co.smartreceipts.android.workers.reports.Report import co.smartreceipts.android.workers.reports.ReportGenerationException import co.smartreceipts.android.workers.reports.ReportResourcesManager import co.smartreceipts.android.workers.reports.csv.CsvReportWriter import co.smartreceipts.android.workers.reports.csv.CsvTableGenerator import co.smartreceipts.android.workers.reports.pdf.PdfBoxFullPdfReport import co.smartreceipts.android.workers.reports.pdf.PdfBoxImagesOnlyReport import co.smartreceipts.android.workers.reports.pdf.misc.TooManyColumnsException import co.smartreceipts.core.di.scopes.ApplicationScope import wb.android.storage.StorageManager import java.io.File import java.io.IOException import java.util.* import javax.inject.Inject @ApplicationScope class AttachmentFilesWriter @Inject constructor( private val context: Context, private val databaseHelper: DatabaseHelper, private val preferenceManager: UserPreferenceManager, private val storageManager: StorageManager, private val reportResourcesManager: ReportResourcesManager, private val purchaseWallet: PurchaseWallet, private val dateFormatter: DateFormatter ) { companion object { private const val IMG_SCALE_FACTOR = 2.1f private const val HW_RATIO = 0.75f } class WriterResults { var didPDFFailCompletely = false var didPDFFailTooManyColumns = false var didCSVFailCompletely = false var didZIPFailCompletely = false var didMemoryErrorOccure = false val files: Array<File?> = arrayOfNulls(EmailOptions.values().size) } fun write(trip: Trip, receiptsList: List<Receipt>, distancesList: List<Distance>, options: EnumSet<EmailOptions>): WriterResults { Logger.info(this, "Generating the following report types {}.", options) val results = WriterResults() // Make our trip output directory exists in a good state var dir = trip.directory if (!dir.exists()) { dir = storageManager.getFile(trip.name) if (!dir.exists()) { dir = storageManager.mkdir(trip.name) } } if (options.contains(EmailOptions.PDF_FULL)) { generateFullPdf(trip, results) } if (options.contains(EmailOptions.PDF_IMAGES_ONLY) && receiptsList.isNotEmpty()) { generateImagesPdf(trip, results) } if (options.contains(EmailOptions.ZIP) && receiptsList.isNotEmpty()) { generateZip(trip, receiptsList, dir, results) } val csvColumns by lazy { databaseHelper.csvTable.get().blockingGet() } if (options.contains(EmailOptions.CSV)) { generateCsv(trip, receiptsList, distancesList, csvColumns, dir, results) } if (options.contains(EmailOptions.ZIP_WITH_METADATA) && receiptsList.isNotEmpty()) { generateZipWithMetadata(trip, receiptsList, csvColumns, dir, options.contains(EmailOptions.ZIP), results) } return results } private fun generateFullPdf(trip: Trip, results: WriterResults) { val pdfFullReport: Report = PdfBoxFullPdfReport(reportResourcesManager, databaseHelper, preferenceManager, storageManager, purchaseWallet, dateFormatter) try { results.files[EmailOptions.PDF_FULL.index] = pdfFullReport.generate(trip) } catch (e: ReportGenerationException) { if (e.cause is TooManyColumnsException) { results.didPDFFailTooManyColumns = true } results.didPDFFailCompletely = true } } private fun generateImagesPdf(trip: Trip, results: WriterResults) { val pdfImagesReport: Report = PdfBoxImagesOnlyReport(reportResourcesManager, databaseHelper, preferenceManager, storageManager, dateFormatter) try { results.files[EmailOptions.PDF_IMAGES_ONLY.index] = pdfImagesReport.generate(trip) } catch (e: ReportGenerationException) { results.didPDFFailCompletely = true } } private fun generateCsv( trip: Trip, receiptsList: List<Receipt>, distancesList: List<Distance>, csvColumns: List<Column<Receipt>>, dir: File, results: WriterResults ) { val printFooters: Boolean = preferenceManager.get(UserPreference.ReportOutput.ShowTotalOnCSV) try { storageManager.delete(dir, dir.name + ".csv") val csvTableGenerator = CsvTableGenerator(reportResourcesManager, csvColumns, true, printFooters, LegacyReceiptFilter(preferenceManager)) val receipts: MutableList<Receipt> = ArrayList(receiptsList) val distances: MutableList<Distance> = ArrayList(distancesList) // Receipts table if (preferenceManager.get(UserPreference.Distance.PrintDistanceAsDailyReceiptInReports)) { receipts.addAll(DistanceToReceiptsConverter(context, dateFormatter).convert(distances)) Collections.sort(receipts, ReceiptDateComparator()) } var data = csvTableGenerator.generate(receipts) // Distance table if (preferenceManager.get(UserPreference.Distance.PrintDistanceTableInReports)) { if (distances.isNotEmpty()) { distances.reverse() // Reverse the list, so we print the most recent one first // CSVs cannot print special characters val distanceColumnDefinitions: ColumnDefinitions<Distance> = DistanceColumnDefinitions(reportResourcesManager, preferenceManager, dateFormatter, true) val distanceColumns = distanceColumnDefinitions.allColumns data += "\n\n" data += CsvTableGenerator( reportResourcesManager, distanceColumns, true, printFooters ).generate(distances) } } // Categorical summation table if (preferenceManager.get(UserPreference.PlusSubscription.CategoricalSummationInReports)) { val sumCategoryGroupingResults = GroupingController(databaseHelper, context, preferenceManager) .getSummationByCategory(trip) .toList() .blockingGet() var isMultiCurrency = false for (sumCategoryGroupingResult in sumCategoryGroupingResults) { if (sumCategoryGroupingResult.isMultiCurrency) { isMultiCurrency = true break } } val taxEnabled: Boolean = preferenceManager.get(UserPreference.Receipts.IncludeTaxField) val categoryColumns = CategoryColumnDefinitions(reportResourcesManager, isMultiCurrency, taxEnabled) .allColumns data += "\n\n" data += CsvTableGenerator( reportResourcesManager, categoryColumns, true, printFooters ).generate(sumCategoryGroupingResults) } // Separated tables for each category if (preferenceManager.get(UserPreference.PlusSubscription.SeparateByCategoryInReports)) { val groupingResults = GroupingController(databaseHelper, context, preferenceManager) .getReceiptsGroupedByCategory(trip) .toList() .blockingGet() for (groupingResult in groupingResults) { data += "\n\n" + groupingResult.category.name + "\n"; data += CsvTableGenerator(reportResourcesManager, csvColumns, true, printFooters).generate(groupingResult.receipts) } } val csvFile = File(dir, dir.name + ".csv") results.files[EmailOptions.CSV.index] = csvFile CsvReportWriter(csvFile).write(data) } catch (e: IOException) { Logger.error(this, "Failed to write the csv file", e) results.didCSVFailCompletely = true; } } private fun generateZip(trip: Trip, receiptsList: List<Receipt>, directory: File, results: WriterResults) { var dir = directory storageManager.delete(dir, dir.name + ".zip") dir = storageManager.mkdir(trip.directory, trip.name) for (i in receiptsList.indices) { val receipt = receiptsList[i] if (!filterOutReceipt(preferenceManager, receipt) && receipt.file != null && receipt.file.exists()) { val data = storageManager.read(receipt.file) if (data != null) storageManager.write(dir, receipt.file.name, data) } } val zip: File = storageManager.zipBuffered(dir, 2048) storageManager.deleteRecursively(dir) results.files[EmailOptions.ZIP.index] = zip } private fun generateZipWithMetadata( trip: Trip, receiptsList: List<Receipt>, csvColumns: List<Column<Receipt>>, dir: File, isZipGenerationIncluded: Boolean, results: WriterResults ) { val zipDir = if (isZipGenerationIncluded) { storageManager.delete(dir, dir.name + "_stamped" + ".zip") storageManager.mkdir(trip.directory, trip.name + "_stamped") } else { storageManager.delete(dir, dir.name + ".zip") storageManager.mkdir(trip.directory, trip.name) } for (i in receiptsList.indices) { val receipt = receiptsList[i] if (!filterOutReceipt(preferenceManager, receipt)) { if (receipt.hasImage()) { val userCommentBuilder = StringBuilder() for (col in csvColumns) { userCommentBuilder.append(reportResourcesManager.getFlexString(col.headerStringResId)) userCommentBuilder.append(": ") userCommentBuilder.append(col.getValue(receipt)) userCommentBuilder.append("\n") } val userComment = userCommentBuilder.toString() try { val b: Bitmap? = stampImage(trip, receipt, Bitmap.Config.ARGB_8888) if (b != null) { storageManager.writeBitmap(zipDir, b, receipt.file!!.name, CompressFormat.JPEG, 85, userComment) b.recycle() } } catch (e: OutOfMemoryError) { Logger.error(this, "Trying to recover from OOM", e) System.gc() try { val b: Bitmap? = stampImage(trip, receipt, Bitmap.Config.RGB_565) if (b != null) { storageManager.writeBitmap(zipDir, b, receipt.file!!.name, CompressFormat.JPEG, 85, userComment) b.recycle() } } catch (e2: OutOfMemoryError) { Logger.error(this, "Failed to recover from OOM", e2) results.didZIPFailCompletely = true results.didMemoryErrorOccure = true break } } } else if (receipt.hasPDF()) { val data = storageManager.read(receipt.file) if (data != null) storageManager.write(zipDir, receipt.file!!.name, data) } } } val zipWithMetadata: File = storageManager.zipBuffered(zipDir, 2048) storageManager.deleteRecursively(zipDir) results.files[EmailOptions.ZIP_WITH_METADATA.index] = zipWithMetadata } /** * Applies a particular filter to determine whether or not this receipt should be * generated for this report * * @param preferences - User preferences * @param receipt - The particular receipt * @return true if if should be filtered out, false otherwise */ private fun filterOutReceipt(preferences: UserPreferenceManager, receipt: Receipt): Boolean { return if (preferences.get(UserPreference.Receipts.OnlyIncludeReimbursable) && !receipt.isReimbursable) { true } else receipt.price.priceAsFloat < preferences.get(UserPreference.Receipts.MinimumReceiptPrice) } private fun stampImage(trip: Trip, receipt: Receipt, config: Bitmap.Config): Bitmap? { if (!receipt.hasImage()) { return null } var foreground: Bitmap? = storageManager.getMutableMemoryEfficientBitmap(receipt.file) return if (foreground != null) { // It can be null if file not found // Size the image var foreWidth = foreground.width var foreHeight = foreground.height if (foreHeight > foreWidth) { foreWidth = (foreHeight * HW_RATIO).toInt() } else { foreHeight = (foreWidth / HW_RATIO).toInt() } // Set up the padding val xPad = (foreWidth / IMG_SCALE_FACTOR).toInt() val yPad = (foreHeight / IMG_SCALE_FACTOR).toInt() // Set up an all white background for our canvas val background = Bitmap.createBitmap(foreWidth + xPad, foreHeight + yPad, config) val canvas = Canvas(background) canvas.drawARGB(0xFF, 0xFF, 0xFF, 0xFF) //This represents White color // Set up the paint val dither = Paint() dither.isDither = true dither.isFilterBitmap = false canvas.drawBitmap( foreground, (background.width - foreground.width) / 2.toFloat(), (background.height - foreground.height) / 2.toFloat(), dither ) val brush = Paint() brush.isAntiAlias = true brush.typeface = Typeface.SANS_SERIF brush.color = Color.BLACK brush.style = Paint.Style.FILL brush.textAlign = Align.LEFT // Set up the number of items to draw var num = 5 if (preferenceManager.get(UserPreference.Receipts.IncludeTaxField)) { num++ } if (receipt.hasExtraEditText1()) { num++ } if (receipt.hasExtraEditText2()) { num++ } if (receipt.hasExtraEditText3()) { num++ } val spacing: Float = getOptimalSpacing(num, yPad / 2, brush) var y = spacing * 4 canvas.drawText(trip.name, xPad / 2.toFloat(), y, brush) y += spacing canvas.drawText( dateFormatter.getFormattedDate(trip.startDisplayableDate) + " -- " + dateFormatter.getFormattedDate(trip.endDisplayableDate), xPad / 2.toFloat(), y, brush ) y = background.height - yPad / 2 + spacing * 2 canvas.drawText( reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_NAME) + ": " + receipt.name, xPad / 2.toFloat(), y, brush ) y += spacing canvas.drawText( reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_PRICE) + ": " + receipt.price.decimalFormattedPrice + " " + receipt.price.currencyCode, xPad / 2.toFloat(), y, brush ) y += spacing if (preferenceManager.get(UserPreference.Receipts.IncludeTaxField)) { val totalTax = PriceBuilderFactory(receipt.tax).setPrice(receipt.tax.price.add(receipt.tax2.price)).build() canvas.drawText( reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_TAX) + ": " + totalTax.decimalFormattedPrice + " " + receipt.price.currencyCode, xPad / 2.toFloat(), y, brush ) y += spacing } canvas.drawText( reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_DATE) + ": " + dateFormatter.getFormattedDate( receipt.date, receipt.timeZone ), xPad / 2.toFloat(), y, brush ) y += spacing canvas.drawText( reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_CATEGORY) + ": " + receipt.category.name, xPad / 2.toFloat(), y, brush ) y += spacing canvas.drawText( reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_COMMENT) + ": " + receipt.comment, xPad / 2.toFloat(), y, brush ) y += spacing if (receipt.hasExtraEditText1()) { canvas.drawText( reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_EXTRA_EDITTEXT_1) + ": " + receipt.extraEditText1, xPad / 2.toFloat(), y, brush ) y += spacing } if (receipt.hasExtraEditText2()) { canvas.drawText( reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_EXTRA_EDITTEXT_2) + ": " + receipt.extraEditText2, xPad / 2.toFloat(), y, brush ) y += spacing } if (receipt.hasExtraEditText3()) { canvas.drawText( reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_EXTRA_EDITTEXT_3) + ": " + receipt.extraEditText3, xPad / 2.toFloat(), y, brush ) } // Clear out the dead data here foreground.recycle() // And return background } else { null } } private fun getOptimalSpacing(count: Int, space: Int, brush: Paint): Float { var fontSize = 8f //Seed brush.textSize = fontSize while (space > (count + 2) * brush.fontSpacing) { brush.textSize = ++fontSize } brush.textSize = --fontSize return brush.fontSpacing } }
app/src/main/java/co/smartreceipts/android/workers/AttachmentFilesWriter.kt
1117219340
package com.elpassion.mainframerplugin.util import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.wm.WindowManager import com.intellij.ui.awt.RelativePoint import javax.swing.SwingUtilities import javax.swing.event.HyperlinkEvent fun showInfo(project: Project, message: String, hyperlinkListener: ((HyperlinkEvent) -> Unit)? = null) { showBalloon(project, message, MessageType.INFO, hyperlinkListener) } fun showError(project: Project, message: String, hyperlinkListener: ((HyperlinkEvent) -> Unit)? = null) { showBalloon(project, message, MessageType.ERROR, hyperlinkListener) } private fun showBalloon(project: Project, message: String, messageType: MessageType, hyperlinkListener: ((HyperlinkEvent) -> Unit)?) = invokeOnUi { val statusBar = WindowManager.getInstance().getStatusBar(project) JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(message, messageType, hyperlinkListener) .setFadeoutTime(5000) .createBalloon() .show(RelativePoint.getCenterOf(statusBar.component), Balloon.Position.above) } private fun invokeOnUi(action: () -> Unit) = if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeAndWait(action) } else { action() }
src/main/kotlin/com/elpassion/mainframerplugin/util/ui.kt
2696990022
package com.airbnb.epoxy.kotlinsample.models import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.GroupModel import com.airbnb.epoxy.kotlinsample.R @EpoxyModelClass abstract class DecoratedLinearGroupModel : GroupModel(R.layout.decorated_linear_group)
kotlinsample/src/main/java/com/airbnb/epoxy/kotlinsample/models/DecoratedLinearGroupModel.kt
3066927326
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util.reference import com.demonwav.mcdev.util.manipulator import com.demonwav.mcdev.util.packageName import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.util.TextRange import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementResolveResult import com.intellij.psi.PsiPackage import com.intellij.psi.PsiQualifiedNamedElement import com.intellij.psi.PsiReference import com.intellij.psi.PsiReferenceBase import com.intellij.psi.PsiReferenceProvider import com.intellij.psi.ResolveResult import com.intellij.util.IncorrectOperationException import com.intellij.util.PlatformIcons import com.intellij.util.ProcessingContext abstract class PackageNameReferenceProvider : PsiReferenceProvider() { protected open val description get() = "package '%s'" protected open fun getBasePackage(element: PsiElement): String? = null protected open fun canBindTo(element: PsiElement) = element is PsiPackage protected open fun resolve( qualifiedName: String, element: PsiElement, facade: JavaPsiFacade ): Array<ResolveResult> { facade.findPackage(qualifiedName)?.let { return arrayOf(PsiElementResolveResult(it)) } return ResolveResult.EMPTY_ARRAY } protected abstract fun collectVariants(element: PsiElement, context: PsiElement?): Array<Any> protected fun collectSubpackages(context: PsiPackage, classes: Iterable<PsiClass>): Array<Any> { return collectPackageChildren(context, classes) {} } protected inline fun collectPackageChildren( context: PsiPackage, classes: Iterable<PsiClass>, classFunc: (PsiClass) -> Any? ): Array<Any> { val parentPackage = context.qualifiedName val subPackageStart = parentPackage.length + 1 val packages = HashSet<String>() val list = ArrayList<Any>() for (psiClass in classes) { val packageName = psiClass.packageName ?: continue if (!packageName.startsWith(parentPackage)) { continue } if (packageName.length < subPackageStart) { classFunc(psiClass)?.let { list.add(it) } continue } val end = packageName.indexOf('.', subPackageStart) val nextName = if (end == -1) packageName.substring(subPackageStart) else packageName.substring(subPackageStart, end) if (packages.add(nextName)) { list.add(LookupElementBuilder.create(nextName).withIcon(PlatformIcons.PACKAGE_ICON)) } } return list.toArray() } fun resolve(element: PsiElement): PsiElement? { val range = element.manipulator!!.getRangeInElement(element) return Reference(element, range, range.startOffset, null).multiResolve(false).firstOrNull()?.element } final override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> { val baseRange = element.manipulator!!.getRangeInElement(element) val text = element.text!! val start = baseRange.startOffset val end = baseRange.endOffset var pos = start var current: Reference? = null val list = ArrayList<PsiReference>() while (true) { val separatorPos = text.indexOf('.', pos) if (separatorPos == -1) { list.add(Reference(element, TextRange(pos, end), start, current)) break } if (separatorPos >= end) { break } current = Reference(element, TextRange(pos, separatorPos), start, current) list.add(current) pos = separatorPos + 1 if (pos == end) { list.add(Reference(element, TextRange(end, end), start, current)) break } } return list.toTypedArray() } private inner class Reference(element: PsiElement, range: TextRange, start: Int, val previous: Reference?) : PsiReferenceBase.Poly<PsiElement>(element, range, false), InspectionReference { override val description: String get() = this@PackageNameReferenceProvider.description private val qualifiedRange = TextRange(start, range.endOffset) private val qualifiedName: String get() { val name = qualifiedRange.substring(element.text) return getBasePackage(element)?.let { it + '.' + name } ?: name } override val unresolved: Boolean get() = multiResolve(false).isEmpty() override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> { return resolve(qualifiedName, element, JavaPsiFacade.getInstance(element.project)) } override fun getVariants(): Array<Any> { return collectVariants(element, previous?.multiResolve(false)?.firstOrNull()?.element) } private fun getNewName(newTarget: PsiQualifiedNamedElement): String { val newName = newTarget.qualifiedName!! return getBasePackage(element)?.let { newName.removePrefix(it + '.') } ?: newName } override fun bindToElement(newTarget: PsiElement): PsiElement? { if (!canBindTo(newTarget)) { throw IncorrectOperationException("Cannot bind to $newTarget") } if (super.isReferenceTo(newTarget)) { return element } val newName = getNewName(newTarget as PsiQualifiedNamedElement) return element.manipulator?.handleContentChange(element, qualifiedRange, newName) } override fun isReferenceTo(element: PsiElement) = canBindTo(element) && super.isReferenceTo(element) } }
src/main/kotlin/com/demonwav/mcdev/util/reference/PackageNameReferenceProvider.kt
1338631351
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations object TranslationConstants { const val DEFAULT_LOCALE = "en_us" const val I18N_CLIENT_CLASS = "net.minecraft.client.resources.I18n" const val I18N_COMMON_CLASS = "net.minecraft.util.text.translation.I18n" const val CONSTRUCTOR = "<init>" const val TRANSLATION_COMPONENT_CLASS = "net.minecraft.util.text.TextComponentTranslation" const val COMMAND_EXCEPTION_CLASS = "net.minecraft.command.CommandException" const val FORMAT = "func_135052_a" const val TRANSLATE_TO_LOCAL = "func_74838_a" const val TRANSLATE_TO_LOCAL_FORMATTED = "func_74837_a" const val SET_BLOCK_NAME = "func_149663_c" const val SET_ITEM_NAME = "func_77655_b" }
src/main/kotlin/com/demonwav/mcdev/translations/TranslationConstants.kt
2252280639
// 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.jetbrains.python.testing import com.intellij.execution.ExecutionException import com.intellij.execution.Location import com.intellij.execution.PsiLocation import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.actions.ConfigurationContext import com.intellij.execution.actions.ConfigurationFromContext import com.intellij.execution.configurations.* import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.testframework.AbstractTestProxy import com.intellij.execution.testframework.sm.runner.SMTestLocator import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.module.Module import com.intellij.openapi.module.impl.scopes.ModuleWithDependenciesScope import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.util.JDOMExternalizerUtil.readField import com.intellij.openapi.util.JDOMExternalizerUtil.writeField import com.intellij.openapi.util.Pair import com.intellij.openapi.util.Ref import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.QualifiedName import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.remote.PathMappingProvider import com.intellij.remote.RemoteSdkAdditionalData import com.intellij.util.ThreeState import com.jetbrains.extensions.* import com.jetbrains.extenstions.ModuleBasedContextAnchor import com.jetbrains.extenstions.QNameResolveContext import com.jetbrains.extenstions.getElementAndResolvableName import com.jetbrains.extenstions.resolveToElement import com.jetbrains.python.PyBundle import com.jetbrains.python.PyNames import com.jetbrains.python.psi.PyFile import com.jetbrains.python.psi.PyFunction import com.jetbrains.python.psi.PyQualifiedNameOwner import com.jetbrains.python.psi.types.TypeEvalContext import com.jetbrains.python.run.* import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant import com.jetbrains.python.run.targetBasedConfiguration.TargetWithVariant import com.jetbrains.python.run.targetBasedConfiguration.createRefactoringListenerIfPossible import com.jetbrains.python.run.targetBasedConfiguration.targetAsPsiElement import com.jetbrains.python.sdk.PySdkUtil import com.jetbrains.reflection.DelegationProperty import com.jetbrains.reflection.Properties import com.jetbrains.reflection.Property import com.jetbrains.reflection.getProperties import jetbrains.buildServer.messages.serviceMessages.ServiceMessage import jetbrains.buildServer.messages.serviceMessages.TestStdErr import jetbrains.buildServer.messages.serviceMessages.TestStdOut import java.util.regex.Matcher /** * New configuration factories */ internal val pythonFactories: Array<PythonConfigurationFactoryBase> = arrayOf( PyUnitTestFactory, PyTestFactory, PyNoseTestFactory, PyTrialTestFactory) /** * Accepts text that may be wrapped in TC message. Unwarps it and removes TC escape code. * Regular text is unchanged */ fun processTCMessage(text: String): String { val parsedMessage = ServiceMessage.parse(text.trim()) ?: return text // Not a TC message return when (parsedMessage) { is TestStdOut -> parsedMessage.stdOut // TC with stdout is TestStdErr -> parsedMessage.stdErr // TC with stderr else -> "" // TC with out of any output } } internal fun getAdditionalArgumentsPropertyName() = com.jetbrains.python.testing.PyAbstractTestConfiguration::additionalArguments.name /** * If runner name is here that means test runner only can run inheritors for TestCase */ val RunnersThatRequireTestCaseClass: Set<String> = setOf<String>(PythonTestConfigurationsModel.PYTHONS_UNITTEST_NAME, PyTestFrameworkService.getSdkReadableNameByFramework(PyNames.TRIAL_TEST)) /** * Checks if element could be test target * @param testCaseClassRequired see [PythonUnitTestUtil] docs */ fun isTestElement(element: PsiElement, testCaseClassRequired: ThreeState, typeEvalContext: TypeEvalContext): Boolean = when (element) { is PyFile -> PythonUnitTestUtil.isTestFile(element, testCaseClassRequired, typeEvalContext) is com.intellij.psi.PsiDirectory -> element.name.contains("test", true) || element.children.any { it is PyFile && PythonUnitTestUtil.isTestFile(it, testCaseClassRequired, typeEvalContext) } is PyFunction -> PythonUnitTestUtil.isTestFunction(element, testCaseClassRequired, typeEvalContext) is com.jetbrains.python.psi.PyClass -> { PythonUnitTestUtil.isTestClass(element, testCaseClassRequired, typeEvalContext) } else -> false } /** * Since runners report names of tests as qualified name, no need to convert it to PSI and back to string. * We just save its name and provide it again to rerun * @param metainfo additional info provided by test runner, in case of pytest it is test name that could be used as "-k" argument */ private class PyTargetBasedPsiLocation(val target: ConfigurationTarget, element: PsiElement, val metainfo: String?) : PsiLocation<PsiElement>(element) { override fun equals(other: Any?): Boolean { if (other is PyTargetBasedPsiLocation) { return target == other.target && metainfo == other.metainfo } return false } override fun hashCode(): Int { return target.hashCode() } } /** * @return factory chosen by user in "test runner" settings */ private fun findConfigurationFactoryFromSettings(module: Module): ConfigurationFactory { val name = TestRunnerService.getInstance(module).projectConfiguration val factories = PythonTestConfigurationType.getInstance().configurationFactories val configurationFactory = factories.find { it.name == name } return configurationFactory ?: factories.first() } // folder provided by python side. Resolve test names versus it private val PATH_URL = java.util.regex.Pattern.compile("^python<([^<>]+)>$") /** * Resolves url into element */ fun getElementByUrl(url: String, module: Module, evalContext: TypeEvalContext): Location<out PsiElement>? { val protocol = VirtualFileManager.extractProtocol(url) ?: return null return getElementByUrl(protocol, VirtualFileManager.extractPath(url), module, evalContext) } private fun Sdk.getMapping(project: Project) = (sdkAdditionalData as? RemoteSdkAdditionalData<*>)?.let { data -> PathMappingProvider.getSuitableMappingProviders(data).flatMap { it.getPathMappingSettings(project, data).pathMappings } } ?: emptyList() private fun getFolderFromMatcher(matcher: Matcher, module: Module): String? { if (!matcher.matches()) { return null } val folder = matcher.group(1) val sdk = module.getSdk() if (sdk != null && PySdkUtil.isRemote(sdk)) { return sdk.getMapping(module.project).find { it.canReplaceRemote(folder) }?.mapToLocal(folder) } else { return folder } } private fun getElementByUrl(protocol: String, path: String, module: Module, evalContext: TypeEvalContext, matcher: Matcher = PATH_URL.matcher(protocol), metainfo: String? = null): Location<out PsiElement>? { val folder = getFolderFromMatcher(matcher, module)?.let { LocalFileSystem.getInstance().findFileByPath(it) } val qualifiedName = QualifiedName.fromDottedString(path) // Assume qname id good and resolve it directly val element = qualifiedName.resolveToElement(QNameResolveContext(ModuleBasedContextAnchor(module), evalContext = evalContext, folderToStart = folder, allowInaccurateResult = true)) return if (element != null) { // Path is qualified name of python test according to runners protocol // Parentheses are part of generators / parametrized tests // Until https://github.com/JetBrains/teamcity-messages/issues/121 they are disabled, // so we cut them out of path not to provide unsupported targets to runners val pathNoParentheses = QualifiedName.fromComponents( qualifiedName.components.filter { !it.contains('(') }).toString() PyTargetBasedPsiLocation(ConfigurationTarget(pathNoParentheses, PyRunTargetVariant.PYTHON), element, metainfo) } else { null } } object PyTestsLocator : SMTestLocator { override fun getLocation(protocol: String, path: String, metainfo: String?, project: Project, scope: GlobalSearchScope): List<Location<out PsiElement>> = getLocationInternal(protocol, path, project, metainfo, scope) override fun getLocation(protocol: String, path: String, project: Project, scope: GlobalSearchScope): List<Location<out PsiElement>> { return getLocationInternal(protocol, path, project, null, scope) } private fun getLocationInternal(protocol: String, path: String, project: Project, metainfo: String?, scope: GlobalSearchScope): List<Location<out PsiElement>> { if (scope !is ModuleWithDependenciesScope) { return listOf() } val matcher = PATH_URL.matcher(protocol) if (!matcher.matches()) { // special case: setup.py runner uses unittest configuration but different (old) protocol // delegate to old protocol locator until setup.py moved to separate configuration val oldLocation = PythonUnitTestTestIdUrlProvider.INSTANCE.getLocation(protocol, path, project, scope) if (oldLocation.isNotEmpty()) { return oldLocation } } return getElementByUrl(protocol, path, scope.module, TypeEvalContext.codeAnalysis(project, null), matcher, metainfo)?.let { listOf(it) } ?: listOf() } } abstract class PyTestExecutionEnvironment<T : PyAbstractTestConfiguration>(configuration: T, environment: ExecutionEnvironment) : PythonTestCommandLineStateBase<T>(configuration, environment) { override fun getTestLocator(): SMTestLocator = PyTestsLocator override fun getTestSpecs(): MutableList<String> = java.util.ArrayList(configuration.getTestSpec()) override fun generateCommandLine(): GeneralCommandLine { val line = super.generateCommandLine() line.workDirectory = java.io.File(configuration.workingDirectorySafe) return line } } abstract class PyAbstractTestSettingsEditor(private val sharedForm: PyTestSharedForm) : SettingsEditor<PyAbstractTestConfiguration>() { override fun resetEditorFrom(s: PyAbstractTestConfiguration) { // usePojoProperties is true because we know that Form is java-based AbstractPythonRunConfiguration.copyParams(s, sharedForm.optionsForm) s.copyTo(getProperties(sharedForm, usePojoProperties = true)) } override fun applyEditorTo(s: PyAbstractTestConfiguration) { AbstractPythonRunConfiguration.copyParams(sharedForm.optionsForm, s) s.copyFrom(getProperties(sharedForm, usePojoProperties = true)) } override fun createEditor(): javax.swing.JComponent = sharedForm.panel } /** * Default target path (run all tests ion project folder) */ private const val DEFAULT_PATH = "" /** * Target depends on target type. It could be path to file/folder or python target */ data class ConfigurationTarget(@ConfigField override var target: String, @ConfigField override var targetType: PyRunTargetVariant) : TargetWithVariant { fun copyTo(dst: ConfigurationTarget) { // TODO: do we have such method it in Kotlin? dst.target = target dst.targetType = targetType } /** * Validates configuration and throws exception if target is invalid */ fun checkValid() { if (targetType != PyRunTargetVariant.CUSTOM && target.isEmpty()) { throw RuntimeConfigurationWarning("Target not provided") } if (targetType == PyRunTargetVariant.PYTHON && !isWellFormed()) { throw RuntimeConfigurationError("Provide a qualified name of function, class or a module") } } fun asPsiElement(configuration: PyAbstractTestConfiguration): PsiElement? = asPsiElement(configuration, configuration.getWorkingDirectoryAsVirtual()) fun generateArgumentsLine(configuration: PyAbstractTestConfiguration): List<String> = when (targetType) { PyRunTargetVariant.CUSTOM -> emptyList() PyRunTargetVariant.PYTHON -> getArgumentsForPythonTarget(configuration) PyRunTargetVariant.PATH -> listOf("--path", target.trim()) } private fun getArgumentsForPythonTarget(configuration: PyAbstractTestConfiguration): List<String> { val element = asPsiElement(configuration) ?: throw ExecutionException( "Can't resolve $target. Try to remove configuration and generate it again") if (element is PsiDirectory) { // Directory is special case: we can't run it as package for now, so we run it as path return listOf("--path", element.virtualFile.path) } val context = TypeEvalContext.userInitiated(configuration.project, null) val qNameResolveContext = QNameResolveContext( contextAnchor = ModuleBasedContextAnchor(configuration.module!!), evalContext = context, folderToStart = LocalFileSystem.getInstance().findFileByPath(configuration.workingDirectorySafe), allowInaccurateResult = true ) val qualifiedNameParts = QualifiedName.fromDottedString(target.trim()).tryResolveAndSplit(qNameResolveContext) ?: throw ExecutionException("Can't find file where $target declared. " + "Make sure it is in project root") // We can't provide element qname here: it may point to parent class in case of inherited functions, // so we make fix file part, but obey element(symbol) part of qname if (!configuration.shouldSeparateTargetPath()) { // Here generate qname instead of file/path::element_name // Try to set path relative to work dir (better than path from closest root) // If we can resolve element by this path relative to working directory then use it val qNameInsideOfDirectory = qualifiedNameParts.getElementNamePrependingFile() val elementAndName = qNameInsideOfDirectory.getElementAndResolvableName(qNameResolveContext.copy(allowInaccurateResult = false)) if (elementAndName != null) { // qNameInsideOfDirectory may contain redundant elements like subtests so we use name that was really resolved // element.qname can't be used because inherited test resolves to parent return listOf("--target", elementAndName.name.toString()) } // Use "full" (path from closest root) otherwise val name = (element.containingFile as? PyFile)?.getQName()?.append(qualifiedNameParts.elementName) ?: throw ExecutionException( "Can't get importable name for ${element.containingFile}. Is it a python file in project?") return listOf("--target", name.toString()) } else { // Here generate file/path::element_name val pyTarget = qualifiedNameParts.elementName val elementFile = element.containingFile.virtualFile val workingDir = elementFile.fileSystem.findFileByPath(configuration.workingDirectorySafe) val fileSystemPartOfTarget = (if (workingDir != null) VfsUtil.getRelativePath(elementFile, workingDir) else null) ?: elementFile.path if (pyTarget.componentCount == 0) { // If python part is empty we are launching file. To prevent junk like "foo.py::" we run it as file instead return listOf("--path", fileSystemPartOfTarget) } return listOf("--target", "$fileSystemPartOfTarget::$pyTarget") } } /** * @return directory which target is situated */ fun getElementDirectory(configuration: PyAbstractTestConfiguration): VirtualFile? { if (target == DEFAULT_PATH) { //This means "current directory", so we do not know where is it // getting vitualfile for it may return PyCharm working directory which is not what we want return null } val fileOrDir = asVirtualFile() ?: asPsiElement(configuration)?.containingFile?.virtualFile ?: return null return if (fileOrDir.isDirectory) fileOrDir else fileOrDir.parent } } /** * To prevent legacy configuration options from clashing with new names, we add prefix * to use for writing/reading xml */ private val Property.prefixedName: String get() = "_new_" + this.getName() /** * Parent of all new test configurations. * All config-specific fields are implemented as properties. They are saved/restored automatically and passed to GUI form. * */ abstract class PyAbstractTestConfiguration(project: Project, configurationFactory: ConfigurationFactory, private val runnerName: String) : AbstractPythonTestRunConfiguration<PyAbstractTestConfiguration>(project, configurationFactory), PyRerunAwareConfiguration, RefactoringListenerProvider { /** * Args after it passed to test runner itself */ protected val rawArgumentsSeparator = "--" @DelegationProperty val target: ConfigurationTarget = ConfigurationTarget(DEFAULT_PATH, PyRunTargetVariant.PATH) @ConfigField var additionalArguments: String = "" val testFrameworkName: String = configurationFactory.name /** * @see [RunnersThatRequireTestCaseClass] */ fun isTestClassRequired(): ThreeState = if (RunnersThatRequireTestCaseClass.contains(runnerName)) { ThreeState.YES } else { ThreeState.NO } @Suppress("LeakingThis") // Legacy adapter is used to support legacy configs. Leak is ok here since everything takes place in one thread @DelegationProperty val legacyConfigurationAdapter: PyTestLegacyConfigurationAdapter<PyAbstractTestConfiguration> = PyTestLegacyConfigurationAdapter(this) /** * For real launch use [getWorkingDirectorySafe] instead */ internal fun getWorkingDirectoryAsVirtual(): VirtualFile? { if (!workingDirectory.isNullOrEmpty()) { return LocalFileSystem.getInstance().findFileByPath(workingDirectory) } return null } override fun getWorkingDirectorySafe(): String { val dirProvidedByUser = super.getWorkingDirectory() if (!dirProvidedByUser.isNullOrEmpty()) { return dirProvidedByUser } return target.getElementDirectory(this)?.path ?: super.getWorkingDirectorySafe() } override fun getRefactoringElementListener(element: PsiElement?): RefactoringElementListener? { if (element == null) return null var renamer = CompositeRefactoringElementListener(PyWorkingDirectoryRenamer(getWorkingDirectoryAsVirtual(), this)) createRefactoringListenerIfPossible(element, target.asPsiElement(this), target.asVirtualFile(), { target.target = it })?.let { renamer = renamer.plus(it) } return renamer } override fun checkConfiguration() { super.checkConfiguration() if (!isFrameworkInstalled()) { throw RuntimeConfigurationWarning( PyBundle.message("runcfg.testing.no.test.framework", testFrameworkName)) } target.checkValid() } /** * Check if framework is available on SDK */ abstract fun isFrameworkInstalled(): Boolean override fun isIdTestBased(): Boolean = true private fun getPythonTestSpecByLocation(location: Location<*>): List<String> { if (location is PyTargetBasedPsiLocation) { return location.target.generateArgumentsLine(this) } if (location !is PsiLocation) { return emptyList() } if (location.psiElement !is PyQualifiedNameOwner) { return emptyList() } val qualifiedName = (location.psiElement as PyQualifiedNameOwner).qualifiedName ?: return emptyList() // Resolve name as python qname as last resort return ConfigurationTarget(qualifiedName, PyRunTargetVariant.PYTHON).generateArgumentsLine(this) } override fun getTestSpec(location: Location<*>, failedTest: com.intellij.execution.testframework.AbstractTestProxy): String? { val list = getPythonTestSpecByLocation(location) if (list.isEmpty()) { return null } else { return list.joinToString(" ") } } override fun getTestSpecsForRerun(scope: com.intellij.psi.search.GlobalSearchScope, locations: MutableList<Pair<Location<*>, AbstractTestProxy>>): List<String> { val result = java.util.ArrayList<String>() // Set used to remove duplicate targets locations.map { it.first }.distinctBy { it.psiElement }.map { getPythonTestSpecByLocation(it) }.forEach { result.addAll(it) } return result + generateRawArguments(true) } fun getTestSpec(): List<String> { return target.generateArgumentsLine(this) + generateRawArguments() } /** * raw arguments to be added after "--" and passed to runner directly */ private fun generateRawArguments(forRerun: Boolean = false): List<String> { val rawArguments = additionalArguments + " " + getCustomRawArgumentsString(forRerun) if (rawArguments.isNotBlank()) { return listOf(rawArgumentsSeparator) + com.intellij.util.execution.ParametersListUtil.parse(rawArguments, false, true) } return emptyList() } override fun suggestedName(): String = when (target.targetType) { PyRunTargetVariant.PATH -> { val name = target.asVirtualFile()?.name "$testFrameworkName in " + (name ?: target.target) } PyRunTargetVariant.PYTHON -> { "$testFrameworkName for " + target.target } else -> { testFrameworkName } } /** * @return configuration-specific arguments */ protected open fun getCustomRawArgumentsString(forRerun: Boolean = false): String = "" fun reset() { target.target = DEFAULT_PATH target.targetType = PyRunTargetVariant.PATH additionalArguments = "" } fun copyFrom(src: Properties) { src.copyTo(getConfigFields()) } fun copyTo(dst: Properties) { getConfigFields().copyTo(dst) } override fun writeExternal(element: org.jdom.Element) { // Write legacy config to preserve it legacyConfigurationAdapter.writeExternal(element) // Super is called after to overwrite legacy settings with new one super.writeExternal(element) val gson = com.google.gson.Gson() getConfigFields().properties.forEach { val value = it.get() if (value != null) { // No need to write null since null is default value writeField(element, it.prefixedName, gson.toJson(value)) } } } override fun readExternal(element: org.jdom.Element) { super.readExternal(element) val gson = com.google.gson.Gson() getConfigFields().properties.forEach { val fromJson: Any? = gson.fromJson(readField(element, it.prefixedName), it.getType()) if (fromJson != null) { it.set(fromJson) } } legacyConfigurationAdapter.readExternal(element) } private fun getConfigFields() = getProperties(this, ConfigField::class.java) /** * Checks if element could be test target for this config. * Function is used to create tests by context. * * If yes, and element is [PsiElement] then it is [PyRunTargetVariant.PYTHON]. * If file then [PyRunTargetVariant.PATH] */ fun couldBeTestTarget(element: PsiElement): Boolean { // TODO: PythonUnitTestUtil logic is weak. We should give user ability to launch test on symbol since user knows better if folder // contains tests etc val context = TypeEvalContext.userInitiated(element.project, element.containingFile) return isTestElement(element, isTestClassRequired(), context) } /** * There are 2 ways to provide target to runner: * * As full qname (package1.module1.Class1.test_foo) * * As filesystem path (package1/module1.py::Class1.test_foo) full or relative to working directory * * Second approach is prefered if this flag is set. It is generally better because filesystem path does not need __init__.py */ internal open fun shouldSeparateTargetPath(): Boolean = true /** * @param metaInfo String "metainfo" field provided by test runner */ open fun setMetaInfo(metaInfo: String) { } /** * @return Boolean if metainfo and target produces same configuration */ open fun isSameAsLocation(target: ConfigurationTarget, metainfo: String?): Boolean = target == this.target } abstract class PyAbstractTestFactory<out CONF_T : PyAbstractTestConfiguration> : PythonConfigurationFactoryBase( PythonTestConfigurationType.getInstance()) { abstract override fun createTemplateConfiguration(project: Project): CONF_T } /** * Only one producer is registered with EP, but it uses factory configured by user to produce different configs */ internal class PyTestsConfigurationProducer : AbstractPythonTestConfigurationProducer<PyAbstractTestConfiguration>() { companion object { /** * Creates [ConfigurationTarget] to make configuration work with provided element. * Also reports working dir what should be set to configuration to work correctly * @return [target, workingDirectory] */ internal fun getTargetForConfig(configuration: PyAbstractTestConfiguration, baseElement: PsiElement): Pair<ConfigurationTarget, String?>? { var element = baseElement // Go up until we reach top of the file // asking configuration about each element if it is supported or not // If element is supported -- set it as configuration target do { if (configuration.couldBeTestTarget(element)) { when (element) { is PyQualifiedNameOwner -> { // Function, class, method val module = configuration.module ?: return null val elementFile = element.containingFile as? PyFile ?: return null val workingDirectory = getDirectoryForFileToBeImportedFrom(elementFile) ?: return null val context = QNameResolveContext(ModuleBasedContextAnchor(module), evalContext = TypeEvalContext.userInitiated(configuration.project, null), folderToStart = workingDirectory.virtualFile) val parts = element.tryResolveAndSplit(context) ?: return null val qualifiedName = parts.getElementNamePrependingFile(workingDirectory) return Pair(ConfigurationTarget(qualifiedName.toString(), PyRunTargetVariant.PYTHON), workingDirectory.virtualFile.path) } is PsiFileSystemItem -> { val virtualFile = element.virtualFile val path = virtualFile val workingDirectory = when (element) { is PyFile -> getDirectoryForFileToBeImportedFrom(element) is PsiDirectory -> element else -> return null }?.virtualFile?.path ?: return null return Pair(ConfigurationTarget(path.path, PyRunTargetVariant.PATH), workingDirectory) } } } element = element.parent ?: break } while (element !is PsiDirectory) // if parent is folder, then we are at file level return null } /** * Inspects file relative imports, finds farthest and returns folder with imported file */ private fun getDirectoryForFileToBeImportedFrom(file: PyFile): PsiDirectory? { val maxRelativeLevel = file.fromImports.map { it.relativeLevel }.max() ?: 0 var elementFolder = file.parent ?: return null for (i in 1..maxRelativeLevel) { elementFolder = elementFolder.parent ?: return null } return elementFolder } } init { if (!isNewTestsModeEnabled()) { throw ExtensionNotApplicableException.INSTANCE } } override fun getConfigurationFactory() = PythonTestConfigurationType.getInstance().configurationFactories[0] override val configurationClass: Class<PyAbstractTestConfiguration> = PyAbstractTestConfiguration::class.java override fun createLightConfiguration(context: ConfigurationContext): RunConfiguration? { val module = context.module ?: return null val project = context.project ?: return null val configuration = findConfigurationFactoryFromSettings(module).createTemplateConfiguration(project) as? PyAbstractTestConfiguration ?: return null if (!setupConfigurationFromContext(configuration, context, Ref(context.psiLocation))) return null return configuration } override fun cloneTemplateConfiguration(context: ConfigurationContext): RunnerAndConfigurationSettings { return cloneTemplateConfigurationStatic(context, findConfigurationFactoryFromSettings(context.module)) } override fun createConfigurationFromContext(context: ConfigurationContext?): ConfigurationFromContext? { // Since we need module, no need to even try to create config with out of it context?.module ?: return null return super.createConfigurationFromContext(context) } override fun findOrCreateConfigurationFromContext(context: ConfigurationContext?): ConfigurationFromContext? { if (!isNewTestsModeEnabled()) { return null } return super.findOrCreateConfigurationFromContext(context) } // test configuration is always prefered over regular one override fun shouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean = other.configuration is PythonRunConfiguration override fun isPreferredConfiguration(self: ConfigurationFromContext?, other: ConfigurationFromContext): Boolean = other.configuration is PythonRunConfiguration override fun setupConfigurationFromContext(configuration: PyAbstractTestConfiguration?, context: ConfigurationContext?, sourceElement: Ref<PsiElement>?): Boolean { if (sourceElement == null || configuration == null) { return false } val element = sourceElement.get() ?: return false if (element.containingFile !is PyFile && element !is PsiDirectory) { return false } val location = context?.location configuration.module = context?.module configuration.isUseModuleSdk = true if (location is PyTargetBasedPsiLocation) { location.target.copyTo(configuration.target) location.metainfo?.let { configuration.setMetaInfo(it) } } else { val targetForConfig = PyTestsConfigurationProducer.getTargetForConfig(configuration, element) ?: return false targetForConfig.first.copyTo(configuration.target) // Directory may be set in Default configuration. In that case no need to rewrite it. if (configuration.workingDirectory.isNullOrEmpty()) { configuration.workingDirectory = targetForConfig.second } } configuration.setGeneratedName() return true } override fun isConfigurationFromContext(configuration: PyAbstractTestConfiguration, context: ConfigurationContext?): Boolean { if (context != null && PyTestConfigurationSelector.EP.extensionList.find { it.isFromContext(configuration, context) } != null) { return true } val location = context?.location if (location is PyTargetBasedPsiLocation) { // With derived classes several configurations for same element may exist return configuration.isSameAsLocation(location.target, location.metainfo) } val psiElement = context?.psiLocation ?: return false val targetForConfig = PyTestsConfigurationProducer.getTargetForConfig(configuration, psiElement) ?: return false if (configuration.target != targetForConfig.first) { return false } //Even of both configurations have same targets, it could be that both have same qname which is resolved // to different elements due to different working folders. // Resolve them and check files if (configuration.target.targetType != PyRunTargetVariant.PYTHON) return true val targetPsi = targetAsPsiElement(configuration.target.targetType, configuration.target.target, configuration, configuration.getWorkingDirectoryAsVirtual()) ?: return true return targetPsi.containingFile == psiElement.containingFile } } @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.PROPERTY) /** * Mark run configuration field with it to enable saving, resotring and form iteraction */ annotation class ConfigField
python/src/com/jetbrains/python/testing/PyTestsShared.kt
2320376054
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.references import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrReferenceExpressionImpl import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.resolveKinds import org.jetbrains.plugins.groovy.lang.resolve.GrReferenceResolveRunner import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyCachingReference import org.jetbrains.plugins.groovy.lang.resolve.impl.filterByArgumentsCount import org.jetbrains.plugins.groovy.lang.resolve.impl.filterBySignature import org.jetbrains.plugins.groovy.lang.resolve.impl.getArguments import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyRValueProcessor import org.jetbrains.plugins.groovy.lang.resolve.processors.MethodProcessor class GrExplicitMethodCallReference(ref: GrReferenceExpressionImpl) : GroovyCachingReference<GrReferenceExpressionImpl>(ref) { override fun doResolve(incomplete: Boolean): Collection<GroovyResolveResult> { require(!incomplete) val ref = element val name = ref.referenceName ?: return emptyList() val methodCall = ref.parent as GrMethodCall val arguments = methodCall.getArguments() val methodProcessor = MethodProcessor(name, ref, arguments, ref.typeArguments) GrReferenceResolveRunner(ref, methodProcessor).resolveReferenceExpression() methodProcessor.applicableCandidates?.let { return it } val propertyProcessor = GroovyRValueProcessor(name, ref, ref.resolveKinds()) GrReferenceResolveRunner(ref, propertyProcessor).resolveReferenceExpression() val properties = propertyProcessor.results if (properties.size == 1) { return properties } val methods = filterBySignature(filterByArgumentsCount(methodProcessor.allCandidates, arguments)) return methods + properties } }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/references/GrExplicitMethodCallReference.kt
2000979115
package org.runestar.client.api.forms import javax.swing.KeyStroke data class KeyStrokeForm( val description: String ) { @Transient val value: KeyStroke = KeyStroke.getKeyStroke(description) }
api/src/main/java/org/runestar/client/api/forms/KeyStrokeForm.kt
2068814490
// 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.inspections import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.SmartPsiElementPointer import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.base.psi.isOneLiner import org.jetbrains.kotlin.idea.intentions.loopToCallChain.countUsages import org.jetbrains.kotlin.idea.intentions.loopToCallChain.previousStatement import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor class MoveVariableDeclarationIntoWhenInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = whenExpressionVisitor(fun(expression: KtWhenExpression) { val subjectExpression = expression.subjectExpression ?: return val property = expression.findDeclarationNear() ?: return val identifier = property.nameIdentifier ?: return val initializer = property.initializer ?: return if (!initializer.isOneLiner()) return if (initializer.anyDescendantOfType<KtExpression> { it is KtThrowExpression || it is KtReturnExpression || it is KtBreakExpression || it is KtContinueExpression }) return val action = property.action(expression) if (action == Action.NOTHING) return if (action == Action.MOVE && !property.isOneLiner()) return holder.registerProblem( property, TextRange.from(identifier.startOffsetInParent, identifier.textLength), action.description, action.createFix(subjectExpression.createSmartPointer()) ) }) } private enum class Action { NOTHING, MOVE, INLINE; val description: String get() = when (this) { MOVE -> KotlinBundle.message("variable.declaration.could.be.moved.into.when") INLINE -> KotlinBundle.message("variable.declaration.could.be.inlined") NOTHING -> KotlinBundle.message("nothing.to.do") } fun createFix(subjectExpressionPointer: SmartPsiElementPointer<KtExpression>): VariableDeclarationIntoWhenFix = when (this) { MOVE -> VariableDeclarationIntoWhenFix(KotlinBundle.message("move.variable.declaration.into.when"), subjectExpressionPointer) { it } INLINE -> VariableDeclarationIntoWhenFix(KotlinBundle.message("inline.variable"), subjectExpressionPointer) { it.initializer } else -> error("Illegal action") } } private fun KtProperty.action(element: KtElement): Action = when (val elementUsages = countUsages(element)) { countUsages() -> if (elementUsages == 1) Action.INLINE else Action.MOVE else -> Action.NOTHING } private fun KtWhenExpression.findDeclarationNear(): KtProperty? { val previousProperty = previousStatement() as? KtProperty ?: previousPropertyFromParent() ?: return null return previousProperty.takeIf { !it.isVar && it.hasInitializer() && it.nameIdentifier?.text == subjectExpression?.text } } private tailrec fun KtExpression.previousPropertyFromParent(): KtProperty? { val parentExpression = parent as? KtExpression ?: return null if (this != when (parentExpression) { is KtProperty -> parentExpression.initializer is KtReturnExpression -> parentExpression.returnedExpression is KtBinaryExpression -> parentExpression.left is KtUnaryExpression -> parentExpression.baseExpression else -> null } ) return null return parentExpression.previousStatement() as? KtProperty ?: parentExpression.previousPropertyFromParent() } private class VariableDeclarationIntoWhenFix( @Nls private val actionName: String, private val subjectExpressionPointer: SmartPsiElementPointer<KtExpression>, private val transform: (KtProperty) -> KtExpression? ) : LocalQuickFix { override fun getName() = actionName override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val property = descriptor.psiElement as? KtProperty ?: return val subjectExpression = subjectExpressionPointer.element ?: return val newElement = property.copy() as? KtProperty ?: return val toReplace = transform(newElement) ?: return val tailComments = newElement.allChildren.toList().takeLastWhile { it is PsiWhiteSpace || it is PsiComment } if (tailComments.isNotEmpty()) { val leftBrace = subjectExpression.siblings(withItself = false).firstOrNull { it.node.elementType == KtTokens.LBRACE } if (leftBrace != null) { tailComments.reversed().forEach { subjectExpression.parent.addAfter(it, leftBrace) it.delete() } } } val docComment = newElement.docComment if (docComment != null) { val whenExpression = subjectExpression.parent whenExpression.parent.addBefore(docComment, whenExpression) docComment.delete() } val resultElement = subjectExpression.replace(toReplace) property.delete() val editor = resultElement.findExistingEditor() ?: return editor.moveCaret((resultElement as? KtProperty)?.nameIdentifier?.startOffset ?: resultElement.startOffset) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/MoveVariableDeclarationIntoWhenInspection.kt
3889012389
package quickbeer.android.domain.review.store import javax.inject.Inject import quickbeer.android.data.store.core.CachingStoreCore import quickbeer.android.domain.review.Review class ReviewStoreCore @Inject constructor( roomCore: ReviewRoomCore ) : CachingStoreCore<Int, Review>(roomCore, Review::id, Review.merger)
app/src/main/java/quickbeer/android/domain/review/store/ReviewStoreCore.kt
4277339055
// 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.maven.configuration import com.intellij.codeInsight.CodeInsightUtilCore import com.intellij.codeInsight.daemon.impl.quickfix.OrderEntryFix import com.intellij.ide.actions.OpenFileAction import com.intellij.ide.highlighter.JavaFileType import com.intellij.openapi.application.runReadAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.roots.DependencyScope import com.intellij.openapi.roots.ExternalLibraryDescriptor import com.intellij.openapi.roots.JavaProjectModelModificationService import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vfs.WritingAccessProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.search.FileTypeIndex import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.xml.XmlFile import org.jetbrains.idea.maven.dom.MavenDomUtil import org.jetbrains.idea.maven.dom.model.MavenDomPlugin import org.jetbrains.idea.maven.model.MavenId import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.utils.MavenArtifactScope import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.base.projectStructure.ModuleSourceRootGroup import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.configuration.* import org.jetbrains.kotlin.idea.facet.getRuntimeLibraryVersion import org.jetbrains.kotlin.idea.facet.getRuntimeLibraryVersionOrDefault import org.jetbrains.kotlin.idea.framework.ui.ConfigureDialogWithModulesAndVersion import org.jetbrains.kotlin.idea.maven.* import org.jetbrains.kotlin.idea.projectConfiguration.LibraryJarDescriptor import org.jetbrains.kotlin.idea.configuration.NotificationMessageCollector import org.jetbrains.kotlin.idea.quickfix.AbstractChangeFeatureSupportLevelFix abstract class KotlinMavenConfigurator protected constructor( private val testArtifactId: String?, private val addJunit: Boolean, override val name: String, override val presentableText: String ) : KotlinProjectConfigurator { override fun getStatus(moduleSourceRootGroup: ModuleSourceRootGroup): ConfigureKotlinStatus { val module = moduleSourceRootGroup.baseModule if (module.buildSystemType != BuildSystemType.Maven) return ConfigureKotlinStatus.NON_APPLICABLE val psi = runReadAction { findModulePomFile(module) } if (psi == null || !psi.isValid || psi !is XmlFile || psi.virtualFile == null ) { return ConfigureKotlinStatus.BROKEN } if (isKotlinModule(module)) { return runReadAction { checkKotlinPlugin(module) } } return ConfigureKotlinStatus.CAN_BE_CONFIGURED } private fun checkKotlinPlugin(module: Module): ConfigureKotlinStatus { val psi = findModulePomFile(module) as? XmlFile ?: return ConfigureKotlinStatus.BROKEN val pom = PomFile.forFileOrNull(psi) ?: return ConfigureKotlinStatus.NON_APPLICABLE if (hasKotlinPlugin(pom)) { return ConfigureKotlinStatus.CONFIGURED } val mavenProjectsManager = MavenProjectsManager.getInstance(module.project) val mavenProject = mavenProjectsManager.findProject(module) ?: return ConfigureKotlinStatus.BROKEN val kotlinPluginId = kotlinPluginId(null) val kotlinPlugin = mavenProject.plugins.find { it.mavenId.equals(kotlinPluginId.groupId, kotlinPluginId.artifactId) } ?: return ConfigureKotlinStatus.CAN_BE_CONFIGURED if (kotlinPlugin.executions.any { it.goals.any(this::isRelevantGoal) }) { return ConfigureKotlinStatus.CONFIGURED } return ConfigureKotlinStatus.CAN_BE_CONFIGURED } private fun hasKotlinPlugin(pom: PomFile): Boolean { val plugin = pom.findPlugin(kotlinPluginId(null)) ?: return false return plugin.executions.executions.any { it.goals.goals.any { isRelevantGoal(it.stringValue ?: "") } } } override fun configure(project: Project, excludeModules: Collection<Module>) { val dialog = ConfigureDialogWithModulesAndVersion(project, this, excludeModules, getMinimumSupportedVersion()) dialog.show() if (!dialog.isOK) return WriteCommandAction.runWriteCommandAction(project) { val collector = NotificationMessageCollector.create(project) for (module in excludeMavenChildrenModules(project, dialog.modulesToConfigure)) { val file = findModulePomFile(module) if (file != null && canConfigureFile(file)) { configureModule(module, file, IdeKotlinVersion.get(dialog.kotlinVersion), collector) OpenFileAction.openFile(file.virtualFile, project) } else { showErrorMessage(project, KotlinMavenBundle.message("error.cant.find.pom.for.module", module.name)) } } collector.showNotification() } } protected open fun getMinimumSupportedVersion() = "1.0.0" protected abstract fun isKotlinModule(module: Module): Boolean protected abstract fun isRelevantGoal(goalName: String): Boolean protected abstract fun createExecutions(pomFile: PomFile, kotlinPlugin: MavenDomPlugin, module: Module) protected abstract fun getStdlibArtifactId(module: Module, version: IdeKotlinVersion): String open fun configureModule(module: Module, file: PsiFile, version: IdeKotlinVersion, collector: NotificationMessageCollector): Boolean = changePomFile(module, file, version, collector) private fun changePomFile( module: Module, file: PsiFile, version: IdeKotlinVersion, collector: NotificationMessageCollector ): Boolean { val virtualFile = file.virtualFile ?: error("Virtual file should exists for psi file " + file.name) val domModel = MavenDomUtil.getMavenDomProjectModel(module.project, virtualFile) if (domModel == null) { showErrorMessage(module.project, null) return false } val pom = PomFile.forFileOrNull(file as XmlFile) ?: return false pom.addProperty(KOTLIN_VERSION_PROPERTY, version.artifactVersion) pom.addDependency( MavenId(GROUP_ID, getStdlibArtifactId(module, version), "\${$KOTLIN_VERSION_PROPERTY}"), MavenArtifactScope.COMPILE, null, false, null ) if (testArtifactId != null) { pom.addDependency(MavenId(GROUP_ID, testArtifactId, "\${$KOTLIN_VERSION_PROPERTY}"), MavenArtifactScope.TEST, null, false, null) } if (addJunit) { // TODO currently it is always disabled: junit version selection could be shown in the configurator dialog pom.addDependency(MavenId("junit", "junit", "4.12"), MavenArtifactScope.TEST, null, false, null) } val repositoryDescription = getRepositoryForVersion(version) if (repositoryDescription != null) { pom.addLibraryRepository(repositoryDescription) pom.addPluginRepository(repositoryDescription) } val plugin = pom.addPlugin(MavenId(GROUP_ID, MAVEN_PLUGIN_ID, "\${$KOTLIN_VERSION_PROPERTY}")) createExecutions(pom, plugin, module) configurePlugin(pom, plugin, module, version) CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement<PsiFile>(file) collector.addMessage(KotlinMavenBundle.message("file.was.modified", virtualFile.path)) return true } protected open fun configurePlugin(pom: PomFile, plugin: MavenDomPlugin, module: Module, version: IdeKotlinVersion) { } protected fun createExecution( pomFile: PomFile, kotlinPlugin: MavenDomPlugin, executionId: String, goalName: String, module: Module, isTest: Boolean ) { pomFile.addKotlinExecution(module, kotlinPlugin, executionId, PomFile.getPhase(false, isTest), isTest, listOf(goalName)) if (hasJavaFiles(module)) { pomFile.addJavacExecutions(module, kotlinPlugin) } } override fun updateLanguageVersion( module: Module, languageVersion: String?, apiVersion: String?, requiredStdlibVersion: ApiVersion, forTests: Boolean ) { fun doUpdateMavenLanguageVersion(): PsiElement? { val psi = findModulePomFile(module) as? XmlFile ?: return null val pom = PomFile.forFileOrNull(psi) ?: return null return pom.changeLanguageVersion( languageVersion, apiVersion ) } val runtimeUpdateRequired = getRuntimeLibraryVersion(module)?.apiVersion?.let { runtimeVersion -> runtimeVersion < requiredStdlibVersion } ?: false if (runtimeUpdateRequired) { Messages.showErrorDialog( module.project, KotlinMavenBundle.message("update.language.version.feature", requiredStdlibVersion), KotlinMavenBundle.message("update.language.version.title") ) return } val element = doUpdateMavenLanguageVersion() if (element == null) { Messages.showErrorDialog( module.project, KotlinMavenBundle.message("error.failed.update.pom"), KotlinMavenBundle.message("update.language.version.title") ) } else { OpenFileDescriptor(module.project, element.containingFile.virtualFile, element.textRange.startOffset).navigate(true) } } override fun addLibraryDependency( module: Module, element: PsiElement, library: ExternalLibraryDescriptor, libraryJarDescriptor: LibraryJarDescriptor, scope: DependencyScope ) { val scope = OrderEntryFix.suggestScopeByLocation(module, element) JavaProjectModelModificationService.getInstance(module.project).addDependency(module, library, scope) } override fun changeGeneralFeatureConfiguration( module: Module, feature: LanguageFeature, state: LanguageFeature.State, forTests: Boolean ) { val sinceVersion = feature.sinceApiVersion val messageTitle = AbstractChangeFeatureSupportLevelFix.getFixText(state, feature.presentableName) if (state != LanguageFeature.State.DISABLED && getRuntimeLibraryVersionOrDefault(module).apiVersion < sinceVersion) { Messages.showErrorDialog( module.project, KotlinMavenBundle.message("update.language.version.feature.support", feature.presentableName, sinceVersion), messageTitle ) return } val element = changeMavenFeatureConfiguration( module, feature, state, messageTitle ) if (element != null) { OpenFileDescriptor(module.project, element.containingFile.virtualFile, element.textRange.startOffset).navigate(true) } } private fun changeMavenFeatureConfiguration( module: Module, feature: LanguageFeature, state: LanguageFeature.State, @NlsContexts.DialogTitle messageTitle: String ): PsiElement? { val psi = findModulePomFile(module) as? XmlFile ?: return null val pom = PomFile.forFileOrNull(psi) ?: return null val element = pom.changeFeatureConfiguration(feature, state) if (element == null) { Messages.showErrorDialog( module.project, KotlinMavenBundle.message("error.failed.update.pom"), messageTitle ) } return element } companion object { const val GROUP_ID = "org.jetbrains.kotlin" const val MAVEN_PLUGIN_ID = "kotlin-maven-plugin" private const val KOTLIN_VERSION_PROPERTY = "kotlin.version" private fun hasJavaFiles(module: Module): Boolean { return !FileTypeIndex.getFiles(JavaFileType.INSTANCE, GlobalSearchScope.moduleScope(module)).isEmpty() } fun findModulePomFile(module: Module): PsiFile? { val files = MavenProjectsManager.getInstance(module.project).projectsFiles for (file in files) { val fileModule = ModuleUtilCore.findModuleForFile(file, module.project) if (module != fileModule) continue val psiFile = PsiManager.getInstance(module.project).findFile(file) ?: continue if (!MavenDomUtil.isProjectFile(psiFile)) continue return psiFile } return null } private fun canConfigureFile(file: PsiFile): Boolean { return WritingAccessProvider.isPotentiallyWritable(file.virtualFile, null) } private fun showErrorMessage(project: Project, @NlsContexts.DialogMessage message: String?) { val cantConfigureAutomatically = KotlinMavenBundle.message("error.cant.configure.maven.automatically") val seeInstructions = KotlinMavenBundle.message("error.see.installation.instructions") Messages.showErrorDialog( project, "<html>$cantConfigureAutomatically<br/>${if (message != null) "$message</br>" else ""}$seeInstructions</html>", KotlinMavenBundle.message("configure.title") ) } } }
plugins/kotlin/maven/src/org/jetbrains/kotlin/idea/maven/configuration/KotlinMavenConfigurator.kt
30736813
/* * Copyright 2022 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.j2cl.transpiler.backend.kotlin.ast // https://kotlinlang.org/docs/keyword-reference.html#hard-keywords private val hardKeywordSet = setOf( "as", "as?", "break", "class", "continue", "do", "else", "false", "for", "fun", "if", "in", "interface", "!in", "is", "!is", "null", "object", "package", "return", "super", "this", "throw", "true", "try", "typealias", "typeof", "val", "var", "when", "while" ) /** * Returns {@code true} if {@code string} is a hard keyword: * https://kotlinlang.org/docs/keyword-reference.html#hard-keywords */ fun isHardKeyword(string: String) = hardKeywordSet.contains(string)
transpiler/java/com/google/j2cl/transpiler/backend/kotlin/ast/Keywords.kt
1094314674
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.jetbrains.python.run.runAnything import com.intellij.execution.RunManager import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.actions.ChooseRunConfigurationPopup import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.ParametersList import com.intellij.execution.configurations.RuntimeConfigurationException import com.intellij.ide.actions.runAnything.activity.RunAnythingMatchedRunConfigurationProvider import com.intellij.openapi.actionSystem.DataContext import com.jetbrains.python.run.PythonConfigurationType import com.jetbrains.python.run.PythonRunConfiguration /** * @author vlan */ class PyRunAnythingProvider : RunAnythingMatchedRunConfigurationProvider() { override fun createConfiguration(dataContext: DataContext, pattern: String): RunnerAndConfigurationSettings { val runManager = RunManager.getInstance(dataContext.project) val settings = runManager.createConfiguration(pattern, configurationFactory) val commandLine = ParametersList.parse(pattern) val arguments = commandLine.drop(1) val configuration = settings.configuration as? PythonRunConfiguration val workingDir = dataContext.virtualFile configuration?.apply { val first = arguments.getOrNull(0) when { first == "-m" -> { scriptName = arguments.getOrNull(1) scriptParameters = ParametersList.join(arguments.drop(2)) isModuleMode = true } first?.startsWith("-m") == true -> { scriptName = first.substring(2) scriptParameters = ParametersList.join(arguments.drop(1)) isModuleMode = true } else -> { scriptName = first scriptParameters = ParametersList.join(arguments.drop(1)) } } workingDir?.findPythonSdk(project)?.let { sdkHome = it.homePath sdk = it } workingDir?.let { workingDirectory = it.canonicalPath } } return settings } override fun getConfigurationFactory(): ConfigurationFactory = PythonConfigurationType.getInstance().factory override fun findMatchingValue(dataContext: DataContext, pattern: String): ChooseRunConfigurationPopup.ItemWrapper<*>? { if (!pattern.startsWith("python ")) return null val configuration = createConfiguration(dataContext, pattern) try { configuration.checkSettings() } catch (e: RuntimeConfigurationException) { return null } return ChooseRunConfigurationPopup.ItemWrapper.wrap(dataContext.project, configuration) } override fun getHelpCommand() = "python" override fun getHelpGroupTitle(): String = "Python" // NON-NLS override fun getHelpCommandPlaceholder() = "python <file name>" }
python/src/com/jetbrains/python/run/runAnything/PyRunAnythingProvider.kt
2891802702
package com.starstorm.beer.activity import android.content.Intent import android.os.Bundle import android.support.v7.app.ActionBarActivity import android.view.View import android.widget.ProgressBar import com.novoda.notils.caster.Views import com.parse.ParseFacebookUtils import com.parse.ParseUser import com.starstorm.beer.R import com.starstorm.beer.fragment.LoginFragment public class LoginActivity : ActionBarActivity() { private var loginFragment: LoginFragment? = null private var loginProgress: ProgressBar? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) loginProgress = Views.findById<ProgressBar>(this, R.id.login_progress) if (savedInstanceState == null) { loginFragment = LoginFragment.newInstance() getFragmentManager().beginTransaction().add(R.id.container, loginFragment).hide(loginFragment).commit() } } override fun onResume() { super.onResume() if (ParseUser.getCurrentUser() != null) { // logged in, go to main page val intent = Intent(this, javaClass<MainActivity>()) startActivity(intent) overridePendingTransition(0, 0) finish() return } // hide progress indicator loginProgress!!.setVisibility(View.GONE) // show login fragment getFragmentManager().beginTransaction().show(loginFragment).commit() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { super.onActivityResult(requestCode, resultCode, data) ParseFacebookUtils.finishAuthentication(requestCode, resultCode, data) } }
android/app/src/main/kotlin/com/starstorm/beer/activity/LoginActivity.kt
3744355706
package com.oneeyedmen.konsent open class AcceptanceTest { companion object { lateinit var recorder: FeatureRecorder // initialised by Konsent } }
src/main/java/com/oneeyedmen/konsent/AcceptanceTest.kt
128835608
/* * Copyright (c) 2019. * Neato Robotics Inc. */ package com.neatorobotics.sdk.android.robotservices.housecleaning class HouseCleaningBasic1Service : HouseCleaningService() { override val isMultipleZonesCleaningSupported: Boolean get() = false override val isEcoModeSupported: Boolean get() = true override val isTurboModeSupported: Boolean get() = true override val isExtraCareModeSupported: Boolean get() = false override val isCleaningAreaSupported: Boolean get() = false override val isCleaningFrequencySupported: Boolean get() = false companion object { private const val TAG = "HouseCleaningBasic1" } }
Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/robotservices/housecleaning/HouseCleaningBasic1Service.kt
471757188
// 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.model.psi.impl import com.intellij.codeInsight.daemon.impl.IdentifierUtil import com.intellij.codeInsight.highlighting.HighlightUsagesHandler import com.intellij.model.psi.PsiSymbolDeclaration import com.intellij.model.psi.PsiSymbolService import com.intellij.model.search.PsiSymbolDeclarationSearchParameters import com.intellij.model.search.PsiSymbolDeclarationSearcher import com.intellij.openapi.util.TextRange import com.intellij.pom.PomTargetPsiElement import com.intellij.pom.PsiDeclaredTarget import com.intellij.psi.ExternallyAnnotated import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiTarget import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.psi.util.PsiUtilBase import com.intellij.util.ArrayQuery import com.intellij.util.Query class PsiElementDeclarationSearcher : PsiSymbolDeclarationSearcher { override fun collectSearchRequests(parameters: PsiSymbolDeclarationSearchParameters): Collection<Query<out PsiSymbolDeclaration>> { val psi = PsiSymbolService.getInstance().extractElementFromSymbol(parameters.symbol) ?: return emptyList() val declaration = getDeclaration(psi, parameters.searchScope) ?: return emptyList() return listOf(ArrayQuery(declaration)) } private fun getDeclaration(psi: PsiElement, searchScope: SearchScope): PsiSymbolDeclaration? { if (searchScope is LocalSearchScope) { return inLocalScope(psi, searchScope) } else { return inGlobalScope(psi, searchScope as GlobalSearchScope) } } private fun inLocalScope(psi: PsiElement, searchScope: LocalSearchScope): PsiSymbolDeclaration? { for (scopeElement in searchScope.scope) { val scopeFile = scopeElement.containingFile ?: continue val declarationRange = HighlightUsagesHandler.getNameIdentifierRangeInCurrentRoot(scopeFile, psi) ?: continue // call old implementation as is return PsiElement2Declaration(psi, scopeFile, declarationRange.getSecond()) } return null } private fun inGlobalScope(psi: PsiElement, searchScope: GlobalSearchScope): PsiSymbolDeclaration? { val containingFile = psi.containingFile ?: return null val virtualFile = containingFile.virtualFile ?: return null if (!searchScope.contains(virtualFile)) { return null } return when (psi) { is PsiFile -> null // files don't have declarations inside PSI is PomTargetPsiElement -> fromPomTargetElement(psi) else -> PsiElement2Declaration.createFromTargetPsiElement(psi) } } private fun fromPomTargetElement(psi: PomTargetPsiElement): PsiSymbolDeclaration? { val target = psi.target as? PsiTarget ?: return null val navigationElement = target.navigationElement return PsiElement2Declaration.createFromPom(target, navigationElement) } }
platform/lang-impl/src/com/intellij/model/psi/impl/PsiElementDeclarationSearcher.kt
2201083201
package com.thedeadpixelsociety.ld34.components import com.badlogic.ashley.core.Component import com.badlogic.gdx.math.Vector2 data class TransformComponent(val position: Vector2 = Vector2(), val origin: Vector2 = Vector2(), var rotation: Float = 0f, val scale: Vector2 = Vector2(1f, 1f)) : Component
core/src/com/thedeadpixelsociety/ld34/components/TransformComponent.kt
2331080063
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE") package io.fluidsonic.json import java.io.* import kotlin.contracts.* import kotlin.internal.* public interface JsonWriter : Closeable, Flushable { public val depth: JsonDepth public val isErrored: Boolean public val isInValueIsolation: Boolean public val path: JsonPath public fun beginValueIsolation(): JsonDepth public fun endValueIsolation(depth: JsonDepth) public fun markAsErrored() public fun terminate() public fun writeBoolean(value: Boolean) public fun writeDouble(value: Double) public fun writeListEnd() public fun writeListStart() public fun writeLong(value: Long) public fun writeMapEnd() public fun writeMapStart() public fun writeNull() public fun writeString(value: String) public fun writeByte(value: Byte) { writeLong(value.toLong()) } public fun writeChar(value: Char) { writeString(value.toString()) } public fun writeFloat(value: Float) { writeDouble(value.toDouble()) } public fun writeInt(value: Int) { writeLong(value.toLong()) } public fun writeMapKey(value: String) { writeString(value) } public fun writeNumber(value: Number) { return when (value) { is Byte -> writeByte(value) is Float -> writeFloat(value) is Int -> writeInt(value) is Long -> writeLong(value) is Short -> writeShort(value) else -> writeDouble(value.toDouble()) } } public fun writeShort(value: Short) { writeLong(value.toLong()) } public fun writeValue(value: Any) { when (value) { is Array<*> -> writeList(value) is Boolean -> writeBoolean(value) is BooleanArray -> writeList(value) is Byte -> writeByte(value) is ByteArray -> writeList(value) is Char -> writeChar(value) is CharArray -> writeList(value) is DoubleArray -> writeList(value) is Float -> writeFloat(value) is FloatArray -> writeList(value) is Int -> writeInt(value) is IntArray -> writeList(value) is Iterable<*> -> writeList(value) is Long -> writeLong(value) is LongArray -> writeList(value) is Map<*, *> -> writeMap(value) is Sequence<*> -> writeList(value) is Short -> writeShort(value) is ShortArray -> writeList(value) is String -> writeString(value) is Number -> writeNumber(value) // after subclasses else -> throw JsonException.Serialization( message = "Cannot write JSON value of ${value::class}: $value", path = path ) } } public companion object { public fun build(destination: Writer): JsonWriter = StandardWriter(destination) } } public inline fun <Writer : JsonWriter> Writer.isolateValueWrite(crossinline write: Writer.() -> Unit) { val depth = beginValueIsolation() val value = write() endValueIsolation(depth = depth) return value } public inline fun <Writer : JsonWriter?, Result> Writer.use(withTermination: Boolean = true, block: (Writer) -> Result): Result { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } var exception: Throwable? = null try { return block(this) } catch (e: Throwable) { exception = e throw e } finally { val finalException = exception when { this == null -> Unit finalException == null -> if (withTermination) terminate() else close() else -> try { close() } catch (closeException: Throwable) { finalException.addSuppressed(closeException) } } } } public inline fun <Writer : JsonWriter, Result> Writer.withTermination(withTermination: Boolean = true, block: Writer.() -> Result): Result { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return if (withTermination) use { it.block() } else block() } public inline fun <Writer : JsonWriter, ReturnValue> Writer.withErrorChecking(block: Writer.() -> ReturnValue): ReturnValue { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } if (isErrored) { throw JsonException.Serialization( message = "Cannot operate on an errored JsonWriter", path = path ) } return try { block() } catch (e: Throwable) { markAsErrored() throw e } } public fun JsonWriter.writeBooleanOrNull(value: Boolean?) { writeOrNull(value, JsonWriter::writeBoolean) } public fun JsonWriter.writeByteOrNull(value: Byte?) { writeOrNull(value, JsonWriter::writeByte) } public fun JsonWriter.writeCharOrNull(value: Char?) { writeOrNull(value, JsonWriter::writeChar) } public fun JsonWriter.writeDoubleOrNull(value: Double?) { writeOrNull(value, JsonWriter::writeDouble) } public fun JsonWriter.writeFloatOrNull(value: Float?) { writeOrNull(value, JsonWriter::writeFloat) } public fun JsonWriter.writeIntOrNull(value: Int?) { writeOrNull(value, JsonWriter::writeInt) } public inline fun <Writer : JsonWriter> Writer.writeIntoList(crossinline writeContent: Writer.() -> Unit) { contract { callsInPlace(writeContent, InvocationKind.EXACTLY_ONCE) } isolateValueWrite { writeListStart() writeContent() writeListEnd() } } public inline fun <Writer : JsonWriter> Writer.writeIntoMap(crossinline writeContent: Writer.() -> Unit) { contract { callsInPlace(writeContent, InvocationKind.EXACTLY_ONCE) } isolateValueWrite { writeMapStart() writeContent() writeMapEnd() } } public fun JsonWriter.writeList(value: BooleanArray) { writeListByElement(value) { writeBoolean(it) } } public fun JsonWriter.writeList(value: ByteArray) { writeListByElement(value) { writeByte(it) } } public fun JsonWriter.writeList(value: CharArray) { writeListByElement(value) { writeChar(it) } } public fun JsonWriter.writeList(value: DoubleArray) { writeListByElement(value) { writeDouble(it) } } public fun JsonWriter.writeList(value: FloatArray) { writeListByElement(value) { writeFloat(it) } } public fun JsonWriter.writeList(value: IntArray) { writeListByElement(value) { writeInt(it) } } public fun JsonWriter.writeList(value: LongArray) { writeListByElement(value) { writeLong(it) } } public fun JsonWriter.writeList(value: ShortArray) { writeListByElement(value) { writeShort(it) } } public fun JsonWriter.writeList(value: Array<*>) { writeListByElement(value) { writeValueOrNull(it) } } public fun JsonWriter.writeList(value: Iterable<*>) { writeListByElement(value) { writeValueOrNull(it) } } public fun JsonWriter.writeList(value: Sequence<*>) { writeListByElement(value) { writeValueOrNull(it) } } public inline fun <Writer : JsonWriter> Writer.writeListByElement( value: BooleanArray, crossinline writeElement: Writer.(element: Boolean) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeIntoList { for (element in value) { isolateValueWrite { writeElement(element) } } } } public inline fun <Writer : JsonWriter> Writer.writeListByElement( value: ByteArray, crossinline writeElement: Writer.(element: Byte) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeIntoList { for (element in value) { isolateValueWrite { writeElement(element) } } } } public inline fun <Writer : JsonWriter> Writer.writeListByElement( value: CharArray, crossinline writeElement: Writer.(element: Char) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeIntoList { for (element in value) { isolateValueWrite { writeElement(element) } } } } public inline fun <Writer : JsonWriter> Writer.writeListByElement( value: DoubleArray, crossinline writeElement: Writer.(element: Double) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeIntoList { for (element in value) { isolateValueWrite { writeElement(element) } } } } public inline fun <Writer : JsonWriter> Writer.writeListByElement( value: FloatArray, crossinline writeElement: Writer.(element: Float) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeIntoList { for (element in value) { isolateValueWrite { writeElement(element) } } } } public inline fun <Writer : JsonWriter> Writer.writeListByElement( value: IntArray, crossinline writeElement: Writer.(element: Int) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeIntoList { for (element in value) { isolateValueWrite { writeElement(element) } } } } public inline fun <Writer : JsonWriter> Writer.writeListByElement( value: LongArray, crossinline writeElement: Writer.(element: Long) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeIntoList { for (element in value) { isolateValueWrite { writeElement(element) } } } } public inline fun <Writer : JsonWriter> Writer.writeListByElement( value: ShortArray, crossinline writeElement: Writer.(element: Short) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeIntoList { for (element in value) { isolateValueWrite { writeElement(element) } } } } public inline fun <Writer : JsonWriter, Element> Writer.writeListByElement( value: Array<Element>, crossinline writeElement: Writer.(element: Element) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeIntoList { for (element in value) { isolateValueWrite { writeElement(element) } } } } public inline fun <Writer : JsonWriter, Element> Writer.writeListByElement( value: Iterable<Element>, crossinline writeElement: Writer.(element: Element) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeIntoList { for (element in value) { isolateValueWrite { writeElement(element) } } } } public inline fun <Writer : JsonWriter, Element> Writer.writeListByElement( value: Sequence<Element>, crossinline writeElement: Writer.(element: Element) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeIntoList { for (element in value) { isolateValueWrite { writeElement(element) } } } } public fun JsonWriter.writeListOrNull(value: BooleanArray?) { writeOrNull(value, JsonWriter::writeList) } public fun JsonWriter.writeListOrNull(value: ByteArray?) { writeOrNull(value, JsonWriter::writeList) } public fun JsonWriter.writeListOrNull(value: CharArray?) { writeOrNull(value, JsonWriter::writeList) } public fun JsonWriter.writeListOrNull(value: DoubleArray?) { writeOrNull(value, JsonWriter::writeList) } public fun JsonWriter.writeListOrNull(value: FloatArray?) { writeOrNull(value, JsonWriter::writeList) } public fun JsonWriter.writeListOrNull(value: IntArray?) { writeOrNull(value, JsonWriter::writeList) } public fun JsonWriter.writeListOrNull(value: LongArray?) { writeOrNull(value, JsonWriter::writeList) } public fun JsonWriter.writeListOrNull(value: ShortArray?) { writeOrNull(value, JsonWriter::writeList) } public fun JsonWriter.writeListOrNull(value: Array<*>?) { writeOrNull(value, JsonWriter::writeList) } public fun JsonWriter.writeListOrNull(value: Iterable<*>?) { writeOrNull(value, JsonWriter::writeList) } public fun JsonWriter.writeListOrNull(value: Sequence<*>?) { writeOrNull(value, JsonWriter::writeList) } public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement( value: BooleanArray?, crossinline writeElement: Writer.(element: Boolean) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeOrNull(value) { writeListByElement(it, writeElement) } } public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement( value: ByteArray?, crossinline writeElement: Writer.(element: Byte) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeOrNull(value) { writeListByElement(it, writeElement) } } public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement( value: CharArray?, crossinline writeElement: Writer.(element: Char) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeOrNull(value) { writeListByElement(it, writeElement) } } public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement( value: DoubleArray?, crossinline writeElement: Writer.(element: Double) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeOrNull(value) { writeListByElement(it, writeElement) } } public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement( value: FloatArray?, crossinline writeElement: Writer.(element: Float) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeOrNull(value) { writeListByElement(it, writeElement) } } public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement( value: IntArray?, crossinline writeElement: Writer.(element: Int) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeOrNull(value) { writeListByElement(it, writeElement) } } public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement( value: LongArray?, crossinline writeElement: Writer.(element: Long) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeOrNull(value) { writeListByElement(it, writeElement) } } public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement( value: ShortArray?, crossinline writeElement: Writer.(element: Short) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeOrNull(value) { writeListByElement(it, writeElement) } } public inline fun <Writer : JsonWriter, Element> Writer.writeListOrNullByElement( value: Array<Element>?, crossinline writeElement: Writer.(element: Element) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeOrNull(value) { writeListByElement(it, writeElement) } } public inline fun <Writer : JsonWriter, Element> Writer.writeListOrNullByElement( value: Iterable<Element>?, crossinline writeElement: Writer.(element: Element) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeOrNull(value) { writeListByElement(it, writeElement) } } public inline fun <Writer : JsonWriter, Element> Writer.writeListOrNullByElement( value: Sequence<Element>?, crossinline writeElement: Writer.(element: Element) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeOrNull(value) { writeListByElement(it, writeElement) } } public fun JsonWriter.writeLongOrNull(value: Long?) { writeOrNull(value, JsonWriter::writeLong) } public fun JsonWriter.writeMap(value: Map<*, *>) { writeMapByElementValue(value) { writeValueOrNull(it) } } public inline fun <Writer : JsonWriter, ElementKey, ElementValue> Writer.writeMapByElement( value: Map<ElementKey, ElementValue>, crossinline writeElement: Writer.(key: ElementKey, value: ElementValue) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeIntoMap { for ((elementKey, elementValue) in value) writeElement(elementKey, elementValue) } } public inline fun <Writer : JsonWriter, ElementValue> Writer.writeMapByElementValue( value: Map<*, ElementValue>, crossinline writeElementValue: Writer.(value: ElementValue) -> Unit, ) { contract { callsInPlace(writeElementValue, InvocationKind.UNKNOWN) } writeMapByElement(value) { elementKey, elementValue -> writeValueOrNull(elementKey) isolateValueWrite { writeElementValue(elementValue) } } } public fun JsonWriter.writeMapOrNull(value: Map<*, *>?) { writeOrNull(value, JsonWriter::writeMap) } public inline fun <Writer : JsonWriter, ElementKey, ElementValue> Writer.writeMapOrNullByElement( value: Map<ElementKey, ElementValue>?, crossinline writeElement: Writer.(key: ElementKey, value: ElementValue) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } writeOrNull(value) { writeMapByElement(it, writeElement) } } public inline fun <Writer : JsonWriter, ElementValue> Writer.writeMapOrNullByElementValue( value: Map<*, ElementValue>?, crossinline writeElementValue: Writer.(value: ElementValue) -> Unit, ) { contract { callsInPlace(writeElementValue, InvocationKind.UNKNOWN) } writeOrNull(value) { writeMapByElementValue(it, writeElementValue) } } public fun JsonWriter.writeMapElement(key: String, boolean: Boolean) { writeMapKey(key) writeBoolean(boolean) } public fun JsonWriter.writeMapElement(key: String, boolean: Boolean?, skipIfNull: Boolean = false) { if (boolean != null) writeMapElement(key, boolean) else if (!skipIfNull) writeMapNullElement(key) else Unit } public fun JsonWriter.writeMapElement(key: String, byte: Byte) { writeMapKey(key) writeByte(byte) } public fun JsonWriter.writeMapElement(key: String, byte: Byte?, skipIfNull: Boolean = false) { if (byte != null) writeMapElement(key, byte) else if (!skipIfNull) writeMapNullElement(key) else Unit } public fun JsonWriter.writeMapElement(key: String, char: Char) { writeMapKey(key) writeChar(char) } public fun JsonWriter.writeMapElement(key: String, char: Char?, skipIfNull: Boolean = false) { if (char != null) writeMapElement(key, char) else if (!skipIfNull) writeMapNullElement(key) else Unit } public fun JsonWriter.writeMapElement(key: String, double: Double) { writeMapKey(key) writeDouble(double) } public fun JsonWriter.writeMapElement(key: String, double: Double?, skipIfNull: Boolean = false) { if (double != null) writeMapElement(key, double) else if (!skipIfNull) writeMapNullElement(key) else Unit } public fun JsonWriter.writeMapElement(key: String, float: Float) { writeMapKey(key) writeFloat(float) } public fun JsonWriter.writeMapElement(key: String, float: Float?, skipIfNull: Boolean = false) { if (float != null) writeMapElement(key, float) else if (!skipIfNull) writeMapNullElement(key) else Unit } public fun JsonWriter.writeMapElement(key: String, int: Int) { writeMapKey(key) writeInt(int) } public fun JsonWriter.writeMapElement(key: String, int: Int?, skipIfNull: Boolean = false) { if (int != null) writeMapElement(key, int) else if (!skipIfNull) writeMapNullElement(key) else Unit } @Deprecated( message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)") ) @LowPriorityInOverloadResolution public fun JsonWriter.writeMapElement(key: String, list: Array<*>?, skipIfNull: Boolean = false) { writeMapElement(key, list = list, skipIfNull = skipIfNull) { writeValueOrNull(it) } } public inline fun <Writer : JsonWriter, Element> Writer.writeMapElement( key: String, list: Array<Element>?, skipIfNull: Boolean = false, crossinline writeElement: Writer.(element: Element) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } if (list != null) { writeMapKey(key) writeListByElement(list, writeElement) } else if (!skipIfNull) writeMapNullElement(key) } @Deprecated( message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)") ) @LowPriorityInOverloadResolution public fun JsonWriter.writeMapElement(key: String, list: BooleanArray?, skipIfNull: Boolean = false) { if (list != null) { writeMapKey(key) writeList(list) } else if (!skipIfNull) writeMapNullElement(key) else Unit } @Deprecated( message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)") ) @LowPriorityInOverloadResolution public fun JsonWriter.writeMapElement(key: String, list: ByteArray?, skipIfNull: Boolean = false) { if (list != null) { writeMapKey(key) writeList(list) } else if (!skipIfNull) writeMapNullElement(key) else Unit } @Deprecated( message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)") ) @LowPriorityInOverloadResolution public fun JsonWriter.writeMapElement(key: String, list: CharArray?, skipIfNull: Boolean = false) { if (list != null) { writeMapKey(key) writeList(list) } else if (!skipIfNull) writeMapNullElement(key) else Unit } @Deprecated( message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)") ) @LowPriorityInOverloadResolution public fun JsonWriter.writeMapElement(key: String, list: DoubleArray?, skipIfNull: Boolean = false) { if (list != null) { writeMapKey(key) writeList(list) } else if (!skipIfNull) writeMapNullElement(key) else Unit } @Deprecated( message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)") ) @LowPriorityInOverloadResolution public fun JsonWriter.writeMapElement(key: String, list: FloatArray?, skipIfNull: Boolean = false) { if (list != null) { writeMapKey(key) writeList(list) } else if (!skipIfNull) writeMapNullElement(key) else Unit } @Deprecated( message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)") ) @LowPriorityInOverloadResolution public fun JsonWriter.writeMapElement(key: String, list: IntArray?, skipIfNull: Boolean = false) { if (list != null) { writeMapKey(key) writeList(list) } else if (!skipIfNull) writeMapNullElement(key) else Unit } @Deprecated( message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)") ) @LowPriorityInOverloadResolution public fun JsonWriter.writeMapElement(key: String, list: Iterable<*>?, skipIfNull: Boolean = false) { writeMapElement(key, list = list, skipIfNull = skipIfNull) { writeValueOrNull(it) } } public inline fun <Writer : JsonWriter, Element> Writer.writeMapElement( key: String, list: Iterable<Element>?, skipIfNull: Boolean = false, crossinline writeElement: Writer.(element: Element) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } if (list != null) { writeMapKey(key) writeListByElement(list, writeElement) } else if (!skipIfNull) writeMapNullElement(key) } @Deprecated( message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)") ) @LowPriorityInOverloadResolution public fun JsonWriter.writeMapElement(key: String, list: LongArray?, skipIfNull: Boolean = false) { if (list != null) { writeMapKey(key) writeList(list) } else if (!skipIfNull) writeMapNullElement(key) else Unit } @Deprecated( message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)") ) @LowPriorityInOverloadResolution public fun JsonWriter.writeMapElement(key: String, list: Sequence<*>?, skipIfNull: Boolean = false) { writeMapElement(key, list = list, skipIfNull = skipIfNull) { writeValueOrNull(it) } } public inline fun <Writer : JsonWriter, Element> Writer.writeMapElement( key: String, list: Sequence<Element>?, skipIfNull: Boolean = false, crossinline writeElement: Writer.(element: Element) -> Unit, ) { contract { callsInPlace(writeElement, InvocationKind.UNKNOWN) } if (list != null) { writeMapKey(key) writeListByElement(list, writeElement) } else if (!skipIfNull) writeMapNullElement(key) } @Deprecated( message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)") ) @LowPriorityInOverloadResolution public fun JsonWriter.writeMapElement(key: String, list: ShortArray?, skipIfNull: Boolean = false) { if (list != null) { writeMapKey(key) writeList(list) } else if (!skipIfNull) writeMapNullElement(key) else Unit } public fun JsonWriter.writeMapElement(key: String, long: Long) { writeMapKey(key) writeLong(long) } public fun JsonWriter.writeMapElement(key: String, long: Long?, skipIfNull: Boolean = false) { if (long != null) writeMapElement(key, long) else if (!skipIfNull) writeMapNullElement(key) else Unit } @Deprecated( message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith(expression = "writeMapElement(key, value = map, skipIfNull = skipIfNull)") ) @LowPriorityInOverloadResolution public fun JsonWriter.writeMapElement(key: String, map: Map<*, *>?, skipIfNull: Boolean = false) { writeMapElement(key, map = map, skipIfNull = skipIfNull) { writeValueOrNull(it) } } public inline fun <Writer : JsonWriter, Child> Writer.writeMapElement( key: String, map: Map<*, Child>?, skipIfNull: Boolean = false, crossinline writeChild: Writer.(value: Child) -> Unit, ) { if (map != null) { writeMapKey(key) writeMapByElementValue(map, writeChild) } else if (!skipIfNull) writeMapNullElement(key) else Unit } public fun JsonWriter.writeMapElement(key: String, number: Number?, skipIfNull: Boolean = false) { if (number != null) { writeMapKey(key) writeNumber(number) } else if (!skipIfNull) writeMapNullElement(key) else Unit } public fun JsonWriter.writeMapElement(key: String, short: Short) { writeMapKey(key) writeShort(short) } public fun JsonWriter.writeMapElement(key: String, short: Short?, skipIfNull: Boolean = false) { if (short != null) writeMapElement(key, short) else if (!skipIfNull) writeMapNullElement(key) else Unit } public fun JsonWriter.writeMapElement(key: String, string: String?, skipIfNull: Boolean = false) { if (string != null) { writeMapKey(key) writeString(string) } else if (!skipIfNull) writeMapNullElement(key) else Unit } public fun JsonWriter.writeMapElement(key: String, value: Any?, skipIfNull: Boolean = false) { writeMapElement(key, value, skipIfNull) { writeValue(it) } } public inline fun <Writer : JsonWriter, Value : Any> Writer.writeMapElement( key: String, value: Value?, skipIfNull: Boolean = false, crossinline writeCustomValue: Writer.(value: Value) -> Unit, ) { contract { callsInPlace(writeCustomValue, InvocationKind.AT_MOST_ONCE) } if (value != null) { writeMapKey(key) isolateValueWrite { writeCustomValue(value) } } else if (!skipIfNull) writeMapNullElement(key) } public inline fun <Writer : JsonWriter> Writer.writeMapElement( key: String, crossinline writeValue: Writer.() -> Unit, ) { contract { callsInPlace(writeValue, InvocationKind.EXACTLY_ONCE) } writeMapKey(key) isolateValueWrite { writeValue() } } public fun JsonWriter.writeMapNullElement(key: String) { writeMapKey(key) writeNull() } public fun JsonWriter.writeNumberOrNull(value: Number?) { writeOrNull(value, JsonWriter::writeNumber) } public inline fun <Writer : JsonWriter, Value : Any> Writer.writeOrNull(value: Value?, crossinline write: Writer.(value: Value) -> Unit) { contract { callsInPlace(write, InvocationKind.AT_MOST_ONCE) } if (value != null) isolateValueWrite { write(value) } else writeNull() } public fun JsonWriter.writeShortOrNull(value: Short?) { writeOrNull(value, JsonWriter::writeShort) } public fun JsonWriter.writeStringOrNull(value: String?) { writeOrNull(value, JsonWriter::writeString) } public fun JsonWriter.writeValueOrNull(value: Any?) { writeOrNull(value, JsonWriter::writeValue) }
basic/sources-jvm/JsonWriter.kt
4202668098
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.google.common.util.concurrent.MoreExecutors import com.netflix.spinnaker.orca.DefaultStageResolver import com.netflix.spinnaker.orca.TaskResolver import com.netflix.spinnaker.orca.api.pipeline.CancellableStage import com.netflix.spinnaker.orca.api.pipeline.graph.StageDefinitionBuilder import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.CANCELED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.api.simplestage.SimpleStage import com.netflix.spinnaker.orca.api.test.pipeline import com.netflix.spinnaker.orca.api.test.stage import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.StageNavigator import com.netflix.spinnaker.orca.q.CancelStage import com.netflix.spinnaker.orca.q.singleTaskStage import com.netflix.spinnaker.q.Queue import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.never import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyZeroInteractions import com.nhaarman.mockito_kotlin.whenever import org.jetbrains.spek.api.dsl.context import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek object CancelStageHandlerTest : SubjectSpek<CancelStageHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val executor = MoreExecutors.directExecutor() val taskResolver: TaskResolver = TaskResolver(emptyList()) val stageNavigator: StageNavigator = mock() val cancellableStage: CancelableStageDefinitionBuilder = mock() val stageResolver = DefaultStageResolver(listOf(singleTaskStage, cancellableStage), emptyList<SimpleStage<Object>>()) subject(GROUP) { CancelStageHandler( queue, repository, DefaultStageDefinitionBuilderFactory(stageResolver), stageNavigator, executor, taskResolver ) } fun resetMocks() = reset(queue, repository, cancellableStage) describe("cancelling a stage") { val pipeline = pipeline { application = "whatever" stage { type = "cancellable" refId = "1" status = SUCCEEDED } stage { type = "cancellable" refId = "2a" requisiteStageRefIds = listOf("1") status = CANCELED } stage { type = singleTaskStage.type refId = "2b" requisiteStageRefIds = listOf("1") status = CANCELED } stage { type = "cancellable" refId = "2c" requisiteStageRefIds = listOf("1") status = TERMINAL } stage { type = "cancellable" refId = "3" requisiteStageRefIds = listOf("2a", "2b", "2c") status = NOT_STARTED } } mapOf( "2a" to "a cancellable stage that was canceled", "2c" to "a cancellable stage that failed" ).forEach { refId, description -> context(description) { val message = CancelStage(PIPELINE, pipeline.id, pipeline.application, pipeline.stageByRef(refId).id) beforeGroup { whenever(cancellableStage.type) doReturn "cancellable" whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("invokes the cancel routine for the stage") { verify(cancellableStage).cancel(pipeline.stageByRef(refId)) } it("should not push any messages to the queue") { verifyZeroInteractions(queue) } } } mapOf( "1" to "a cancellable stage that completed already", "2b" to "a running non-cancellable stage", "3" to "a cancellable stage that did not start yet" ).forEach { refId, description -> context(description) { val message = CancelStage(PIPELINE, pipeline.id, pipeline.application, pipeline.stageByRef(refId).id) beforeGroup { whenever(cancellableStage.type) doReturn "cancellable" whenever(repository.retrieve(pipeline.type, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("does not run any cancel routine") { verify(cancellableStage, never()).cancel(any()) } it("should not push any messages to the queue") { verifyZeroInteractions(queue) } } } } }) interface CancelableStageDefinitionBuilder : StageDefinitionBuilder, CancellableStage
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/CancelStageHandlerTest.kt
8882891
package course.examples.ui.mapview import android.os.Bundle import androidx.fragment.app.FragmentActivity import com.google.android.gms.maps.* import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions class GoogleMapActivity : FragmentActivity(), OnMapReadyCallback { public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main) // The GoogleMap instance underlying the GoogleMapFragment defined in main.xml val map = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment map.getMapAsync(this) } override fun onMapReady(map: GoogleMap?) { if (map != null) { // Set the map position map.moveCamera( CameraUpdateFactory.newLatLngZoom( LatLng( 29.0, -88.0 ), 3.0f ) ) // Add a marker on Washington, DC, USA map.addMarker( MarkerOptions().position( LatLng(38.8895, -77.0352) ).title( getString(R.string.in_washington_string) ) ) // Add a marker on Mexico City, Mexico map.addMarker( MarkerOptions().position( LatLng(19.13, -99.4) ).title( getString(R.string.in_mexico_string) ) ) } } }
ExamplesKotlin/UIGoogleMaps/app/src/main/java/course/examples/ui/mapview/GoogleMapActivity.kt
368894584
// 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.xdebugger.impl.ui import com.intellij.debugger.ui.DebuggerContentInfo import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.ui.layout.LayoutAttractionPolicy import com.intellij.execution.ui.layout.PlaceInGrid import com.intellij.icons.AllIcons import com.intellij.ide.actions.TabListAction import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.ui.PersistentThreeComponentSplitter import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ToolWindowType import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.openapi.wm.ex.ToolWindowManagerListener import com.intellij.ui.JBColor import com.intellij.ui.content.ContentManagerEvent import com.intellij.ui.content.ContentManagerListener import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.xdebugger.* import com.intellij.xdebugger.impl.XDebugSessionImpl import com.intellij.xdebugger.impl.actions.XDebuggerActions import com.intellij.xdebugger.impl.frame.* import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree import com.intellij.xdebugger.impl.ui.tree.nodes.XDebuggerTreeNode import java.awt.Component import java.awt.Container import javax.swing.Icon import javax.swing.LayoutFocusTraversalPolicy import javax.swing.event.AncestorEvent import javax.swing.event.AncestorListener class XDebugSessionTab2( session: XDebugSessionImpl, icon: Icon?, environment: ExecutionEnvironment? ) : XDebugSessionTab(session, icon, environment, false) { companion object { private const val threadsIsVisibleKey = "threadsIsVisibleKey" private const val debuggerContentId = "DebuggerView" } private val project = session.project private var threadsIsVisible get() = PropertiesComponent.getInstance(project).getBoolean(threadsIsVisibleKey, true) set(value) = PropertiesComponent.getInstance(project).setValue(threadsIsVisibleKey, value, true) private val lifetime = Disposer.newDisposable() private val splitter = PersistentThreeComponentSplitter(false, true, "DebuggerViewTab", lifetime, project, 0.35f, 0.3f) private val xThreadsFramesView = XThreadsFramesView(myProject) private var variables: XVariablesView? = null private val toolWindow get() = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.DEBUG) private val focusTraversalPolicy = MyFocusTraversalPolicy() init { // value from com.intellij.execution.ui.layout.impl.GridImpl splitter.setMinSize(48) splitter.isFocusCycleRoot = true splitter.isFocusTraversalPolicyProvider = true splitter.focusTraversalPolicy = focusTraversalPolicy session.addSessionListener(object : XDebugSessionListener { override fun sessionStopped() { UIUtil.invokeLaterIfNeeded { splitter.saveProportions() Disposer.dispose(lifetime) } } }) project.messageBus.connect(lifetime).subscribe(XDebuggerManager.TOPIC, object : XDebuggerManagerListener { override fun processStarted(debugProcess: XDebugProcess) { UIUtil.invokeLaterIfNeeded { if (debugProcess.session != null && debugProcess.session != session) { splitter.saveProportions() } } } override fun currentSessionChanged(previousSession: XDebugSession?, currentSession: XDebugSession?) { UIUtil.invokeLaterIfNeeded { if (previousSession == session) { splitter.saveProportions() xThreadsFramesView.saveUiState() } else if (currentSession == session) splitter.restoreProportions() } } override fun processStopped(debugProcess: XDebugProcess) { UIUtil.invokeLaterIfNeeded { splitter.saveProportions() xThreadsFramesView.saveUiState() if (debugProcess.session == session) Disposer.dispose(lifetime) } } }) val ancestorListener = object : AncestorListener { override fun ancestorAdded(event: AncestorEvent?) { if (XDebuggerManager.getInstance(project).currentSession == session) { splitter.restoreProportions() } } override fun ancestorRemoved(event: AncestorEvent?) { if (XDebuggerManager.getInstance(project).currentSession == session) { splitter.saveProportions() xThreadsFramesView.saveUiState() } } override fun ancestorMoved(event: AncestorEvent?) { } } toolWindow?.component?.addAncestorListener(ancestorListener) Disposer.register(lifetime, Disposable { toolWindow?.component?.removeAncestorListener(ancestorListener) }) var oldToolWindowType: ToolWindowType? = null project.messageBus.connect(lifetime).subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener { override fun stateChanged(toolWindowManager: ToolWindowManager) { if (oldToolWindowType == toolWindow?.type) return setHeaderState() oldToolWindowType = toolWindow?.type } }) } override fun getWatchesContentId() = debuggerContentId override fun getFramesContentId() = debuggerContentId override fun addVariablesAndWatches(session: XDebugSessionImpl) { val variablesView: XVariablesView? val watchesView: XVariablesView? val layoutDisposable = Disposer.newDisposable(ui.contentManager, "debugger layout disposable") if (isWatchesInVariables) { variablesView = XWatchesViewImpl2(session, true, true, layoutDisposable) registerView(DebuggerContentInfo.VARIABLES_CONTENT, variablesView) variables = variablesView watchesView = null myWatchesView = variablesView } else { variablesView = XVariablesView(session) registerView(DebuggerContentInfo.VARIABLES_CONTENT, variablesView) variables = variablesView watchesView = XWatchesViewImpl2(session, false, true, layoutDisposable) registerView(DebuggerContentInfo.WATCHES_CONTENT, watchesView) myWatchesView = watchesView } splitter.apply { innerComponent = variablesView.panel lastComponent = watchesView?.panel } UIUtil.removeScrollBorder(splitter) splitter.revalidate() splitter.repaint() updateTraversalPolicy() } private fun updateTraversalPolicy() { focusTraversalPolicy.components = getComponents().asSequence().toList() } override fun initDebuggerTab(session: XDebugSessionImpl) { val framesView = xThreadsFramesView registerView(DebuggerContentInfo.FRAME_CONTENT, framesView) framesView.setThreadsVisible(threadsIsVisible) splitter.firstComponent = xThreadsFramesView.mainPanel addVariablesAndWatches(session) val name = debuggerContentId val content = myUi.createContent(name, splitter, XDebuggerBundle.message("xdebugger.debugger.tab.title"), AllIcons.Toolwindows.ToolWindowDebugger, framesView.defaultFocusedComponent).apply { isCloseable = false } myUi.addContent(content, 0, PlaceInGrid.left, false) ui.defaults.initContentAttraction(debuggerContentId, XDebuggerUIConstants.LAYOUT_VIEW_BREAKPOINT_CONDITION, LayoutAttractionPolicy.FocusOnce()) toolWindow?.let { val contentManager = it.contentManager val listener = object : ContentManagerListener { override fun contentAdded(event: ContentManagerEvent) { setHeaderState() } override fun contentRemoved(event: ContentManagerEvent) { setHeaderState() } } contentManager.addContentManagerListener(listener) Disposer.register(lifetime, Disposable { contentManager.removeContentManagerListener(listener) }) } setHeaderState() } private fun getComponents(): Iterator<Component> { return iterator { if (threadsIsVisible) yield(xThreadsFramesView.threads) yield(xThreadsFramesView.frames) val vars = variables ?: return@iterator yield(vars.defaultFocusedComponent) if (!isWatchesInVariables) yield(myWatchesView.defaultFocusedComponent) } } private fun setHeaderState() { toolWindow?.let { toolWindow -> if (toolWindow !is ToolWindowEx) return@let val singleContent = toolWindow.contentManager.contents.singleOrNull() val headerVisible = toolWindow.isHeaderVisible val topRightToolbar = DefaultActionGroup().apply { if (headerVisible) return@apply addAll(toolWindow.decorator.headerToolbar.actions.filter { it != null && it !is TabListAction }) } myUi.options.setTopRightToolbar(topRightToolbar, ActionPlaces.DEBUGGER_TOOLBAR) val topMiddleToolbar = DefaultActionGroup().apply { if (singleContent == null || headerVisible) return@apply add(object : AnAction(XDebuggerBundle.message("session.tab.close.debug.session"), null, AllIcons.Actions.Close) { override fun actionPerformed(e: AnActionEvent) { toolWindow.contentManager.removeContent(singleContent, true) } }) addSeparator() } myUi.options.setTopMiddleToolbar(topMiddleToolbar, ActionPlaces.DEBUGGER_TOOLBAR) toolWindow.decorator.isHeaderVisible = headerVisible if (toolWindow.decorator.isHeaderVisible) { toolWindow.component.border = null toolWindow.component.invalidate() toolWindow.component.repaint() } else if (toolWindow.component.border == null) { UIUtil.addBorder(toolWindow.component, JBUI.Borders.customLine(JBColor.border(), 1, 0, 0, 0)) } } } private val ToolWindowEx.isHeaderVisible get() = (type != ToolWindowType.DOCKED) || contentManager.contents.singleOrNull() == null override fun registerAdditionalActions(leftToolbar: DefaultActionGroup, topLeftToolbar: DefaultActionGroup, settings: DefaultActionGroup) { leftToolbar.apply { val constraints = Constraints(Anchor.BEFORE, XDebuggerActions.VIEW_BREAKPOINTS) add(object : ToggleAction() { override fun setSelected(e: AnActionEvent, state: Boolean) { if (threadsIsVisible != state) { threadsIsVisible = state updateTraversalPolicy() } xThreadsFramesView.setThreadsVisible(state) Toggleable.setSelected(e.presentation, state) } override fun isSelected(e: AnActionEvent) = threadsIsVisible override fun update(e: AnActionEvent) { e.presentation.icon = AllIcons.Actions.SplitVertically if (threadsIsVisible) { e.presentation.text = XDebuggerBundle.message("session.tab.hide.threads.view") } else { e.presentation.text = XDebuggerBundle.message("session.tab.show.threads.view") } setSelected(e, threadsIsVisible) } }, constraints) add(ActionManager.getInstance().getAction(XDebuggerActions.FRAMES_TOP_TOOLBAR_GROUP), constraints) add(Separator.getInstance(), constraints) } super.registerAdditionalActions(leftToolbar, settings, topLeftToolbar) } override fun dispose() { Disposer.dispose(lifetime) super.dispose() } class MyFocusTraversalPolicy : LayoutFocusTraversalPolicy() { var components: List<Component> = listOf() override fun getLastComponent(aContainer: Container?): Component { if (components.isNotEmpty()) return components.last().prepare() return super.getLastComponent(aContainer) } override fun getFirstComponent(aContainer: Container?): Component { if (components.isNotEmpty()) return components.first().prepare() return super.getFirstComponent(aContainer) } override fun getComponentAfter(aContainer: Container?, aComponent: Component?): Component { if (aComponent == null) return super.getComponentAfter(aContainer, aComponent) val index = components.indexOf(aComponent) if (index < 0 || index > components.lastIndex) return super.getComponentAfter(aContainer, aComponent) for (i in components.indices) { val component = components[(index + i + 1) % components.size] if (isEmpty(component)) continue return component.prepare() } return components[index + 1].prepare() } override fun getComponentBefore(aContainer: Container?, aComponent: Component?): Component { if (aComponent == null) return super.getComponentBefore(aContainer, aComponent) val index = components.indexOf(aComponent) if (index < 0 || index > components.lastIndex) return super.getComponentBefore(aContainer, aComponent) for (i in components.indices) { val component = components[(components.size + index - i - 1) % components.size] if (isEmpty(component)) continue return component.prepare() } return components[index - 1].prepare() } private fun Component.prepare(): Component { if (this is XDebuggerTree && this.selectionCount == 0){ val child = root.children.firstOrNull() as? XDebuggerTreeNode ?: return this selectionPath = child.path } return this } private fun isEmpty(component: Component): Boolean { return when (component) { is XDebuggerThreadsList -> component.isEmpty is XDebuggerFramesList -> component.isEmpty is XDebuggerTree -> component.isEmpty else -> false; } } } }
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab2.kt
2295075912
package json.representation import io.fluidsonic.json.* @Json( representation = Json.Representation.singleValue ) class SingleValue(val value: String)
annotation-processor/test-cases/1/input/json/representation/SingleValue.kt
75425408
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.recorder.compile import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.cl.PluginClassLoader import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.DefaultPluginDescriptor import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.testGuiFramework.recorder.GuiRecorderManager import com.intellij.testGuiFramework.recorder.ui.Notifier import com.intellij.util.download.DownloadableFileService import com.intellij.util.lang.UrlClassLoader import java.io.BufferedReader import java.io.File import java.io.FileNotFoundException import java.io.InputStreamReader import java.nio.file.Path import java.util.* import java.util.concurrent.TimeUnit import java.util.stream.Collectors private val LOG by lazy { Logger.getInstance(LocalCompiler::class.java) } private const val TEST_CLASS_NAME = "CurrentTest" /** * @author Sergey Karashevich */ internal class LocalCompiler { private var codeHash: Int? = null private val helloKtText = "fun main(args: Array<String>) { \n println(\"Hello, World!\") \n }" private val kotlinCompilerJarUrl = "http://central.maven.org/maven2/org/jetbrains/kotlin/kotlin-compiler/1.0.6/kotlin-compiler-1.0.6.jar" private val kotlinCompilerJarName = "kotlin-compiler-1.0.6.jar" private val tempDir by lazy { FileUtil.createTempDirectory("kotlin-compiler-tmp", null, true) } private val helloKt by lazy { createTempFile(helloKtText) } private var tempFile: File? = null private fun createTempFile(content: String, fileName: String = TEST_CLASS_NAME, extension: String = ".kt"): File { val tempFile = FileUtil.createTempFile(fileName, extension, true) FileUtil.writeToFile(tempFile, content, false) this.tempFile = tempFile return tempFile } fun compileAndRunOnPooledThread(code: String, classpath: List<String>) { val taskFuture = ApplicationManager.getApplication().executeOnPooledThread( { try { if (codeHash == null || codeHash != code.hashCode()) { compile(code, classpath) codeHash = code.hashCode() } run() } catch (ce: CompilationException) { LOG.error(ce.message) } }) GuiRecorderManager.currentTask = taskFuture } //alternative way to run compiled code with pluginClassloader built especially for this file private fun run() { Notifier.updateStatus("${Notifier.LONG_OPERATION_PREFIX}Script running...") var classLoadersArray: Array<ClassLoader> try { //run testGuiTest gradle configuration ApplicationManager::class.java.classLoader.loadClass("com.intellij.testGuiFramework.impl.GuiTestCase") classLoadersArray = arrayOf(ApplicationManager::class.java.classLoader) } catch (cfe: ClassNotFoundException) { classLoadersArray = arrayOf(ApplicationManager::class.java.classLoader, this.javaClass.classLoader) } val pluginClassLoader = PluginClassLoader(UrlClassLoader.build().files(listOf(tempDir.toPath())).useCache(), classLoadersArray, DefaultPluginDescriptor("SubGuiScriptRecorder"), null as Path?, PluginManagerCore::class.java.classLoader, null, null, null) val currentTest = pluginClassLoader.loadClass(TEST_CLASS_NAME) ?: throw Exception("Unable to load by pluginClassLoader $TEST_CLASS_NAME.class file") val testCase = currentTest.getDeclaredConstructor().newInstance() val testMethod = currentTest.getMethod(ScriptWrapper.TEST_METHOD_NAME) GuiRecorderManager.state = GuiRecorderManager.States.RUNNING try { testMethod.invoke(testCase) Notifier.updateStatus("Script stopped") GuiRecorderManager.state = GuiRecorderManager.States.IDLE } catch (throwable: Throwable) { GuiRecorderManager.state = GuiRecorderManager.States.RUNNING_ERROR Notifier.updateStatus("Running error, please see idea.log") throw throwable } } private fun compile(code: String, classpath: List<String>): Boolean = compile(createTempFile(code), classpath) private fun compile(fileKt: File? = null, classpath: List<String>): Boolean { val scriptKt = fileKt ?: helloKt val kotlinCompilerJar = getKotlinCompilerJar() val libDirLocation = getApplicationLibDir().parentFile Notifier.updateStatus("${Notifier.LONG_OPERATION_PREFIX}Compiling...") GuiRecorderManager.state = GuiRecorderManager.States.COMPILING val compilationProcessBuilder = if (SystemInfo.isWindows) getProcessBuilderForWin(kotlinCompilerJar, libDirLocation, classpath, scriptKt) else ProcessBuilder("java", "-jar", kotlinCompilerJar.path, "-kotlin-home", libDirLocation.path, "-d", tempDir.path, "-cp", buildClasspath(classpath), scriptKt.path) val process = compilationProcessBuilder.start() val wait = process.waitFor(120, TimeUnit.MINUTES) assert(wait) if (process.exitValue() == 1) { LOG.error(BufferedReader(InputStreamReader(process.errorStream)).lines().collect(Collectors.joining("\n"))) Notifier.updateStatus("Compilation error (see idea.log)") GuiRecorderManager.state = GuiRecorderManager.States.COMPILATION_ERROR throw CompilationException() } else { Notifier.updateStatus("Compilation is done") GuiRecorderManager.state = GuiRecorderManager.States.COMPILATION_DONE } return wait } private fun getKotlinCompilerJar(): File { val kotlinCompilerDir = getPluginKotlincDir() if (!isKotlinCompilerDir(kotlinCompilerDir)) downloadKotlinCompilerJar(kotlinCompilerDir.path) return kotlinCompilerDir.listFiles().firstOrNull { file -> file.name.contains("kotlin-compiler") } ?: throw FileNotFoundException("Unable to find kotlin-compiler*.jar in ${kotlinCompilerDir.path} directory") } private fun getApplicationLibDir(): File { return File(PathManager.getLibPath()) } private fun getPluginKotlincDir(): File { val tempDirFile = File(PathManager.getTempPath()) FileUtil.ensureExists(tempDirFile) return tempDirFile } private fun isKotlinCompilerDir(dir: File): Boolean = dir.listFiles().any { file -> file.name.contains("kotlin-compiler") } private fun downloadKotlinCompilerJar(destDirPath: String?): File { Notifier.updateStatus("${Notifier.LONG_OPERATION_PREFIX}Downloading kotlin-compiler.jar...") val downloader = DownloadableFileService.getInstance() val description = downloader.createFileDescription(kotlinCompilerJarUrl, kotlinCompilerJarName) ApplicationManager.getApplication().invokeAndWait( { downloader.createDownloader(Arrays.asList(description), kotlinCompilerJarName).downloadFilesWithProgress(destDirPath, null, null) }) Notifier.updateStatus("kotlin-compiler.jar downloaded successfully") return File(destDirPath + File.separator + kotlinCompilerJarName) } private class CompilationException : Exception() private fun buildClasspath(cp: List<String>): String { if (SystemInfo.isWindows) { val ideaJar = "idea.jar" val ideaJarPath = cp.find { pathStr -> pathStr.endsWith("${File.separator}$ideaJar") } val ideaLibPath = ideaJarPath!!.substring(startIndex = 0, endIndex = ideaJarPath.length - ideaJar.length - File.separator.length) return cp.filterNot { pathStr -> pathStr.startsWith(ideaLibPath) }.plus(ideaLibPath).joinToString(";") } else return cp.joinToString(":") } private fun getProcessBuilderForWin(kotlinCompilerJar: File, libDirLocation: File, classpath: List<String>, scriptKt: File): ProcessBuilder { val moduleXmlFile = createTempFile( content = ModuleXmlBuilder.build(outputDir = tempDir.path, classPath = classpath, sourcePath = scriptKt.path), fileName = "module", extension = ".xml") return ProcessBuilder( "java", "-jar", kotlinCompilerJar.path, "-kotlin-home", libDirLocation.path, "-module", moduleXmlFile.path, scriptKt.path) } }
platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/compile/LocalCompiler.kt
359521456
// 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.plugins import java.nio.file.Path /** * @author yole */ data class PluginInstallCallbackData( val file: Path, val pluginDescriptor: IdeaPluginDescriptorImpl, val restartNeeded: Boolean ) data class PendingDynamicPluginInstall( val file: Path, val pluginDescriptor: IdeaPluginDescriptorImpl ) fun installPluginFromCallbackData(callbackData: PluginInstallCallbackData) { if (callbackData.restartNeeded) { PluginManagerConfigurable.shutdownOrRestartAppAfterInstall(callbackData.pluginDescriptor.name) } else { if (!PluginInstaller.installAndLoadDynamicPlugin(callbackData.file, null, callbackData.pluginDescriptor)) { PluginManagerConfigurable.shutdownOrRestartAppAfterInstall(callbackData.pluginDescriptor.name) } } }
platform/platform-impl/src/com/intellij/ide/plugins/PluginInstallCallbackData.kt
2109283038
package jetbrains.buildServer.dotnet import jetbrains.buildServer.RunBuildException import jetbrains.buildServer.agent.Path import jetbrains.buildServer.agent.ToolCannotBeFoundException import jetbrains.buildServer.agent.ToolPath import jetbrains.buildServer.agent.runner.ParameterType import jetbrains.buildServer.agent.runner.ParametersService import java.io.File class VSTestToolResolver( private val _parametersService: ParametersService, private val _dotnetToolResolver: ToolResolver) : ToolResolver { override val paltform: ToolPlatform get() = _currentTool?.platform ?: ToolPlatform.CrossPlatform override val executable: ToolPath get() { _currentTool?.let { when (it.platform) { ToolPlatform.Windows -> { val vstestTool = "teamcity.dotnet.vstest.${it.version}.0" return ToolPath(tryGetTool(vstestTool) ?: throw RunBuildException(ToolCannotBeFoundException(vstestTool))) } else -> { } } } return _dotnetToolResolver.executable } override val isCommandRequired: Boolean get() { _currentTool?.let { return it.platform == ToolPlatform.CrossPlatform } return true } private val _currentTool: Tool? get() { _parametersService.tryGetParameter(ParameterType.Runner, DotnetConstants.PARAM_VSTEST_VERSION)?.let { return Tool.tryParse(it) } return null } private fun tryGetTool(parameterName: String): Path? { _parametersService.tryGetParameter(ParameterType.Configuration, parameterName)?.let { return Path(File(it).canonicalPath) } return null } }
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotnet/VSTestToolResolver.kt
2601444290
package com.eigengraph.egf2.framework import retrofit2.Response import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Query import rx.Observable internal interface EGF2AuthService { @POST("register") fun register(@Body body: Any): Observable<Response<TokenModel>> @POST("login") fun login(@Body body: Any): Observable<Response<TokenModel>> @GET("verify_email") fun verifyEmail(@Query("token") token: String): Observable<Response<Any>> @GET("logout") fun logout(): Observable<Response<Void>> @GET("forgot_password") fun forgotPassword(@Query("email") email: String): Observable<Response<Any>> @POST("reset_password") fun resetPassword(@Body body: Any): Observable<Response<Any>> @POST("change_password") fun changePassword(@Body body: Any): Observable<Response<Any>> @POST("resend_email_verification") fun resendEmailVerification(): Observable<Response<Void>> }
framework/src/main/kotlin/com/eigengraph/egf2/framework/EGF2AuthService.kt
1350261918
package com.trevjonez.ktor_playground.people import com.trevjonez.ktor_playground.people.PersonEntity.* import org.assertj.core.api.Assertions.assertThat import org.junit.Test class PersonEntityPostValidatorTest { @Test fun `validator fills in optional fields`() { assertThat(PostValidator.validate(RawPerson(null, null, null, null, "John Doe", 22))) .hasNoNullFieldsOrPropertiesExcept("deletedOn") } @Test(expected = NullPointerException::class) fun `missing name throws npe`() { PostValidator.validate(RawPerson(null, null, null, null, null, 22)) } @Test(expected = NullPointerException::class) fun `missing age throws npe`() { PostValidator.validate(RawPerson(null, null, null, null, "John Doe", null)) } }
src/test/kotlin/com/trevjonez/ktor_playground/people/PersonEntityPostValidatorTest.kt
3459766327
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage import com.intellij.workspaceModel.storage.bridgeEntities.LibraryTableId import com.intellij.workspaceModel.storage.bridgeEntities.addLibraryEntity import com.intellij.workspaceModel.storage.entities.MySource import com.intellij.workspaceModel.storage.entities.addSampleEntity import com.intellij.workspaceModel.storage.impl.EntityStorageSerializerImpl import com.intellij.workspaceModel.storage.impl.WorkspaceEntityStorageBuilderImpl import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl import junit.framework.Assert.* import org.junit.Test import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream class EntityStorageSerializationTest { @Test fun `simple model serialization`() { val builder = createEmptyBuilder() builder.addSampleEntity("MyEntity") SerializationRoundTripChecker.verifyPSerializationRoundTrip(builder.toStorage(), VirtualFileUrlManagerImpl()) } @Test fun `serialization with version changing`() { val builder = createEmptyBuilder() builder.addSampleEntity("MyEntity") val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl()) val deserializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl()) .also { it.serializerDataFormatVersion = "XYZ" } val stream = ByteArrayOutputStream() serializer.serializeCache(stream, builder.toStorage()) val byteArray = stream.toByteArray() val deserialized = (deserializer.deserializeCache(ByteArrayInputStream(byteArray)) as? WorkspaceEntityStorageBuilderImpl)?.toStorage() assertNull(deserialized) } @Test fun `serializer version`() { val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl()) val kryo = serializer.createKryo() val registration = (10..1_000).mapNotNull { kryo.getRegistration(it) }.joinToString(separator = "\n") assertEquals("Have you changed kryo registration? Update the version number! (And this test)", expectedKryoRegistration, registration) } @Test fun `serialize empty lists`() { val virtualFileManager = VirtualFileUrlManagerImpl() val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager) val builder = createEmptyBuilder() // Do not replace ArrayList() with emptyList(). This must be a new object for this test builder.addLibraryEntity("myName", LibraryTableId.ProjectLibraryTableId, ArrayList(), ArrayList(), MySource) val stream = ByteArrayOutputStream() serializer.serializeCache(stream, builder.toStorage()) } @Test fun `serialize abstract`() { val virtualFileManager = VirtualFileUrlManagerImpl() val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager) val builder = createEmptyBuilder() builder.addSampleEntity("myString") val stream = ByteArrayOutputStream() val result = serializer.serializeCache(stream, builder.toStorage()) assertTrue(result is SerializationResult.Success) } @Test fun `read broken cache`() { val virtualFileManager = VirtualFileUrlManagerImpl() val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager) val builder = createEmptyBuilder() builder.addSampleEntity("myString") val stream = ByteArrayOutputStream() serializer.serializeCache(stream, builder.toStorage()) // Remove random byte from a serialised store val inputStream = stream.toByteArray().filterIndexed { i, _ -> i != 3 }.toByteArray().inputStream() val result = serializer.deserializeCache(inputStream) assertNull(result) } } // Kotlin tip: Use the ugly ${'$'} to insert the $ into the multiline string private val expectedKryoRegistration = """ [10, com.intellij.workspaceModel.storage.impl.EntityId] [11, com.google.common.collect.HashMultimap] [12, com.intellij.workspaceModel.storage.impl.ConnectionId] [13, com.intellij.workspaceModel.storage.impl.ImmutableEntitiesBarrel] [14, com.intellij.workspaceModel.storage.impl.EntityStorageSerializerImpl${'$'}TypeInfo] [15, java.util.ArrayList] [16, java.util.HashMap] [17, com.intellij.util.SmartList] [18, java.util.LinkedHashMap] [19, com.intellij.workspaceModel.storage.impl.containers.BidirectionalMap] [20, com.intellij.workspaceModel.storage.impl.containers.BidirectionalSetMap] [21, java.util.HashSet] [22, com.intellij.util.containers.BidirectionalMultiMap] [23, com.google.common.collect.HashBiMap] [24, com.intellij.workspaceModel.storage.impl.containers.LinkedBidirectionalMap] [25, it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap] [26, it.unimi.dsi.fastutil.objects.ObjectOpenHashSet] [27, it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap] [28, java.util.Arrays${'$'}ArrayList] [29, byte[]] [30, com.intellij.workspaceModel.storage.impl.ImmutableEntityFamily] [31, com.intellij.workspaceModel.storage.impl.RefsTable] [32, com.intellij.workspaceModel.storage.impl.containers.ImmutableNonNegativeIntIntBiMap] [33, com.intellij.workspaceModel.storage.impl.containers.ImmutableIntIntUniqueBiMap] [34, com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex] [35, com.intellij.workspaceModel.storage.impl.indices.EntityStorageInternalIndex] [36, com.intellij.workspaceModel.storage.impl.containers.ImmutableNonNegativeIntIntMultiMap${'$'}ByList] [37, int[]] [38, kotlin.Pair] [39, com.intellij.workspaceModel.storage.impl.indices.MultimapStorageIndex] [40, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}AddEntity] [41, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}RemoveEntity] [42, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}ReplaceEntity] [43, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}ChangeEntitySource] [44, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}ReplaceAndChangeSource] [45, java.util.LinkedHashSet] [46, java.util.Collections${'$'}UnmodifiableCollection] [47, java.util.Collections${'$'}UnmodifiableSet] [48, java.util.Collections${'$'}UnmodifiableRandomAccessList] [49, java.util.Collections${'$'}UnmodifiableMap] [50, java.util.Collections${'$'}EmptyList] [51, java.util.Collections${'$'}EmptyMap] [52, java.util.Collections${'$'}EmptySet] [53, java.util.Collections${'$'}SingletonList] [54, java.util.Collections${'$'}SingletonMap] [55, java.util.Collections${'$'}SingletonSet] [56, com.intellij.util.containers.ContainerUtilRt${'$'}EmptyList] [57, com.intellij.util.containers.MostlySingularMultiMap${'$'}EmptyMap] [58, com.intellij.util.containers.MultiMap${'$'}EmptyMap] [59, kotlin.collections.EmptyMap] [60, kotlin.collections.EmptyList] [61, kotlin.collections.EmptySet] """.trimIndent()
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/EntityStorageSerializationTest.kt
3554151589
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.rename.inplace import com.intellij.codeInsight.template.TemplateResultListener import com.intellij.codeInsight.template.impl.TemplateState import com.intellij.injected.editor.DocumentWindow import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.refactoring.rename.api.PsiRenameUsage import com.intellij.util.DocumentUtil internal fun usageRangeInHost(hostFile: PsiFile, usage: PsiRenameUsage): TextRange? { return if (usage.file == hostFile) { usage.range } else { injectedToHost(hostFile.project, usage.file, usage.range) } } private fun injectedToHost(project: Project, injectedFile: PsiFile, injectedRange: TextRange): TextRange? { val injectedDocument: DocumentWindow = PsiDocumentManager.getInstance(project).getDocument(injectedFile) as? DocumentWindow ?: return null val startOffsetHostRange: TextRange = injectedDocument.getHostRange(injectedDocument.injectedToHost(injectedRange.startOffset)) ?: return null val endOffsetHostRange: TextRange = injectedDocument.getHostRange(injectedDocument.injectedToHost(injectedRange.endOffset)) ?: return null return if (startOffsetHostRange == endOffsetHostRange) { injectedDocument.injectedToHost(injectedRange) } else { null } } internal fun TemplateState.addTemplateResultListener(resultConsumer: (TemplateResultListener.TemplateResult) -> Unit) { return addTemplateStateListener(TemplateResultListener(resultConsumer)) } internal fun deleteInplaceTemplateSegments( project: Project, document: Document, templateSegmentRanges: List<TextRange> ): Runnable { val hostDocumentContent = document.text val stateBefore: List<Pair<RangeMarker, String>> = templateSegmentRanges.map { range -> val marker = document.createRangeMarker(range).also { it.isGreedyToRight = true } val content = range.substring(hostDocumentContent) Pair(marker, content) } DocumentUtil.executeInBulk(document, true) { for (range in templateSegmentRanges.asReversed()) { document.deleteString(range.startOffset, range.endOffset) } } return Runnable { WriteCommandAction.writeCommandAction(project).run<Throwable> { DocumentUtil.executeInBulk(document, true) { for ((marker: RangeMarker, content: String) in stateBefore) { document.replaceString(marker.startOffset, marker.endOffset, content) } } PsiDocumentManager.getInstance(project).commitDocument(document) } } }
platform/lang-impl/src/com/intellij/refactoring/rename/inplace/util.kt
3414599167
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.issue import com.intellij.build.BuildView import com.intellij.build.issue.BuildIssue import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.execution.runners.ExecutionUtil import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.externalSystem.issue.quickfix.ReimportQuickFix.Companion.requestImport import com.intellij.openapi.externalSystem.util.ExternalSystemBundle import com.intellij.openapi.project.Project import com.intellij.pom.Navigatable import org.jetbrains.annotations.ApiStatus import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.util.GradleConstants import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.runAsync @ApiStatus.Internal abstract class UnresolvedDependencyIssue(dependencyName: String) : BuildIssue { override val title: String = "Could not resolve $dependencyName" override fun getNavigatable(project: Project): Navigatable? = null fun buildDescription(failureMessage: String?, isOfflineMode: Boolean, offlineModeQuickFixText: String): String { val issueDescription = StringBuilder(failureMessage?.trim()) val noRepositoriesDefined = failureMessage?.contains("no repositories are defined") ?: false issueDescription.append("\n\nPossible solution:\n") when { isOfflineMode && !noRepositoriesDefined -> issueDescription.append( " - <a href=\"$offlineQuickFixId\">$offlineModeQuickFixText</a>\n") else -> issueDescription.append( " - Declare repository providing the artifact, see the documentation at $declaringRepositoriesLink\n") } return issueDescription.toString() } companion object { internal const val offlineQuickFixId = "disable_offline_mode" private const val declaringRepositoriesLink = "https://docs.gradle.org/current/userguide/declaring_repositories.html" } } @ApiStatus.Experimental class UnresolvedDependencySyncIssue(dependencyName: String, failureMessage: String?, projectPath: String, isOfflineMode: Boolean) : UnresolvedDependencyIssue(dependencyName) { override val quickFixes = if (isOfflineMode) listOf<BuildIssueQuickFix>(DisableOfflineAndReimport(projectPath)) else emptyList() override val description: String = buildDescription(failureMessage, isOfflineMode, "Disable offline mode and reload the project") inner class DisableOfflineAndReimport(private val projectPath: String) : BuildIssueQuickFix { override val id = offlineQuickFixId override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> { GradleSettings.getInstance(project).isOfflineWork = false return tryRerun(dataContext) ?: requestImport(project, projectPath, GradleConstants.SYSTEM_ID) } } } @ApiStatus.Experimental class UnresolvedDependencyBuildIssue(dependencyName: String, failureMessage: String?, isOfflineMode: Boolean) : UnresolvedDependencyIssue(dependencyName) { override val quickFixes = if (isOfflineMode) listOf<BuildIssueQuickFix>(DisableOfflineAndRerun()) else emptyList() override val description: String = buildDescription(failureMessage, isOfflineMode, "Disable offline mode and rerun the build") inner class DisableOfflineAndRerun : BuildIssueQuickFix { override val id = offlineQuickFixId override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> { GradleSettings.getInstance(project).isOfflineWork = false return tryRerun(dataContext) ?: CompletableFuture.completedFuture(null) } } } private fun tryRerun(dataContext: DataContext): CompletableFuture<*>? { val environment = LangDataKeys.EXECUTION_ENVIRONMENT.getData(dataContext) if (environment != null) { return runAsync { ExecutionUtil.restart(environment) } } val restartActions = BuildView.RESTART_ACTIONS.getData(dataContext) val reimportActionText = ExternalSystemBundle.message("action.refresh.project.text", GradleConstants.SYSTEM_ID.readableName) restartActions?.find { it.templateText == reimportActionText }?.let { action -> val actionEvent = AnActionEvent.createFromAnAction(action, null, "BuildView", dataContext) action.update(actionEvent) if (actionEvent.presentation.isEnabledAndVisible) { return runAsync { action.actionPerformed(actionEvent) } } } return null }
plugins/gradle/src/org/jetbrains/plugins/gradle/issue/UnresolvedDependencyIssue.kt
555198003
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME fun box() : String { val i = 1 return if(i.javaClass.getSimpleName() == "int") "OK" else "fail" }
backend.native/tests/external/codegen/box/regressions/kt1568.kt
4270706036
package net.ndrei.teslacorelib.utils import net.minecraft.util.EnumFacing import net.minecraft.util.math.BlockPos /** * Created by CF on 2017-07-06. */ object BlockPosUtils { fun getCube(entityPos: BlockPos, facing: EnumFacing?, radius: Int, height: Int): BlockCube { val pos1: BlockPos var pos2: BlockPos if (facing != null) { if (facing == EnumFacing.UP) { pos1 = entityPos .offset(EnumFacing.EAST, radius) .offset(EnumFacing.SOUTH, radius) .up(1) pos2 = entityPos .offset(EnumFacing.WEST, radius) .offset(EnumFacing.NORTH, radius) .up(height) } else if (facing == EnumFacing.DOWN) { pos1 = entityPos .offset(EnumFacing.EAST, radius) .offset(EnumFacing.SOUTH, radius) .down(1) pos2 = entityPos .offset(EnumFacing.WEST, radius) .offset(EnumFacing.NORTH, radius) .down(height) } else { // assume horizontal facing val left = facing.rotateYCCW() val right = facing.rotateY() pos1 = entityPos .offset(left, radius) .offset(facing, 1) pos2 = entityPos .offset(right, radius) .offset(facing, radius * 2 + 1) } } else { pos1 = BlockPos(entityPos.x - radius, entityPos.y, entityPos.z - radius) pos2 = BlockPos(entityPos.x + radius, entityPos.y, entityPos.z + radius) } pos2 = pos2.offset(EnumFacing.UP, height - 1) return BlockCube(pos1, pos2) } }
src/main/kotlin/net/ndrei/teslacorelib/utils/BlockPosUtils.kt
1668849270
package kotlinApp.services import kotlinApp.model.Message import org.springframework.stereotype.Service import java.util.UUID @Service interface MessageService { fun getMessages(): List<Message> fun saveMessage(message: Message) fun updateMessage(message: Message) fun deleteMessage(id: String) }
KotlinApp/src/main/kotlin/kotlinApp/services/MessageService.kt
2151490099
package io.github.robwin.web.entity import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.Id import javax.persistence.Table @Entity @Table(name = "heroes") data class Hero (@Id @GeneratedValue(strategy = javax.persistence.GenerationType.AUTO) var id: Int? = null, var name: String = "")
spring-boot-server/src/main/kotlin/io/github/robwin/web/entity/Hero.kt
4275363982
open class A class B : A() { fun foo() = 1 } class Test { val a : A = B() private val b : B get() = a as B //'private' is important here fun outer() : Int { fun inner() : Int = b.foo() //'no such field error' here return inner() } } fun box() = if (Test().outer() == 1) "OK" else "fail"
backend.native/tests/external/codegen/box/properties/kt2892.kt
2157088532
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME var result = "fail 2" class Foo { val b = { a } val c = Runnable { result = a } companion object { @JvmStatic private val a = "OK" } } fun box(): String { if (Foo().b() != "OK") return "fail 1" Foo().c.run() return result }
backend.native/tests/external/codegen/box/jvmStatic/propertyAccessorsCompanion.kt
4239815677
class K1 : MyJavaClass() { override fun coll(c: Collection<Any?>?, i: Int) = Unit } class K2 : MyJavaClass() { override fun coll(c: Collection<Any?>, i: Int) = Unit } class K3 : MyJavaClass() { override fun coll(c: MutableCollection<Any?>, i: Int) = Unit } class K4 : MyJavaClass() { override fun coll(c: MutableCollection<Any?>?, i: Int) = Unit }
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/ChangeJavaMethodWithRawTypeAfter.1.kt
585349579
// MOVE: up class A { fun <T, U, W> foo( b: Int, c: Int <caret>a: Int, ) { } class B { } }
plugins/kotlin/idea/tests/testData/codeInsight/moveUpDown/trailingComma/funParams4.kt
3805375300
package technology.mainthread.apps.gatekeeper.viewModel import androidx.databinding.BaseObservable class MainActivityViewModel : BaseObservable()
mobile/src/main/java/technology/mainthread/apps/gatekeeper/viewModel/MainActivityViewModel.kt
2397048695
package core.export import com.cout970.modeler.core.export.ModelImporters.tcnImporter import com.cout970.modeler.util.toResourcePath import org.junit.Assert import org.junit.Test import java.io.File /** * Created by cout970 on 2017/06/06. */ class TcnHandler { @Test fun `Try importing a cube mode`() { val path = File("src/test/resources/model/cube.tcn").toResourcePath() val model = tcnImporter.import(path) Assert.assertEquals("Invalid number of cubes", 1, model.objects.size) } }
src/test/kotlin/core/export/TcnHandler.kt
3391459284
package info.nightscout.androidaps.plugins.general.automation.elements import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerTestBase import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) class LabelWithElementTest : TriggerTestBase() { @Test fun constructorTest() { val l = LabelWithElement(injector, "A", "B", InputInsulin(injector)) Assert.assertEquals("A", l.textPre) Assert.assertEquals("B", l.textPost) Assert.assertEquals(InputInsulin::class.java, l.element!!.javaClass) } }
app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElementTest.kt
2911363187
package ftl.ios.xctest.common import com.google.common.truth.Truth.assertThat import flank.common.isWindows import ftl.ios.xctest.FIXTURES_PATH import ftl.ios.xctest.multiTargetsSwiftXcTestRunV1 import ftl.ios.xctest.swiftTestsV1 import ftl.ios.xctest.swiftXcTestRunV1 import ftl.run.exception.FlankGeneralError import org.junit.Assume.assumeFalse import org.junit.Test import java.io.File import java.nio.file.Files import java.nio.file.Paths class FindTestsForTargetKtTest { @Test fun `findTestNames respects skip`() { assumeFalse(isWindows) val inputXml = """ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>EarlGreyExampleSwiftTests</key> <dict> <key>DependentProductPaths</key> <array> <string>__TESTROOT__/Debug-iphoneos/EarlGreyExampleSwift.app/PlugIns/EarlGreyExampleSwiftTests.xctest</string> <string>__TESTROOT__/Debug-iphoneos/EarlGreyExampleSwift.app</string> </array> <key>SkipTestIdentifiers</key> <array> <string>EarlGreyExampleSwiftTests/testBasicSelectionActionAssert</string> <string>EarlGreyExampleSwiftTests/testBasicSelectionAndAction</string> <string>EarlGreyExampleSwiftTests/testBasicSelectionAndAssert</string> <string>EarlGreyExampleSwiftTests/testCatchErrorOnFailure</string> <string>EarlGreyExampleSwiftTests/testCollectionMatchers</string> <string>EarlGreyExampleSwiftTests/testCustomAction</string> <string>EarlGreyExampleSwiftTests/testLayout</string> <string>EarlGreyExampleSwiftTests/testSelectionOnMultipleElements</string> <string>EarlGreyExampleSwiftTests/testTableCellOutOfScreen</string> <string>EarlGreyExampleSwiftTests/testThatThrows</string> <string>EarlGreyExampleSwiftTests/testWithCondition</string> <string>EarlGreyExampleSwiftTests/testWithCustomAssertion</string> <string>EarlGreyExampleSwiftTests/testWithCustomFailureHandler</string> <string>EarlGreyExampleSwiftTests/testWithCustomMatcher</string> <string>EarlGreyExampleSwiftTests/testWithGreyAssertions</string> <string>EarlGreyExampleSwiftTests/testWithInRoot</string> </array> </dict> </dict> </plist> """.trimIndent() val tmpXml = Paths.get("$FIXTURES_PATH/ios/EarlGreyExample", "skip.xctestrun") Files.write(tmpXml, inputXml.toByteArray()) tmpXml.toFile().deleteOnExit() val actualTests = findTestsForTestTarget("EarlGreyExampleSwiftTests", tmpXml.toFile(), true).sorted() assertThat(actualTests).isEqualTo(listOf("EarlGreyExampleSwiftTests/testBasicSelection")) } @Test fun findTestNamesForTestTarget() { assumeFalse(isWindows) val names = findTestsForTestTarget(testTarget = "EarlGreyExampleSwiftTests", xctestrun = File(swiftXcTestRunV1), true).sorted() assertThat(swiftTestsV1).isEqualTo(names) } @Test(expected = FlankGeneralError::class) fun `findTestNames for nonexisting test target`() { assumeFalse(isWindows) findTestsForTestTarget(testTarget = "Incorrect", xctestrun = File(swiftXcTestRunV1), true).sorted() } @Test fun `find test names for xctestrun file containing multiple test targets`() { assumeFalse(isWindows) val names = findTestsForTestTarget(testTarget = "FlankExampleTests", xctestrun = File(multiTargetsSwiftXcTestRunV1), true).sorted() assertThat(names).isEqualTo(listOf("FlankExampleTests/test1", "FlankExampleTests/test2")) val names2 = findTestsForTestTarget(testTarget = "FlankExampleSecondTests", xctestrun = File(multiTargetsSwiftXcTestRunV1), true).sorted() assertThat(names2).isEqualTo(listOf("FlankExampleSecondTests/test3", "FlankExampleSecondTests/test4")) } }
test_runner/src/test/kotlin/ftl/ios/xctest/common/FindTestsForTargetKtTest.kt
908959450
// 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.vcs.changes.committed import com.intellij.openapi.Disposable import com.intellij.openapi.ui.ComponentValidator import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList import com.intellij.ui.FilterComponent import com.intellij.ui.LightColors import com.intellij.ui.components.JBCheckBox import com.intellij.util.containers.ContainerUtil.createLockFreeCopyOnWriteList import com.intellij.util.ui.UIUtil.getTextFieldBackground import java.awt.BorderLayout import java.awt.event.ItemListener import java.util.function.Supplier import java.util.regex.PatternSyntaxException import javax.swing.JComponent import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener private typealias CommittedChangeListPredicate = (CommittedChangeList) -> Boolean private val TEXT_FILTER_KEY = CommittedChangesFilterKey("text", CommittedChangesFilterPriority.TEXT) class CommittedChangesFilterComponent : FilterComponent("COMMITTED_CHANGES_FILTER_HISTORY", 20), ChangeListFilteringStrategy, Disposable { private val listeners = createLockFreeCopyOnWriteList<ChangeListener>() private val regexCheckBox = JBCheckBox(message("committed.changes.regex.title")).apply { model.addItemListener(ItemListener { filter() }) } private val regexValidator = ComponentValidator(this) .withValidator(Supplier { validateRegex() }) .installOn(textEditor) private var regex: Regex? = null init { add(regexCheckBox, BorderLayout.EAST) } private fun hasValidationErrors(): Boolean = regexValidator.validationInfo != null private fun validateRegex(): ValidationInfo? { if (!regexCheckBox.isSelected) return null regex = null val value = filter.takeUnless { it.isNullOrEmpty() } ?: return null return try { regex = Regex(value) null } catch (e: PatternSyntaxException) { ValidationInfo("Please enter a valid regex", textEditor) } } override fun filter() { regexValidator.revalidate() val event = ChangeEvent(this) listeners.forEach { it.stateChanged(event) } } override fun getKey(): CommittedChangesFilterKey = TEXT_FILTER_KEY override fun getFilterUI(): JComponent? = null override fun addChangeListener(listener: ChangeListener) { listeners += listener } override fun removeChangeListener(listener: ChangeListener) { listeners -= listener } override fun setFilterBase(changeLists: List<CommittedChangeList>) = Unit override fun resetFilterBase() = Unit override fun appendFilterBase(changeLists: List<CommittedChangeList>) = Unit override fun filterChangeLists(changeLists: List<CommittedChangeList>): List<CommittedChangeList> { val result = doFilter(changeLists) textEditor.background = if (result.isEmpty() && changeLists.isNotEmpty()) LightColors.RED else getTextFieldBackground() return result } private fun doFilter(changeLists: List<CommittedChangeList>): List<CommittedChangeList> { if (hasValidationErrors()) return emptyList() val predicate = createFilterPredicate() ?: return changeLists return changeLists.filter(predicate) } private fun createFilterPredicate(): CommittedChangeListPredicate? = if (regexCheckBox.isSelected) regex?.let { RegexPredicate(it) } else filter.takeUnless { it.isNullOrBlank() }?.let { WordPredicate(it) } } private class RegexPredicate(private val regex: Regex) : CommittedChangeListPredicate { override fun invoke(changeList: CommittedChangeList): Boolean = regex.containsMatchIn(changeList.comment.orEmpty()) || regex.containsMatchIn(changeList.committerName.orEmpty()) || regex.containsMatchIn(changeList.number.toString()) } private class WordPredicate(filter: String) : CommittedChangeListPredicate { private val filterWords = filter.split(" ") override fun invoke(changeList: CommittedChangeList): Boolean = filterWords.any { word -> changeList.comment.orEmpty().contains(word, true) || changeList.committerName.orEmpty().contains(word, true) || changeList.number.toString().contains(word) } }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CommittedChangesFilterComponent.kt
2760021829
// 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.diff.comparison import com.intellij.diff.DiffTestCase import com.intellij.diff.fragments.MergeLineFragment import com.intellij.diff.util.IntPair import com.intellij.diff.util.MergeRange import com.intellij.diff.util.ThreeSide import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.util.Couple import java.util.* abstract class ComparisonMergeUtilTestBase : DiffTestCase() { private fun doCharTest(texts: Trio<Document>, expected: List<Change>?, matchings: Trio<BitSet>?) { val iterable1 = ByChar.compare(texts.data2.charsSequence, texts.data1.charsSequence, INDICATOR) val iterable2 = ByChar.compare(texts.data2.charsSequence, texts.data3.charsSequence, INDICATOR) val fragments = ComparisonMergeUtil.buildSimple(iterable1, iterable2, INDICATOR) val actual = convertDiffFragments(fragments) checkConsistency(actual, texts) if (matchings != null) checkDiffMatching(actual, matchings) if (expected != null) checkDiffChanges(actual, expected) } private fun doLineDiffTest(texts: Trio<Document>, expected: List<Change>?, matchings: Trio<BitSet>?, policy: ComparisonPolicy) { val fragments = MANAGER.compareLines(texts.data1.charsSequence, texts.data2.charsSequence, texts.data3.charsSequence, policy, INDICATOR) val actual = convertMergeFragments(fragments) if (matchings != null) checkDiffMatching(actual, matchings) if (expected != null) checkDiffChanges(actual, expected) } private fun doLineMergeTest(texts: Trio<Document>, expected: List<Change>?, matchings: Trio<BitSet>?, policy: ComparisonPolicy) { val fragments = MANAGER.mergeLines(texts.data1.charsSequence, texts.data2.charsSequence, texts.data3.charsSequence, policy, INDICATOR) val actual = convertMergeFragments(fragments) if (matchings != null) checkDiffMatching(actual, matchings) if (expected != null) checkDiffChanges(actual, expected) } private fun checkConsistency(actual: List<Change>, texts: Trio<Document>) { var lasts = Trio(-1, -1, -1) for (change in actual) { val starts = change.starts val ends = change.ends var empty = true var squashed = true ThreeSide.values().forEach { val start = starts(it) val end = ends(it) val last = lasts(it) assertTrue(last <= start) assertTrue(start <= end) empty = empty && (start == end) squashed = squashed && (start == last) } assertTrue(!empty) assertTrue(!squashed) lasts = ends } } private fun checkDiffChanges(actual: List<Change>, expected: List<Change>) { assertOrderedEquals(expected, actual) } private fun checkDiffMatching(changes: List<Change>, matchings: Trio<BitSet>) { val sets = Trio(BitSet(), BitSet(), BitSet()) for (change in changes) { sets.forEach { set: BitSet, side: ThreeSide -> set.set(change.start(side), change.end(side)) } } assertSetsEquals(matchings.data1, sets.data1, "Left") assertSetsEquals(matchings.data2, sets.data2, "Base") assertSetsEquals(matchings.data3, sets.data3, "Right") } private fun convertDiffFragments(fragments: List<MergeRange>): List<Change> { return fragments.map { Change( it.start1, it.end1, it.start2, it.end2, it.start3, it.end3) } } private fun convertMergeFragments(fragments: List<MergeLineFragment>): List<Change> { return fragments.map { Change( it.getStartLine(ThreeSide.LEFT), it.getEndLine(ThreeSide.LEFT), it.getStartLine(ThreeSide.BASE), it.getEndLine(ThreeSide.BASE), it.getStartLine(ThreeSide.RIGHT), it.getEndLine(ThreeSide.RIGHT)) } } internal enum class TestType { CHAR, LINE_DIFF, LINE_MERGE } internal inner class MergeTestBuilder(val type: TestType) { private var isExecuted: Boolean = false private var texts: Trio<Document>? = null private var changes: List<Change>? = null private var matching: Trio<BitSet>? = null fun assertExecuted() { assertTrue(isExecuted) } fun test() { test(ComparisonPolicy.DEFAULT) } fun test(policy: ComparisonPolicy) { isExecuted = true assertTrue(changes != null || matching != null) when (type) { TestType.CHAR -> { assertEquals(policy, ComparisonPolicy.DEFAULT) doCharTest(texts!!, changes, matching) } TestType.LINE_DIFF -> { doLineDiffTest(texts!!, changes, matching, policy) } TestType.LINE_MERGE -> { doLineMergeTest(texts!!, changes, matching, policy) } } } operator fun String.minus(v: String): Couple<String> { return Couple(this, v) } operator fun Couple<String>.minus(v: String): Helper { return Helper(Trio(this.first, this.second, v)) } inner class Helper(val matchTexts: Trio<String>) { init { if (texts == null) { texts = matchTexts.map { it -> DocumentImpl(parseSource(it)) } } } fun matching() { assertNull(matching) if (type != TestType.CHAR) { matching = matchTexts.map { it, side -> parseLineMatching(it, texts!!(side)) } } else { matching = matchTexts.map { it, side -> parseMatching(it, texts!!(side)) } } } } fun changes(vararg expected: Change) { assertNull(changes) changes = listOf(*expected) } fun mod(line1: Int, line2: Int, line3: Int, count1: Int, count2: Int, count3: Int): Change { return Change(line1, line1 + count1, line2, line2 + count2, line3, line3 + count3) } } internal fun chars(f: MergeTestBuilder.() -> Unit) { doTest(TestType.CHAR, f) } internal fun lines_diff(f: MergeTestBuilder.() -> Unit) { doTest(TestType.LINE_DIFF, f) } internal fun lines_merge(f: MergeTestBuilder.() -> Unit) { doTest(TestType.LINE_MERGE, f) } internal fun doTest(type: TestType, f: MergeTestBuilder.() -> Unit) { val builder = MergeTestBuilder(type) builder.f() builder.assertExecuted() } class Change(start1: Int, end1: Int, start2: Int, end2: Int, start3: Int, end3: Int) : Trio<IntPair>(IntPair(start1, end1), IntPair(start2, end2), IntPair(start3, end3)) { val start1 = start(ThreeSide.LEFT) val start2 = start(ThreeSide.BASE) val start3 = start(ThreeSide.RIGHT) val end1 = end(ThreeSide.LEFT) val end2 = end(ThreeSide.BASE) val end3 = end(ThreeSide.RIGHT) val starts = Trio(start1, start2, start3) val ends = Trio(end1, end2, end3) fun start(side: ThreeSide): Int = this(side).val1 fun end(side: ThreeSide): Int = this(side).val2 override fun toString(): String { return "($start1, $end1) - ($start2, $end2) - ($start3, $end3)" } } }
platform/diff-impl/tests/testSrc/com/intellij/diff/comparison/ComparisonMergeUtilTestBase.kt
1553164742
fun a() { val b = 3 val a = "${b<caret>}" }
plugins/kotlin/idea/tests/testData/indentationOnNewline/templates/TemplateEntryClose.kt
2743678243
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator import org.jetbrains.kotlin.idea.core.isVisible import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns class DestructureInspection : IntentionBasedInspection<KtDeclaration>( DestructureIntention::class, { element, _ -> val usagesToRemove = DestructureIntention.collectUsagesToRemove(element)?.data if (element is KtParameter) { usagesToRemove != null && (usagesToRemove.any { it.declarationToDrop is KtDestructuringDeclaration } || usagesToRemove.filter { it.usagesToReplace.isNotEmpty() }.size > usagesToRemove.size / 2) } else { usagesToRemove?.any { it.declarationToDrop is KtDestructuringDeclaration } ?: false } } ) class DestructureIntention : SelfTargetingRangeIntention<KtDeclaration>( KtDeclaration::class.java, KotlinBundle.lazyMessage("use.destructuring.declaration") ) { override fun applyTo(element: KtDeclaration, editor: Editor?) { val (usagesToRemove, removeSelectorInLoopRange) = collectUsagesToRemove(element) ?: return val factory = KtPsiFactory(element) val parent = element.parent val (container, anchor) = if (parent is KtParameterList) parent.parent to null else parent to element val validator = NewDeclarationNameValidator( container = container, anchor = anchor, target = NewDeclarationNameValidator.Target.VARIABLES, excludedDeclarations = usagesToRemove.map { (it.declarationToDrop as? KtDestructuringDeclaration)?.entries ?: listOfNotNull(it.declarationToDrop) }.flatten() ) val names = ArrayList<String>() val underscoreSupported = element.languageVersionSettings.supportsFeature(LanguageFeature.SingleUnderscoreForParameterName) // For all unused we generate normal names, not underscores val allUnused = usagesToRemove.all { (_, usagesToReplace, variableToDrop) -> usagesToReplace.isEmpty() && variableToDrop == null } usagesToRemove.forEach { (descriptor, usagesToReplace, variableToDrop, name) -> val suggestedName = if (usagesToReplace.isEmpty() && variableToDrop == null && underscoreSupported && !allUnused) { "_" } else { KotlinNameSuggester.suggestNameByName(name ?: descriptor.name.asString(), validator) } runWriteAction { variableToDrop?.delete() usagesToReplace.forEach { it.replace(factory.createExpression(suggestedName)) } } names.add(suggestedName) } val joinedNames = names.joinToString() when (element) { is KtParameter -> { val loopRange = (element.parent as? KtForExpression)?.loopRange runWriteAction { val type = element.typeReference?.let { ": ${it.text}" } ?: "" element.replace(factory.createDestructuringParameter("($joinedNames)$type")) if (removeSelectorInLoopRange && loopRange is KtDotQualifiedExpression) { loopRange.replace(loopRange.receiverExpression) } } } is KtFunctionLiteral -> { val lambda = element.parent as KtLambdaExpression SpecifyExplicitLambdaSignatureIntention().applyTo(lambda, editor) runWriteAction { lambda.functionLiteral.valueParameters.singleOrNull()?.replace( factory.createDestructuringParameter("($joinedNames)") ) } } is KtVariableDeclaration -> { val rangeAfterEq = PsiChildRange(element.initializer, element.lastChild) val modifierList = element.modifierList runWriteAction { if (modifierList == null) { element.replace( factory.createDestructuringDeclarationByPattern( "val ($joinedNames) = $0", rangeAfterEq ) ) } else { val rangeBeforeVal = PsiChildRange(element.firstChild, modifierList) element.replace( factory.createDestructuringDeclarationByPattern( "$0:'@xyz' val ($joinedNames) = $1", rangeBeforeVal, rangeAfterEq ) ) } } } } } override fun applicabilityRange(element: KtDeclaration): TextRange? { if (!element.isSuitableDeclaration()) return null val usagesToRemove = collectUsagesToRemove(element)?.data ?: return null if (usagesToRemove.isEmpty()) return null return when (element) { is KtFunctionLiteral -> element.lBrace.textRange is KtNamedDeclaration -> element.nameIdentifier?.textRange else -> null } } companion object { internal fun KtDeclaration.isSuitableDeclaration() = getUsageScopeElement() != null private fun KtDeclaration.getUsageScopeElement(): PsiElement? { val lambdaSupported = languageVersionSettings.supportsFeature(LanguageFeature.DestructuringLambdaParameters) return when (this) { is KtParameter -> { val parent = parent when { parent is KtForExpression -> parent parent.parent is KtFunctionLiteral -> if (lambdaSupported) parent.parent else null else -> null } } is KtProperty -> parent.takeIf { isLocal } is KtFunctionLiteral -> if (!hasParameterSpecification() && lambdaSupported) this else null else -> null } } internal data class UsagesToRemove(val data: List<UsageData>, val removeSelectorInLoopRange: Boolean) internal fun collectUsagesToRemove(declaration: KtDeclaration): UsagesToRemove? { val context = declaration.analyze() val variableDescriptor = when (declaration) { is KtParameter -> context.get(BindingContext.VALUE_PARAMETER, declaration) is KtFunctionLiteral -> context.get(BindingContext.FUNCTION, declaration)?.valueParameters?.singleOrNull() is KtVariableDeclaration -> context.get(BindingContext.VARIABLE, declaration) else -> null } ?: return null val variableType = variableDescriptor.type if (variableType.isMarkedNullable) return null val classDescriptor = variableType.constructor.declarationDescriptor as? ClassDescriptor ?: return null val mapEntryClassDescriptor = classDescriptor.builtIns.mapEntry val usageScopeElement = declaration.getUsageScopeElement() ?: return null val nameToSearch = when (declaration) { is KtParameter -> declaration.nameAsName is KtVariableDeclaration -> declaration.nameAsName else -> Name.identifier("it") } ?: return null // Note: list should contains properties in order to create destructuring declaration val usagesToRemove = mutableListOf<UsageData>() var noBadUsages = true var removeSelectorInLoopRange = false when { DescriptorUtils.isSubclass(classDescriptor, mapEntryClassDescriptor) -> { val forLoop = declaration.parent as? KtForExpression if (forLoop != null) { val loopRangeDescriptor = forLoop.loopRange.getResolvedCall(context)?.resultingDescriptor if (loopRangeDescriptor != null) { val loopRangeDescriptorOwner = loopRangeDescriptor.containingDeclaration val mapClassDescriptor = classDescriptor.builtIns.map if (loopRangeDescriptorOwner is ClassDescriptor && DescriptorUtils.isSubclass(loopRangeDescriptorOwner, mapClassDescriptor) ) { removeSelectorInLoopRange = loopRangeDescriptor.name.asString().let { it == "entries" || it == "entrySet" } } } } listOf("key", "value").mapTo(usagesToRemove) { UsageData( descriptor = mapEntryClassDescriptor.unsubstitutedMemberScope.getContributedVariables( Name.identifier(it), NoLookupLocation.FROM_BUILTINS ).single() ) } usageScopeElement.iterateOverMapEntryPropertiesUsages( context, nameToSearch, variableDescriptor, { index, usageData -> noBadUsages = usagesToRemove[index].add(usageData, index) && noBadUsages }, { noBadUsages = false } ) } classDescriptor.isData -> { val valueParameters = classDescriptor.unsubstitutedPrimaryConstructor?.valueParameters ?: return null valueParameters.mapTo(usagesToRemove) { UsageData(descriptor = it) } val constructorParameterNameMap = mutableMapOf<Name, ValueParameterDescriptor>() valueParameters.forEach { constructorParameterNameMap[it.name] = it } usageScopeElement.iterateOverDataClassPropertiesUsagesWithIndex( context, nameToSearch, variableDescriptor, constructorParameterNameMap, { index, usageData -> noBadUsages = usagesToRemove[index].add(usageData, index) && noBadUsages }, { noBadUsages = false } ) } else -> return null } if (!noBadUsages) return null val droppedLastUnused = usagesToRemove.dropLastWhile { it.usagesToReplace.isEmpty() && it.declarationToDrop == null } return if (droppedLastUnused.isEmpty()) { UsagesToRemove(usagesToRemove, removeSelectorInLoopRange) } else { UsagesToRemove(droppedLastUnused, removeSelectorInLoopRange) } } private fun PsiElement.iterateOverMapEntryPropertiesUsages( context: BindingContext, parameterName: Name, variableDescriptor: VariableDescriptor, process: (Int, SingleUsageData) -> Unit, cancel: () -> Unit ) { anyDescendantOfType<KtNameReferenceExpression> { when { it.getReferencedNameAsName() != parameterName -> false it.getResolvedCall(context)?.resultingDescriptor != variableDescriptor -> false else -> { val applicableUsage = getDataIfUsageIsApplicable(it, context) if (applicableUsage != null) { val usageDescriptor = applicableUsage.descriptor if (usageDescriptor == null) { process(0, applicableUsage) process(1, applicableUsage) return@anyDescendantOfType false } when (usageDescriptor.name.asString()) { "key", "getKey" -> { process(0, applicableUsage) return@anyDescendantOfType false } "value", "getValue" -> { process(1, applicableUsage) return@anyDescendantOfType false } } } cancel() true } } } } private fun PsiElement.iterateOverDataClassPropertiesUsagesWithIndex( context: BindingContext, parameterName: Name, variableDescriptor: VariableDescriptor, constructorParameterNameMap: Map<Name, ValueParameterDescriptor>, process: (Int, SingleUsageData) -> Unit, cancel: () -> Unit ) { anyDescendantOfType<KtNameReferenceExpression> { when { it.getReferencedNameAsName() != parameterName -> false it.getResolvedCall(context)?.resultingDescriptor != variableDescriptor -> false else -> { val applicableUsage = getDataIfUsageIsApplicable(it, context) if (applicableUsage != null) { val usageDescriptor = applicableUsage.descriptor if (usageDescriptor == null) { for (parameter in constructorParameterNameMap.values) { process(parameter.index, applicableUsage) } return@anyDescendantOfType false } val parameter = constructorParameterNameMap[usageDescriptor.name] if (parameter != null) { process(parameter.index, applicableUsage) return@anyDescendantOfType false } } cancel() true } } } } private fun getDataIfUsageIsApplicable(dataClassUsage: KtReferenceExpression, context: BindingContext): SingleUsageData? { val destructuringDecl = dataClassUsage.parent as? KtDestructuringDeclaration if (destructuringDecl != null && destructuringDecl.initializer == dataClassUsage) { return SingleUsageData(descriptor = null, usageToReplace = null, declarationToDrop = destructuringDecl) } val qualifiedExpression = dataClassUsage.getQualifiedExpressionForReceiver() ?: return null val parent = qualifiedExpression.parent when (parent) { is KtBinaryExpression -> { if (parent.operationToken in KtTokens.ALL_ASSIGNMENTS && parent.left == qualifiedExpression) return null } is KtUnaryExpression -> { if (parent.operationToken == KtTokens.PLUSPLUS || parent.operationToken == KtTokens.MINUSMINUS) return null } } val property = parent as? KtProperty // val x = d.y if (property != null && property.isVar) return null val descriptor = qualifiedExpression.getResolvedCall(context)?.resultingDescriptor ?: return null if (!descriptor.isVisible( dataClassUsage, qualifiedExpression.receiverExpression, context, dataClassUsage.containingKtFile.getResolutionFacade() ) ) { return null } return SingleUsageData(descriptor = descriptor, usageToReplace = qualifiedExpression, declarationToDrop = property) } internal data class SingleUsageData( val descriptor: CallableDescriptor?, val usageToReplace: KtExpression?, val declarationToDrop: KtDeclaration? ) internal data class UsageData( val descriptor: CallableDescriptor, val usagesToReplace: MutableList<KtExpression> = mutableListOf(), var declarationToDrop: KtDeclaration? = null, var name: String? = null ) { // Returns true if data is successfully added, false otherwise fun add(newData: SingleUsageData, componentIndex: Int): Boolean { if (newData.declarationToDrop is KtDestructuringDeclaration) { val destructuringEntries = newData.declarationToDrop.entries if (componentIndex < destructuringEntries.size) { if (declarationToDrop != null) return false name = destructuringEntries[componentIndex].name ?: return false declarationToDrop = newData.declarationToDrop } } else { name = name ?: newData.declarationToDrop?.name declarationToDrop = declarationToDrop ?: newData.declarationToDrop } newData.usageToReplace?.let { usagesToReplace.add(it) } return true } } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/DestructureIntention.kt
1604694665
// "Convert expression to 'List' by inserting '.toList()'" "true" // WITH_RUNTIME fun foo(a: Array<String>) { bar(a<caret>) } fun bar(a: List<String>) {}
plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/convertCollection/arrayToList.kt
895280542
// 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.coroutine.proxy.mirror import com.sun.jdi.ArrayReference import com.sun.jdi.ObjectReference import com.sun.jdi.StringReference import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext class DebugMetadata private constructor(context: DefaultExecutionContext) : BaseMirror<ObjectReference, MirrorOfDebugProbesImpl>("kotlin.coroutines.jvm.internal.DebugMetadataKt", context) { private val getStackTraceElementMethod by MethodMirrorDelegate("getStackTraceElement", StackTraceElement(context)) private val getSpilledVariableFieldMappingMethod by MethodDelegate<ArrayReference>("getSpilledVariableFieldMapping", "(Lkotlin/coroutines/jvm/internal/BaseContinuationImpl;)[Ljava/lang/String;") val baseContinuationImpl = BaseContinuationImpl(context, this) override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): MirrorOfDebugProbesImpl? = throw IllegalStateException("Not meant to be mirrored.") fun fetchContinuationStack(continuation: ObjectReference, context: DefaultExecutionContext): MirrorOfContinuationStack { val coroutineStack = mutableListOf<MirrorOfStackFrame>() var loopContinuation: ObjectReference? = continuation while (loopContinuation != null) { val continuationMirror = baseContinuationImpl.mirror(loopContinuation, context) ?: break coroutineStack.add(MirrorOfStackFrame(loopContinuation, continuationMirror)) loopContinuation = continuationMirror.nextContinuation } return MirrorOfContinuationStack(continuation, coroutineStack) } fun getStackTraceElement(value: ObjectReference, context: DefaultExecutionContext) = getStackTraceElementMethod.mirror(value, context) fun getSpilledVariableFieldMapping(value: ObjectReference, context: DefaultExecutionContext) = getSpilledVariableFieldMappingMethod.value(value, context) companion object { val log by logger fun instance(context: DefaultExecutionContext): DebugMetadata? { try { return DebugMetadata(context) } catch (e: IllegalStateException) { log.debug("Attempt to access DebugMetadata but none found.", e) } return null } } } class BaseContinuationImpl(context: DefaultExecutionContext, private val debugMetadata: DebugMetadata) : BaseMirror<ObjectReference, MirrorOfBaseContinuationImpl>("kotlin.coroutines.jvm.internal.BaseContinuationImpl", context) { private val getCompletion by MethodMirrorDelegate("getCompletion", this, "()Lkotlin/coroutines/Continuation;") override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): MirrorOfBaseContinuationImpl? { val stackTraceElementMirror = debugMetadata.getStackTraceElement(value, context) val fieldVariables = getSpilledVariableFieldMapping(value, context) val completionValue = getCompletion.value(value, context) val completion = if (completionValue != null && getCompletion.isCompatible(completionValue)) completionValue else null val coroutineOwner = if (completionValue != null && DebugProbesImplCoroutineOwner.instanceOf(completionValue)) completionValue else null return MirrorOfBaseContinuationImpl(value, stackTraceElementMirror, fieldVariables, completion, coroutineOwner) } private fun getSpilledVariableFieldMapping(value: ObjectReference, context: DefaultExecutionContext): List<FieldVariable> { val getSpilledVariableFieldMappingReference = debugMetadata.getSpilledVariableFieldMapping(value, context) ?: return emptyList() val length = getSpilledVariableFieldMappingReference.length() / 2 val fieldVariables = ArrayList<FieldVariable>() for (index in 0 until length) { val fieldVariable = getFieldVariableName(getSpilledVariableFieldMappingReference, index) ?: continue fieldVariables.add(fieldVariable) } return fieldVariables } private fun getFieldVariableName(rawSpilledVariables: ArrayReference, index: Int): FieldVariable? { val fieldName = (rawSpilledVariables.getValue(2 * index) as? StringReference)?.value() ?: return null val variableName = (rawSpilledVariables.getValue(2 * index + 1) as? StringReference)?.value() ?: return null return FieldVariable(fieldName, variableName) } }
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/mirror/debugMetadata.kt
4129989856
fun a() { when<caret> { } }
plugins/kotlin/idea/tests/testData/indentationOnNewline/controlFlowConstructions/WhenWithoutCondition.kt
1649020690
package io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders import android.view.View import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.models.dataclass.Downvoter import io.github.feelfreelinux.wykopmobilny.utils.toPrettyDate import kotlinx.android.synthetic.main.downvoters_list_item.view.* class DownvoterViewHolder(val view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) { companion object { const val BURY_REASON_DUPLICATE = 1 const val BURY_REASON_SPAM = 2 const val BURY_REASON_FAKE_INFO = 3 const val BURY_REASON_WRONG_CONTENT = 4 const val BURY_REASON_UNSUITABLE_CONTENT = 5 } fun bindView(downvoter: Downvoter) { view.authorHeaderView.setAuthorData(downvoter.author, downvoter.date.toPrettyDate()) view.reason_textview.text = when (downvoter.reason) { BURY_REASON_DUPLICATE -> view.resources.getString(R.string.reason_duplicate) BURY_REASON_SPAM -> view.resources.getString(R.string.reason_spam) BURY_REASON_FAKE_INFO -> view.resources.getString(R.string.reason_fake_info) BURY_REASON_WRONG_CONTENT -> view.resources.getString(R.string.reason_wrong_content) BURY_REASON_UNSUITABLE_CONTENT -> view.resources.getString(R.string.reason_unsuitable_content) else -> "" } } }
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/adapters/viewholders/DownvoterViewHolder.kt
947006858
// 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.configuration import com.intellij.framework.addSupport.FrameworkSupportInModuleConfigurable import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel import com.intellij.openapi.externalSystem.model.project.ProjectId import com.intellij.openapi.externalSystem.service.project.wizard.AbstractExternalModuleBuilder import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectCoreUtil import com.intellij.openapi.roots.ModifiableModelsProvider import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.kotlin.idea.core.util.toPsiFile import org.jetbrains.kotlin.idea.extensions.gradle.GradleBuildScriptSupport import org.jetbrains.kotlin.idea.extensions.gradle.RepositoryDescription import org.jetbrains.kotlin.idea.extensions.gradle.SettingsScriptBuilder import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.UserDataProperty import org.jetbrains.plugins.gradle.frameworkSupport.GradleFrameworkSupportProvider import org.jetbrains.plugins.gradle.service.project.wizard.AbstractGradleModuleBuilder import org.jetbrains.plugins.gradle.util.GradleConstants import java.io.File internal var Module.gradleModuleBuilder: AbstractExternalModuleBuilder<*>? by UserDataProperty(Key.create("GRADLE_MODULE_BUILDER")) private var Module.settingsScriptBuilder: SettingsScriptBuilder<out PsiFile>? by UserDataProperty(Key.create("SETTINGS_SCRIPT_BUILDER")) internal fun findSettingsGradleFile(module: Module): VirtualFile? { val contentEntryPath = module.gradleModuleBuilder?.contentEntryPath ?: return null if (contentEntryPath.isEmpty()) return null val contentRootDir = File(contentEntryPath) val modelContentRootDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(contentRootDir) ?: return null return modelContentRootDir.findChild(GradleConstants.SETTINGS_FILE_NAME) ?: modelContentRootDir.findChild(GradleConstants.KOTLIN_DSL_SETTINGS_FILE_NAME) ?: module.project.baseDir.findChild(GradleConstants.SETTINGS_FILE_NAME) ?: module.project.baseDir.findChild(GradleConstants.KOTLIN_DSL_SETTINGS_FILE_NAME) } class KotlinSettingsScriptBuilder(scriptFile: KtFile): SettingsScriptBuilder<KtFile>(scriptFile) { override fun addPluginRepository(repository: RepositoryDescription) { addPluginRepositoryExpression(repository.toKotlinRepositorySnippet()) } override fun buildPsiFile(project: Project): KtFile { return KtPsiFactory(project).createFile(build()) } } // Circumvent write actions and modify the file directly // TODO: Get rid of this hack when IDEA API allows manipulation of settings script similarly to the main script itself internal fun updateSettingsScript(module: Module, updater: (SettingsScriptBuilder<out PsiFile>) -> Unit) { fun createScriptBuilder(module: Module): SettingsScriptBuilder<*>? { val settingsGradleFile = findSettingsGradleFile(module)?.toPsiFile(module.project) ?: return null for (extension in GradleBuildScriptSupport.EP_NAME.extensionList) { return extension.createScriptBuilder(settingsGradleFile) ?: continue } return null } val storedSettingsBuilder = module.settingsScriptBuilder val settingsBuilder = storedSettingsBuilder ?: createScriptBuilder(module) ?: return if (storedSettingsBuilder == null) { module.settingsScriptBuilder = settingsBuilder } updater(settingsBuilder) } internal fun flushSettingsGradleCopy(module: Module) { try { val settingsFile = findSettingsGradleFile(module) val settingsScriptBuilder = module.settingsScriptBuilder if (settingsScriptBuilder != null && settingsFile != null) { // The module.project is not opened yet. // Due to optimization in ASTDelegatePsiElement.getManager() and relevant ones, // we have to take theOnlyOpenProject() for manipulations with tmp file // (otherwise file will have one parent project and its elements will have other parent project, // and we will get KT-29333 problem). // TODO: get rid of file manipulations until project is opened val project = ProjectCoreUtil.theOnlyOpenProject() ?: module.project val tmpFile = settingsScriptBuilder.buildPsiFile(project) CodeStyleManager.getInstance(project).reformat(tmpFile) VfsUtil.saveText(settingsFile, tmpFile.text) } } finally { module.gradleModuleBuilder = null module.settingsScriptBuilder = null } } class KotlinGradleFrameworkSupportInModuleConfigurable( private val model: FrameworkSupportModel, private val supportProvider: GradleFrameworkSupportProvider ) : FrameworkSupportInModuleConfigurable() { override fun createComponent() = supportProvider.createComponent() override fun addSupport( module: Module, rootModel: ModifiableRootModel, modifiableModelsProvider: ModifiableModelsProvider ) { val buildScriptData = AbstractGradleModuleBuilder.getBuildScriptData(module) if (buildScriptData != null) { val builder = model.moduleBuilder val projectId = (builder as? AbstractGradleModuleBuilder)?.projectId ?: ProjectId(null, module.name, null) try { module.gradleModuleBuilder = builder as? AbstractExternalModuleBuilder<*> supportProvider.addSupport(projectId, module, rootModel, modifiableModelsProvider, buildScriptData) } finally { flushSettingsGradleCopy(module) } } } }
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/configuration/gradleModuleBuilderUtils.kt
4226444476
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.ift.lesson.run import training.dsl.parseLessonSample object PythonRunLessonsUtils { const val demoConfigurationName = "sandbox" val demoSample = parseLessonSample(""" def find_average(value): check_input(value) result = 0 for s in value: <caret>result += <select id=1>validate_number(extract_number(remove_quotes(s)))</select> <caret id=3/>return result def prepare_values(): return ["'apple 1'", "orange 2", "'tomato 3'"] def extract_number(s): return int(<select id=2>s.split()[0]</select>) def check_input(value): if (value is None) or (len(value) == 0): raise ValueError(value) def remove_quotes(s): if len(s) > 1 and s[0] == "'" and s[-1] == "'": return s[1:-1] return s def validate_number(number): if number < 0: raise ValueError(number) return number average = find_average(prepare_values()) print("The average is ", average) """.trimIndent()) }
python/python-features-trainer/src/com/jetbrains/python/ift/lesson/run/PythonRunLessonsUtils.kt
3174775982
// 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.run import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.task.TaskData import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.module.Module import org.jetbrains.kotlin.config.KotlinFacetSettingsProvider import org.jetbrains.kotlin.idea.caches.project.isMPPModule import org.jetbrains.kotlin.idea.configuration.KotlinTargetData import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeAsciiOnly import org.jetbrains.plugins.gradle.execution.test.runner.GradleTestTasksProvider import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil import org.jetbrains.plugins.gradle.util.GradleConstants class KotlinMPPGradleTestTasksProvider : GradleTestTasksProvider { private companion object { const val TASK_NAME_SUFFIX = "Test" const val CLEAN_NAME_PREFIX = "clean" val ALLOWED_TARGETS = listOf("jvm") } override fun getTasks(module: Module): List<String> { if (!isMultiplatformTestModule(module)) { return emptyList() } val projectPath = ExternalSystemApiUtil.getExternalProjectPath(module) ?: return emptyList() val externalProjectInfo = ExternalSystemUtil.getExternalProjectInfo(module.project, GradleConstants.SYSTEM_ID, projectPath) ?: return emptyList() val moduleData = GradleProjectResolverUtil.findModule(externalProjectInfo.externalProjectStructure, projectPath) ?: return emptyList() val gradlePath = GradleProjectResolverUtil.getGradlePath(module) ?: return emptyList() val taskNamePrefix = if (gradlePath.endsWith(':')) gradlePath else "$gradlePath:" val kotlinTaskNameCandidates = ExternalSystemApiUtil.findAll(moduleData, KotlinTargetData.KEY) .filter { it.data.externalName in ALLOWED_TARGETS } .mapTo(mutableSetOf()) { it.data.externalName + TASK_NAME_SUFFIX } return ExternalSystemApiUtil.findAll(moduleData, ProjectKeys.TASK) .filter { it.data.name in kotlinTaskNameCandidates } .flatMap { getTaskNames(it.data, taskNamePrefix) } } private fun isMultiplatformTestModule(module: Module): Boolean { val settingsProvider = KotlinFacetSettingsProvider.getInstance(module.project) ?: return false val settings = settingsProvider.getInitializedSettings(module) return settings.isMPPModule && settings.isTestModule } private fun getTaskNames(task: TaskData, namePrefix: String): List<String> { val name = task.name return listOf(namePrefix + CLEAN_NAME_PREFIX + name.capitalizeAsciiOnly(), namePrefix + name) } }
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/run/KotlinMPPGradleTestTasksProvider.kt
1611263267
val p0: () -> Int = { 31 } val p1: (Int) -> Int = <warning descr="SSR">{ x -> x }</warning> val p1b: (Int) -> Int = <warning descr="SSR">{ it }</warning> val p2: (Int, Int) -> Int = { x, y -> x + y } val p3: (Int, Int, Int) -> Int = { x, y, z -> x + y + z }
plugins/kotlin/idea/tests/testData/structuralsearch/countFilter/oneLambdaParameter.kt
3490744255
// PROBLEM: none fun test(obj : Any) { if (<caret>obj is Int) {} }
plugins/kotlin/idea/tests/testData/inspectionsLocal/dfa/anyIsInt.kt
2429898523
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.asJava import com.intellij.psi.* import com.intellij.psi.impl.light.LightParameterListBuilder import org.jetbrains.kotlin.asJava.builder.LightMemberOrigin import org.jetbrains.kotlin.asJava.classes.METHOD_INDEX_FOR_GETTER import org.jetbrains.kotlin.asJava.classes.METHOD_INDEX_FOR_SETTER import org.jetbrains.kotlin.asJava.classes.lazyPub import org.jetbrains.kotlin.asJava.elements.FirLightIdentifier import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.fir.declarations.FirResolvePhase import org.jetbrains.kotlin.idea.asJava.parameters.FirLightSetterParameterForSymbol import org.jetbrains.kotlin.idea.frontend.api.isValid import org.jetbrains.kotlin.idea.frontend.api.symbols.* import org.jetbrains.kotlin.idea.util.ifTrue import org.jetbrains.kotlin.load.java.JvmAbi.getterName import org.jetbrains.kotlin.load.java.JvmAbi.setterName import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtParameter internal class FirLightAccessorMethodForSymbol( private val propertyAccessorSymbol: KtPropertyAccessorSymbol, private val containingPropertySymbol: KtPropertySymbol, lightMemberOrigin: LightMemberOrigin?, containingClass: FirLightClassBase, private val isTopLevel: Boolean, ) : FirLightMethod( lightMemberOrigin, containingClass, if (propertyAccessorSymbol is KtPropertyGetterSymbol) METHOD_INDEX_FOR_GETTER else METHOD_INDEX_FOR_SETTER ) { private val isGetter: Boolean get() = propertyAccessorSymbol is KtPropertyGetterSymbol private fun String.abiName() = if (isGetter) getterName(this) else setterName(this) private val _name: String by lazyPub { propertyAccessorSymbol.getJvmNameFromAnnotation() ?: run { val defaultName = containingPropertySymbol.name.identifier.let { if (containingClass.isAnnotationType) it else it.abiName() } containingPropertySymbol.computeJvmMethodName(defaultName, containingClass, accessorSite) } } override fun getName(): String = _name override fun hasTypeParameters(): Boolean = false override fun getTypeParameterList(): PsiTypeParameterList? = null override fun getTypeParameters(): Array<PsiTypeParameter> = PsiTypeParameter.EMPTY_ARRAY override fun isVarArgs(): Boolean = false override val kotlinOrigin: KtDeclaration? = (propertyAccessorSymbol.psi ?: containingPropertySymbol.psi) as? KtDeclaration private val accessorSite get() = if (propertyAccessorSymbol is KtPropertyGetterSymbol) AnnotationUseSiteTarget.PROPERTY_GETTER else AnnotationUseSiteTarget.PROPERTY_SETTER //TODO Fix it when KtFirConstructorValueParameterSymbol be ready private val isParameter: Boolean get() = containingPropertySymbol.psi.let { it == null || it is KtParameter } private fun computeAnnotations(isPrivate: Boolean): List<PsiAnnotation> { val nullabilityApplicable = isGetter && !isPrivate && !(isParameter && (containingClass.isAnnotationType || containingClass.isEnum)) val nullabilityType = if (nullabilityApplicable) containingPropertySymbol.annotatedType.type .getTypeNullability(containingPropertySymbol, FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE) else NullabilityType.Unknown val annotationsFromProperty = containingPropertySymbol.computeAnnotations( parent = this, nullability = nullabilityType, annotationUseSiteTarget = accessorSite, ) val annotationsFromAccessor = propertyAccessorSymbol.computeAnnotations( parent = this, nullability = NullabilityType.Unknown, annotationUseSiteTarget = null, ) return annotationsFromProperty + annotationsFromAccessor } private fun computeModifiers(): Set<String> { val isOverrideMethod = propertyAccessorSymbol.isOverride || containingPropertySymbol.isOverride val isInterfaceMethod = containingClass.isInterface val modifiers = mutableSetOf<String>() containingPropertySymbol.computeModalityForMethod( isTopLevel = isTopLevel, suppressFinal = isOverrideMethod || isInterfaceMethod, result = modifiers ) val visibility = isOverrideMethod.ifTrue { (containingClass as? FirLightClassForSymbol) ?.tryGetEffectiveVisibility(containingPropertySymbol) ?.toPsiVisibilityForMember(isTopLevel) } ?: propertyAccessorSymbol.toPsiVisibilityForMember(isTopLevel) modifiers.add(visibility) if (containingPropertySymbol.hasJvmStaticAnnotation(accessorSite)) { modifiers.add(PsiModifier.STATIC) } if (isInterfaceMethod) { modifiers.add(PsiModifier.ABSTRACT) } return modifiers } private val _modifierList: PsiModifierList by lazyPub { val modifiers = computeModifiers() val annotations = computeAnnotations(modifiers.contains(PsiModifier.PRIVATE)) FirLightClassModifierList(this, modifiers, annotations) } override fun getModifierList(): PsiModifierList = _modifierList override fun isConstructor(): Boolean = false private val _isDeprecated: Boolean by lazyPub { containingPropertySymbol.hasDeprecatedAnnotation(accessorSite) } override fun isDeprecated(): Boolean = _isDeprecated private val _identifier: PsiIdentifier by lazyPub { FirLightIdentifier(this, containingPropertySymbol) } override fun getNameIdentifier(): PsiIdentifier = _identifier private val _returnedType: PsiType? by lazyPub { if (!isGetter) return@lazyPub PsiType.VOID return@lazyPub containingPropertySymbol.annotatedType.asPsiType( context = containingPropertySymbol, parent = this@FirLightAccessorMethodForSymbol, phase = FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE ) } override fun getReturnType(): PsiType? = _returnedType override fun equals(other: Any?): Boolean = this === other || (other is FirLightAccessorMethodForSymbol && isGetter == other.isGetter && kotlinOrigin == other.kotlinOrigin && propertyAccessorSymbol == other.propertyAccessorSymbol) override fun hashCode(): Int = kotlinOrigin.hashCode() private val _parametersList by lazyPub { val builder = LightParameterListBuilder(manager, language) FirLightParameterForReceiver.tryGet(containingPropertySymbol, this)?.let { builder.addParameter(it) } val propertyParameter = (propertyAccessorSymbol as? KtPropertySetterSymbol)?.parameter if (propertyParameter != null) { builder.addParameter( FirLightSetterParameterForSymbol( parameterSymbol = propertyParameter, containingPropertySymbol = containingPropertySymbol, containingMethod = this@FirLightAccessorMethodForSymbol ) ) } builder } override fun getParameterList(): PsiParameterList = _parametersList override fun isValid(): Boolean = super.isValid() && propertyAccessorSymbol.isValid() }
plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/asJava/methods/FirLightAccessorMethodForSymbol.kt
2191118204
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* import core.windows.* val WGL_NV_gpu_affinity = "WGLNVGPUAffinity".nativeClassWGL("WGL_NV_gpu_affinity", NV) { documentation = """ Native bindings to the $registryLink extension. On systems with more than one GPU it is desirable to be able to select which GPU(s) in the system become the target for OpenGL rendering commands. This extension introduces the concept of a GPU affinity mask. OpenGL rendering commands are directed to the GPU(s) specified by the affinity mask. GPU affinity is immutable. Once set, it cannot be changed. This extension also introduces the concept called affinity-DC. An affinity-DC is a device context with a GPU affinity mask embedded in it. This restricts the device context to only allow OpenGL commands to be sent to the GPU(s) in the affinity mask. Requires ${WGL_ARB_extensions_string.link}. """ val wglMakeCurrent = "WGL#wglMakeCurrent()" val wglMakeContextCurrentARB = "#MakeContextCurrentARB()" IntConstant( "New error code set by wglShareLists, wglMakeCurrent and $wglMakeContextCurrentARB.", "ERROR_INCOMPATIBLE_AFFINITY_MASKS_NV"..0x20D0 ).noPrefix() IntConstant( "New error code set by $wglMakeCurrent and $wglMakeContextCurrentARB.", "ERROR_MISSING_AFFINITY_MASK_NV"..0x20D1 ).noPrefix() // Functions BOOL( "EnumGpusNV", """ Returns the handles for all GPUs in a system. By looping over {@code wglEnumGpusNV} and incrementing {@code gpuIndex}, starting at index 0, all GPU handles can be queried. If the function succeeds, the return value is TRUE. If the function fails, the return value is FALSE and {@code gpu} will be unmodified. The function fails if {@code gpuIndex} is greater or equal than the number of GPUs supported by the system. """, UINT("gpuIndex", "an index value that specifies a GPU"), Check(1)..HGPUNV.p("gpu", "returns a handle for GPU number {@code gpuIndex}. The first GPU will be index 0.") ) BOOL( "EnumGpuDevicesNV", "Retrieve information about the display devices supported by a GPU.", HGPUNV("gpu", "a handle to the GPU to query"), UINT("deviceIndex", "an index value that specifies a display device, supported by {@code gpu}, to query. The first display device will be index 0."), PGPU_DEVICE("gpuDevice", "a ##GPU_DEVICE structure which will receive information about the display device at index {@code deviceIndex}.") ) HDC( "CreateAffinityDCNV", """ Creates an affinity-DC. Affinity-DCs, a new type of DC, can be used to direct OpenGL commands to a specific GPU or set of GPUs. An affinity-DC is a device context with a GPU affinity mask embedded in it. This restricts the device context to only allow OpenGL commands to be sent to the GPU(s) in the affinity mask. An affinity-DC can be created directly, using the new function {@code wglCreateAffinityDCNV} and also indirectly by calling #CreatePbufferARB() followed by #GetPbufferDCARB(). If successful, the function returns an affinity-DC handle. If it fails, #NULL will be returned. """, NullTerminated..HGPUNV.const.p("gpuList", "a #NULL-terminated array of GPU handles to which the affinity-DC will be restricted") ) BOOL( "EnumGpusFromAffinityDCNV", """ Retrieves a list of GPU handles that make up the affinity-mask of an affinity-DC. By looping over {@code wglEnumGpusFromAffinityDCNV} and incrementing {@code gpuIndex}, starting at index 0, all GPU handles associated with the DC can be queried. If the function succeeds, the return value is TRUE. If the function fails, the return value is FALSE and {@code gpu} will be unmodified. The function fails if {@code gpuIndex} is greater or equal than the number of GPUs associated with {@code affinityDC}. """, HDC("affinityDC", "a handle of the affinity-DC to query"), UINT("gpuIndex", "an index value of the GPU handle in the affinity mask of {@code affinityDC} to query"), Check(1)..HGPUNV.p("gpu", "returns a handle for GPU number {@code gpuIndex}. The first GPU will be at index 0.") ) BOOL( "DeleteDCNV", "Deletes an affinity-DC.", HDC("hdc", "a handle of an affinity-DC to delete") ) }
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/WGL_NV_gpu_affinity.kt
3584608199
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.actions.navbar import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.project.DumbAware import com.intellij.ui.ExperimentalUI class NavBarLocationGroup : DefaultActionGroup(), DumbAware { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = ExperimentalUI.isNewUI() } }
platform/lang-impl/src/com/intellij/ide/actions/navbar/NavBarLocationGroup.kt
427282963
// FIR_IDENTICAL // FIR_COMPARISON class SomeType<T> fun test(a: SomeType<<caret>>) {} // WITH_ORDER // EXIST: { itemText: "SomeType" } // EXIST: { itemText: "in" } // EXIST: { itemText: "out" } // EXIST: { itemText: "suspend" }
plugins/kotlin/completion/tests/testData/basic/common/KeywordsAreLowInParameterTypeCompletion2.kt
477176298
package com.intellij.cce.core import com.google.gson.* import java.lang.reflect.Type interface TokenProperties { val tokenType: TypeProperty val location: SymbolLocation fun additionalProperty(name: String): String? fun describe(): String fun hasFeature(feature: String): Boolean fun withFeatures(features: Set<String>): TokenProperties interface Adapter<T> { fun adapt(props: TokenProperties): T? } object JsonAdapter : JsonDeserializer<TokenProperties>, JsonSerializer<TokenProperties> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): TokenProperties { return context.deserialize(json, SimpleTokenProperties::class.java) } override fun serialize(src: TokenProperties, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { return context.serialize(src) } } companion object { val UNKNOWN = SimpleTokenProperties.create(TypeProperty.UNKNOWN, SymbolLocation.UNKNOWN) {} } } object PropertyAdapters { internal const val LANGUAGE_PROPERTY = "lang" object Jvm : Base<JvmProperties>("Jvm") { override fun build(props: TokenProperties): JvmProperties = JvmProperties(props) } abstract class Base<T>(internal val language: String) : TokenProperties.Adapter<T> { final override fun adapt(props: TokenProperties): T? { return if (props.additionalProperty(LANGUAGE_PROPERTY) != language) null else build(props) } abstract fun build(props: TokenProperties): T } } class JvmProperties(private val props: TokenProperties) : TokenProperties by props { companion object { const val STATIC = "isStatic" const val PACKAGE = "packageName" const val CONTAINING_CLASS = "containingClass" fun create(tokenType: TypeProperty, location: SymbolLocation, init: Builder.() -> Unit): TokenProperties { val builder = Builder() builder.init() return SimpleTokenProperties.create(tokenType, location) { builder.isStatic?.let { put(STATIC, it.toString()) } builder.packageName?.let { put(PACKAGE, it) } builder.declaringClass?.let { put(CONTAINING_CLASS, it) } put(PropertyAdapters.LANGUAGE_PROPERTY, PropertyAdapters.Jvm.language) } } } val isStatic: Boolean? = props.additionalProperty(STATIC) == "true" val packageName: String? = props.additionalProperty(PACKAGE) val containingClass: String? = props.additionalProperty(CONTAINING_CLASS) class Builder { var isStatic: Boolean? = null var packageName: String? = null var declaringClass: String? = null } } class SimpleTokenProperties private constructor( override val tokenType: TypeProperty, override val location: SymbolLocation, private val features: MutableSet<String>, private val additional: Map<String, String> ) : TokenProperties { companion object { fun create(tokenType: TypeProperty, location: SymbolLocation, init: MutableMap<String, String>.() -> Unit): TokenProperties { val props = mutableMapOf<String, String>() props.init() return SimpleTokenProperties(tokenType, location, mutableSetOf(), props) } } override fun additionalProperty(name: String): String? { return additional[name] } override fun describe(): String { return buildString { append("tokenType=$tokenType") append(", location=$location") if (additional.isNotEmpty()) { append(additional.entries.sortedBy { it.key }.joinToString(separator = ", ", prefix = " | ")) } } } override fun hasFeature(feature: String): Boolean = features.contains(feature) override fun withFeatures(features: Set<String>): TokenProperties = SimpleTokenProperties(tokenType, location, this.features.apply { addAll(features) }, additional) } enum class SymbolLocation { PROJECT, LIBRARY, UNKNOWN } enum class TypeProperty { KEYWORD, VARIABLE, LINE, // TODO: consider constructors separately TYPE_REFERENCE, METHOD_CALL, FIELD, ARGUMENT_NAME, PARAMETER_MEMBER, UNKNOWN }
plugins/evaluation-plugin/core/src/com/intellij/cce/core/TokenProperties.kt
3515365226
// 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.fir.inspections import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.psi.PsiFile import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.analysis.api.analyse import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.inspections.KotlinOptimizeImportsQuickFix import org.jetbrains.kotlin.psi.KtFile internal class KotlinHLUnusedImportInspection : AbstractKotlinInspection() { override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<out ProblemDescriptor>? { if (file !is KtFile) return null val result = analyse(file) { analyseImports(file) } if (result.unusedImports.isEmpty()) return null val quickFixes = arrayOf(KotlinOptimizeImportsQuickFix(file)) val problems = result.unusedImports.map { importPsiElement -> manager.createProblemDescriptor( importPsiElement, KotlinBundle.message("unused.import.directive"), isOnTheFly, quickFixes, ProblemHighlightType.LIKE_UNUSED_SYMBOL ) } return problems.toTypedArray() } }
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/inspections/KotlinHLUnusedImportInspection.kt
648393681
package me.serce.solidity.lang.completion class SolMemberAccessCompletionTest : SolCompletionTestBase() { fun testEmptyCompletion() = checkCompletion(hashSetOf("doSmth"), """ contract SomeContract { function doSmth() public { } } contract Test { function doSmth(SomeContract c) { c./*caret*/ } } """) fun testFunctionCompletion() = checkCompletion(hashSetOf("doSmth3"), """ contract SomeContract { function doSmth() public { } function doSmth3() public { } } contract Test { function doSmth(SomeContract c) { c.doS/*caret*/ } } """) fun testPublicStateVarCompletion() = checkCompletion(hashSetOf("smth", "smth2"), """ contract SomeContract { uint public smth; uint public smth2; } contract Test { function doSmth(SomeContract c) { c.sm/*caret*/ } } """, strict = true) fun testOnlyPublicStateVarCompletion() = checkCompletion(hashSetOf("smthPublic1", "smthPublic2"), """ contract SomeContract { uint smth; uint public smthPublic1; uint public smthPublic2; } contract Test { function doSmth(SomeContract c) { c.sm/*caret*/ } } """, strict = true) fun testOnlyPublicFunctionCompletion() = checkCompletion(hashSetOf("doSmth1", "doSmth2"), """ contract SomeContract { function doSmthInternal() internal { } function doSmthPrivate() private { } function doSmth1() public { } function doSmth2() public { } } contract Test { function doFunc(SomeContract c) { c.doS/*caret*/ } } """, strict = true) fun testOverridesOnlyOnce() { InlineFile(""" contract BaseContract { function doSmth1() public { } } contract SomeContract is BaseContract { function doSmth1() public { } function doSmth2() public { } } contract Test { function doFunc(SomeContract c) { c.doS/*caret*/ } } """).withCaret() val variants = myFixture.completeBasic() .map { it.lookupString } .groupBy { it } .mapValues { it.value.size } assertEquals(variants["doSmth1"], 1) } }
src/test/kotlin/me/serce/solidity/lang/completion/SolMemberAccessCompletionTest.kt
1654518888
package com.chrhsmt.sisheng import android.annotation.SuppressLint import android.app.Activity import com.chrhsmt.sisheng.exception.AudioServiceException import com.chrhsmt.sisheng.point.Point import com.chrhsmt.sisheng.point.SimplePointCalculator import com.chrhsmt.sisheng.ui.Chart /** * Created by hkimura on 2017/10/30. */ class AudioServiceMock : AudioServiceInterface { private val TAG: String = "AudioServiceMock" private val activity: Activity private val chart: Chart private var isRunning: Boolean = false constructor(chart: Chart, activity: Activity) { this.activity = activity this.chart = chart } override fun startAudioRecord() { // NOP } override fun testPlay(fileName: String, path: String?, playback: Boolean, callback: Runnable?, async: Boolean, labelName: String) { this.isRunning = true } override fun debugTestPlay(fileName: String, path: String, playback: Boolean, callback: Runnable?) { } override fun attemptPlay(fileName: String) { this.isRunning = true } override fun stop() { this.isRunning = false } @Throws(AudioServiceException::class) override fun analyze() : Point { return analyze("") } @Throws(AudioServiceException::class) override fun analyze(klassName: String) : Point { this.isRunning = true Thread.sleep(1000 * 2) this.isRunning = false //throw AudioServiceException() return Point( 80, 5.0, 5.0, 1, null) } override fun clear() { // NOP } override fun clearFrequencies() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun clearTestFrequencies() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun isRunning(): Boolean { return this.isRunning } }
app/src/main/java/com/chrhsmt/sisheng/AudioServiceMock.kt
4117309150
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.semantics import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.geometry.Rect import androidx.compose.ui.layout.boundsInRoot import androidx.compose.ui.node.LayoutNode import androidx.compose.ui.node.NodeCoordinator import androidx.compose.ui.node.SemanticsModifierNode import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastMap // This part is a copy from ViewGroup#addChildrenForAccessibility. @OptIn(ExperimentalComposeUiApi::class) internal fun LayoutNode.findOneLayerOfSemanticsWrappersSortedByBounds( list: MutableList<SemanticsModifierNode> = mutableListOf() ): List<SemanticsModifierNode> { fun sortWithStrategy(holders: List<NodeLocationHolder>): List<NodeLocationHolder> { // This is gross but the least risky solution. The current comparison // strategy breaks transitivity but produces very good results. Coming // up with a new strategy requires time which we do not have, so ... return try { NodeLocationHolder.comparisonStrategy = NodeLocationHolder.ComparisonStrategy.Stripe holders.toMutableList().apply { sort() } } catch (iae: IllegalArgumentException) { // Note that in practice this occurs extremely rarely in a couple // of pathological cases. NodeLocationHolder.comparisonStrategy = NodeLocationHolder.ComparisonStrategy.Location holders.toMutableList().apply { sort() } } } if (!isAttached) { return list } val holders = ArrayList<NodeLocationHolder>() children.fastForEach { if (it.isAttached) holders.add(NodeLocationHolder(this, it)) } val sortedChildren = sortWithStrategy(holders).fastMap { it.node } sortedChildren.fastForEach { child -> val outerSemantics = child.outerSemantics if (outerSemantics != null) { list.add(outerSemantics) } else { child.findOneLayerOfSemanticsWrappersSortedByBounds(list) } } return list } internal class NodeLocationHolder internal constructor( internal val subtreeRoot: LayoutNode, internal val node: LayoutNode ) : Comparable<NodeLocationHolder> { internal companion object { internal var comparisonStrategy = ComparisonStrategy.Stripe } internal enum class ComparisonStrategy { Stripe, Location } private val location: Rect? private val layoutDirection = subtreeRoot.layoutDirection init { val subtreeRootCoordinator = subtreeRoot.innerCoordinator val coordinator = node.findCoordinatorToGetBounds() location = if (subtreeRootCoordinator.isAttached && coordinator.isAttached) { subtreeRootCoordinator.localBoundingBoxOf(coordinator) } else { null } } override fun compareTo(other: NodeLocationHolder): Int { if (location == null) { // put the unattached nodes at last. This probably can save accessibility services time. return 1 } if (other.location == null) { return -1 } if (comparisonStrategy == ComparisonStrategy.Stripe) { // First is above second. if (location.bottom - other.location.top <= 0) { return -1 } // First is below second. if (location.top - other.location.bottom >= 0) { return 1 } } // We are ordering left-to-right, top-to-bottom. if (layoutDirection == LayoutDirection.Ltr) { val leftDifference = location.left - other.location.left if (leftDifference != 0f) { return if (leftDifference < 0) -1 else 1 } } else { // RTL val rightDifference = location.right - other.location.right if (rightDifference != 0f) { return if (rightDifference < 0) 1 else -1 } } // We are ordering left-to-right, top-to-bottom. val topDifference = location.top - other.location.top if (topDifference != 0f) { return if (topDifference < 0) -1 else 1 } // Find a child of each view with different screen bounds. If we get here, node and // other.node must be attached. val view1Bounds = node.findCoordinatorToGetBounds().boundsInRoot() val view2Bounds = other.node.findCoordinatorToGetBounds().boundsInRoot() val child1 = node.findNodeByPredicateTraversal { val wrapper = it.findCoordinatorToGetBounds() wrapper.isAttached && view1Bounds != wrapper.boundsInRoot() } val child2 = other.node.findNodeByPredicateTraversal { val wrapper = it.findCoordinatorToGetBounds() wrapper.isAttached && view2Bounds != wrapper.boundsInRoot() } // Compare the children recursively if ((child1 != null) && (child2 != null)) { val childHolder1 = NodeLocationHolder(subtreeRoot, child1) val childHolder2 = NodeLocationHolder(other.subtreeRoot, child2) return childHolder1.compareTo(childHolder2) } // If only one has a child, use that one if (child1 != null) { return 1 } if (child2 != null) { return -1 } val zDifference = LayoutNode.ZComparator.compare(node, other.node) if (zDifference != 0) { return -zDifference } // Break tie somehow return node.semanticsId - other.node.semanticsId } } internal fun LayoutNode.findNodeByPredicateTraversal( predicate: (LayoutNode) -> Boolean ): LayoutNode? { if (predicate(this)) { return this } children.fastForEach { val result = it.findNodeByPredicateTraversal(predicate) if (result != null) { return result } } return null } /** * If this node has semantics, we use the semantics wrapper to get bounds. Otherwise, we use * innerCoordinator because it seems the bounds after padding is the effective content. */ @OptIn(ExperimentalComposeUiApi::class) internal fun LayoutNode.findCoordinatorToGetBounds(): NodeCoordinator { return (outerMergingSemantics ?: outerSemantics)?.node?.coordinator ?: innerCoordinator }
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/semantics/SemanticsSort.kt
1276584946
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.navigation import androidx.compose.runtime.collectAsState import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.runtime.State import androidx.navigation.NavBackStackEntry import androidx.navigation.NavController import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController /** * Creates a NavHostController that handles the adding of the [WearNavigator] * from androidx.wear.compose.navigation. */ @Composable public fun rememberSwipeDismissableNavController(): NavHostController { return rememberNavController(remember { WearNavigator() }) } /** * Gets the current navigation back stack entry as a [State]. When the given navController * changes the back stack due to a [NavController.navigate] or [NavController.popBackStack] this * will trigger a recompose and return the top entry on the back stack. * * @return state of the current back stack entry */ @Composable public fun NavController.currentBackStackEntryAsState(): State<NavBackStackEntry?> { return currentBackStackEntryFlow.collectAsState(null) }
wear/compose/compose-navigation/src/main/java/androidx/wear/compose/navigation/SwipeDismissableNavHostController.kt
4141423054
package domain.autoswipe object AutoSwipeHolder { internal lateinit var autoSwipeLauncherFactory: AutoSwipeLauncherFactory fun autoSwipeIntentFactory( autoSwipeLauncherFactory: AutoSwipeLauncherFactory) { this.autoSwipeLauncherFactory = autoSwipeLauncherFactory } }
domain/src/main/kotlin/domain/autoswipe/AutoSwipeHolder.kt
2464693502
package li.ruoshi.nextday.views import android.content.Context import android.support.v4.view.ViewPager import android.util.AttributeSet import android.view.MotionEvent class SwipeControllableViewPager @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ViewPager(context, attrs) { private var swipeEnabled: Boolean = false init { this.swipeEnabled = true } fun setSwipeEnabled(enabled: Boolean) { this.swipeEnabled = enabled } override fun onInterceptTouchEvent(event: MotionEvent): Boolean { try { return this.swipeEnabled && super.onInterceptTouchEvent(event) } catch (t: Throwable) { return false } } override fun onTouchEvent(event: MotionEvent): Boolean { return this.swipeEnabled && super.onTouchEvent(event) } }
app/src/main/kotlin/li/ruoshi/nextday/views/SwipeControllableViewPager.kt
2698863581
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.tv.tvmaterial.samples import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { App() } } }
tv/tv-material/samples/src/main/java/androidx/tv/tvmaterial/samples/MainActivity.kt
2595221030
package org.thoughtcrime.securesms.components.quotes import android.content.Context import androidx.core.content.ContextCompat import org.thoughtcrime.securesms.R enum class QuoteViewColorTheme( private val backgroundColorRes: Int, private val barColorRes: Int, private val foregroundColorRes: Int ) { INCOMING_WALLPAPER( R.color.quote_view_background_incoming_wallpaper, R.color.quote_view_bar_incoming_wallpaper, R.color.quote_view_foreground_incoming_wallpaper ), INCOMING_NORMAL( R.color.quote_view_background_incoming_normal, R.color.quote_view_bar_incoming_normal, R.color.quote_view_foreground_incoming_normal ), OUTGOING_WALLPAPER( R.color.quote_view_background_outgoing_wallpaper, R.color.quote_view_bar_outgoing_wallpaper, R.color.quote_view_foreground_outgoing_wallpaper ), OUTGOING_NORMAL( R.color.quote_view_background_outgoing_normal, R.color.quote_view_bar_outgoing_normal, R.color.quote_view_foreground_outgoing_normal ); fun getBackgroundColor(context: Context) = ContextCompat.getColor(context, backgroundColorRes) fun getBarColor(context: Context) = ContextCompat.getColor(context, barColorRes) fun getForegroundColor(context: Context) = ContextCompat.getColor(context, foregroundColorRes) companion object { @JvmStatic fun resolveTheme(isOutgoing: Boolean, isPreview: Boolean, hasWallpaper: Boolean): QuoteViewColorTheme { return when { isPreview && hasWallpaper -> INCOMING_WALLPAPER isPreview && !hasWallpaper -> INCOMING_NORMAL isOutgoing && hasWallpaper -> OUTGOING_WALLPAPER !isOutgoing && hasWallpaper -> INCOMING_WALLPAPER isOutgoing && !hasWallpaper -> OUTGOING_NORMAL else -> INCOMING_NORMAL } } } }
app/src/main/java/org/thoughtcrime/securesms/components/quotes/QuoteViewColorTheme.kt
1810519112
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.uwb import kotlinx.coroutines.flow.Flow /** Interface for client session that is established between nearby UWB devices. */ interface UwbClientSessionScope { /** * Returns a flow of [RangingResult]. Consuming the flow will initiate the UWB ranging and only * one flow can be initiated. To consume the flow from multiple consumers, * convert the flow to a SharedFlow. * * @throws [IllegalStateException] if a new flow was consumed again after the UWB * ranging is already initiated. * * @throws [androidx.core.uwb.exceptions.UwbSystemCallbackException] if the backend UWB system * has resulted in an error. * * @throws [SecurityException] if ranging does not have the * android.permission.UWB_RANGING permission. Apps must * have requested and been granted this permission before calling this method. * * @throws [IllegalArgumentException] if the client starts a ranging session * without setting complex channel and peer address. * * @throws [IllegalArgumentException] if the client starts a ranging session * with invalid config id or ranging update type. */ fun prepareSession(parameters: RangingParameters): Flow<RangingResult> /** Returns the [RangingCapabilities] which the device supports. */ val rangingCapabilities: RangingCapabilities /** * A local address can only be used for a single ranging session. After * a ranging session is ended, a new address will be allocated. * * Ranging session duration may also be limited to prevent addresses * from being used for too long. In this case, your ranging session would be * suspended and clients would need to exchange the new address with their peer * before starting again. */ val localAddress: UwbAddress }
core/uwb/uwb/src/main/java/androidx/core/uwb/UwbClientSessionScope.kt
3578141229
/* * 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.compiler.plugins.kotlin import org.intellij.lang.annotations.Language abstract class AbstractControlFlowTransformTests : AbstractIrTransformTest() { protected fun controlFlow( @Language("kotlin") source: String, expectedTransformed: String, dumpTree: Boolean = false, ) = verifyComposeIrTransform( """ import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.runtime.key import androidx.compose.runtime.NonRestartableComposable $source """.trimIndent(), expectedTransformed, """ import androidx.compose.runtime.Composable inline class InlineClass(val value: Int) fun used(x: Any?) {} @Composable fun A() {} @Composable fun A(x: Int) { } @Composable fun B(): Boolean { return true } @Composable fun B(x: Int): Boolean { return true } @Composable fun R(): Int { return 10 } @Composable fun R(x: Int): Int { return 10 } @Composable fun P(x: Int) { } @Composable fun Int.A() { } @Composable fun L(): List<Int> { return listOf(1, 2, 3) } @Composable fun W(content: @Composable () -> Unit) { content() } @Composable inline fun IW(content: @Composable () -> Unit) { content() } fun NA() { } fun NB(): Boolean { return true } fun NR(): Int { return 10 } var a = 1 var b = 2 var c = 3 """.trimIndent(), dumpTree = dumpTree, ) }
compose/compiler/compiler-hosted/integration-tests/src/test/java/androidx/compose/compiler/plugins/kotlin/AbstractControlFlowTransformTests.kt
1848795735
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.lang.jvm.JvmModifier import com.intellij.psi.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.asJava.elements.isGetter import org.jetbrains.kotlin.asJava.elements.isSetter import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.resolve.annotations.JVM_STATIC_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter @ApiStatus.Internal open class KotlinUMethod( psi: PsiMethod, final override val sourcePsi: KtDeclaration?, givenParent: UElement? ) : KotlinAbstractUElement(givenParent), UMethod, UAnchorOwner, PsiMethod by psi { constructor( psi: KtLightMethod, givenParent: UElement? ) : this(psi, getKotlinMemberOrigin(psi), givenParent) override val uastParameters: List<UParameter> by lz { fun parameterOrigin(psiParameter: PsiParameter?): KtElement? = when (psiParameter) { is KtLightElement<*, *> -> psiParameter.kotlinOrigin is UastKotlinPsiParameter -> psiParameter.ktParameter else -> null } val lightParams = psi.parameterList.parameters val receiver = receiverTypeReference ?: return@lz lightParams.map { KotlinUParameter(it, parameterOrigin(it), this) } val receiverLight = lightParams.firstOrNull() ?: return@lz emptyList() val uParameters = SmartList<UParameter>(KotlinReceiverUParameter(receiverLight, receiver, this)) lightParams.drop(1).mapTo(uParameters) { KotlinUParameter(it, parameterOrigin(it), this) } uParameters } override val psi: PsiMethod = unwrap<UMethod, PsiMethod>(psi) override val javaPsi = psi override fun getSourceElement() = sourcePsi ?: this private val kotlinOrigin = getKotlinMemberOrigin(psi.originalElement) ?: sourcePsi override fun getContainingFile(): PsiFile? { kotlinOrigin?.containingFile?.let { return it } return unwrapFakeFileForLightClass(psi.containingFile) } override fun getNameIdentifier() = UastLightIdentifier(psi, kotlinOrigin) override val uAnnotations: List<UAnnotation> by lz { // NB: we can't use sourcePsi.annotationEntries directly due to annotation use-site targets. The given `psi` as a light element, // which spans regular function, property accessors, etc., is already built with targeted annotation. baseResolveProviderService.getPsiAnnotations(psi).asSequence() .filter { if (javaPsi.hasModifier(JvmModifier.STATIC)) !isJvmStatic(it) else true } .mapNotNull { (it as? KtLightElement<*, *>)?.kotlinOrigin as? KtAnnotationEntry } .map { baseResolveProviderService.baseKotlinConverter.convertAnnotation(it, this) } .toList() } private val receiverTypeReference by lz { when (sourcePsi) { is KtCallableDeclaration -> sourcePsi is KtPropertyAccessor -> sourcePsi.property else -> null }?.receiverTypeReference } override val uastAnchor: UIdentifier? by lz { val identifierSourcePsi = when (val sourcePsi = sourcePsi) { is PsiNameIdentifierOwner -> sourcePsi.nameIdentifier is KtObjectDeclaration -> sourcePsi.getObjectKeyword() is KtPropertyAccessor -> sourcePsi.namePlaceholder else -> sourcePsi?.navigationElement } KotlinUIdentifier(nameIdentifier, identifierSourcePsi, this) } override val uastBody: UExpression? by lz { if (kotlinOrigin?.canAnalyze() != true) return@lz null // EA-137193 val bodyExpression = when (sourcePsi) { is KtFunction -> sourcePsi.bodyExpression is KtPropertyAccessor -> sourcePsi.bodyExpression is KtProperty -> when { psi is KtLightMethod && psi.isGetter -> sourcePsi.getter?.bodyExpression psi is KtLightMethod && psi.isSetter -> sourcePsi.setter?.bodyExpression else -> null } else -> null } ?: return@lz null wrapExpressionBody(this, bodyExpression) } override val returnTypeReference: UTypeReferenceExpression? by lz { (sourcePsi as? KtCallableDeclaration)?.typeReference?.let { KotlinUTypeReferenceExpression(it, this) { javaPsi.returnType ?: UastErrorType } } } companion object { fun create( psi: KtLightMethod, givenParent: UElement? ): UMethod { val kotlinOrigin = psi.kotlinOrigin return when { kotlinOrigin is KtConstructor<*> -> KotlinConstructorUMethod(kotlinOrigin.containingClassOrObject, psi, givenParent) kotlinOrigin is KtParameter && kotlinOrigin.getParentOfType<KtClass>(true)?.isAnnotation() == true -> KotlinUAnnotationMethod(psi, givenParent) else -> KotlinUMethod(psi, givenParent) } } private fun isJvmStatic(it: PsiAnnotation): Boolean = it.hasQualifiedName(JVM_STATIC_ANNOTATION_FQ_NAME.asString()) } }
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUMethod.kt
553272799
// IS_APPLICABLE: false fun test() { class Test { operator fun inc(): Test = Test() } val test = Test() test.inc<caret>() }
plugins/kotlin/idea/tests/testData/intentions/conventionNameCalls/replaceCallWithUnaryOperator/inc.kt
2427142477
// 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.debugger.test.sequence.dsl import com.intellij.debugger.streams.test.DslTestCase import com.intellij.debugger.streams.trace.dsl.impl.DslImpl import org.jetbrains.kotlin.idea.debugger.sequence.trace.dsl.KotlinCollectionsPeekCallFactory import org.jetbrains.kotlin.idea.debugger.sequence.trace.dsl.KotlinStatementFactory import org.jetbrains.kotlin.idea.base.test.KotlinRoot import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith import java.io.File @RunWith(JUnit38ClassRunner::class) class KotlinDslTest : DslTestCase(DslImpl(KotlinStatementFactory(KotlinCollectionsPeekCallFactory()))) { override fun getTestDataPath(): String { return File(KotlinRoot.DIR, "jvm-debugger/test/testData/sequence/dsl").absolutePath } }
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/sequence/dsl/KotlinDslTest.kt
909075858
// 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.jetbrains.python.testing import com.intellij.execution.ExecutionException import com.intellij.execution.ExecutionResult import com.intellij.execution.Executor import com.intellij.execution.Location import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.configurations.RunConfigurationBase import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.target.TargetEnvironment import com.intellij.execution.target.TargetEnvironmentRequest import com.intellij.execution.target.value.TargetEnvironmentFunction import com.intellij.execution.testframework.AbstractTestProxy import com.intellij.execution.testframework.actions.AbstractRerunFailedTestsAction import com.intellij.execution.testframework.sm.runner.SMTestLocator import com.intellij.openapi.application.ReadAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComponentContainer import com.intellij.openapi.util.Pair import com.intellij.openapi.util.ThrowableComputable import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.concurrency.annotations.RequiresReadLock import com.jetbrains.python.HelperPackage import com.jetbrains.python.PyBundle import com.jetbrains.python.run.AbstractPythonRunConfiguration import com.jetbrains.python.run.CommandLinePatcher import com.jetbrains.python.run.PythonScriptExecution import com.jetbrains.python.run.PythonScriptTargetedCommandLineBuilder import com.jetbrains.python.run.target.HelpersAwareTargetEnvironmentRequest import java.util.function.Function class PyRerunFailedTestsAction(componentContainer: ComponentContainer) : AbstractRerunFailedTestsAction(componentContainer) { override fun getRunProfile(environment: ExecutionEnvironment): MyRunProfile? { val model = model ?: return null return MyTestRunProfile(model.properties.configuration as AbstractPythonRunConfiguration<*>) } private inner class MyTestRunProfile(configuration: RunConfigurationBase<*>) : MyRunProfile(configuration) { override fun getModules(): Array<Module> = (peer as AbstractPythonRunConfiguration<*>).modules @Throws(ExecutionException::class) override fun getState(executor: Executor, env: ExecutionEnvironment): RunProfileState? { val configuration = peer as AbstractPythonTestRunConfiguration<*> // If configuration wants to take care about rerun itself if (configuration is TestRunConfigurationReRunResponsible) { // TODO: Extract method val failedTestElements = mutableSetOf<PsiElement>() for (proxy in getFailedTests(project)) { val location = proxy.getLocation(project, GlobalSearchScope.allScope(project)) if (location != null) { failedTestElements.add(location.psiElement) } } return (configuration as TestRunConfigurationReRunResponsible).rerunTests(executor, env, failedTestElements) } val state = configuration.getState(executor, env) ?: return null return FailedPythonTestCommandLineStateBase(configuration, env, state as PythonTestCommandLineStateBase<*>) } } private inner class FailedPythonTestCommandLineStateBase(configuration: AbstractPythonTestRunConfiguration<*>, env: ExecutionEnvironment?, private val state: PythonTestCommandLineStateBase<*>) : PythonTestCommandLineStateBase<AbstractPythonTestRunConfiguration<*>>(configuration, env) { private val project: Project init { project = configuration.project } override fun getRunner(): HelperPackage = state.runner override fun getTestLocator(): SMTestLocator? = state.testLocator @Throws(ExecutionException::class) override fun execute(executor: Executor, processStarter: PythonProcessStarter, vararg patchers: CommandLinePatcher): ExecutionResult { // Insane rerun tests with out of spec. if (testSpecs.isEmpty()) { throw ExecutionException(PyBundle.message("runcfg.tests.cant_rerun")) } return super.execute(executor, processStarter, *patchers) } @Throws(ExecutionException::class) override fun execute(executor: Executor, converter: PythonScriptTargetedCommandLineBuilder): ExecutionResult? { // Insane rerun tests with out of spec. if (testSpecs.isEmpty()) { throw ExecutionException(PyBundle.message("runcfg.tests.cant_rerun")) } return super.execute(executor, converter) } /** * *To be deprecated. The part of the legacy implementation based on [GeneralCommandLine].* */ override fun getTestSpecs(): List<String> { // Method could be called on any thread (as any method of this class), and we need read action return ReadAction.compute(ThrowableComputable<List<String>, RuntimeException> { getTestSpecImpl() }) } override fun getTestSpecs(request: TargetEnvironmentRequest): List<TargetEnvironmentFunction<String>> = ReadAction.compute(ThrowableComputable<List<TargetEnvironmentFunction<String>>, RuntimeException> { getTestSpecImpl(request) }) @RequiresReadLock private fun getTestSpecImpl(): List<String> { val failedTests = getFailedTests(project) val failedTestLocations = getTestLocations(failedTests) val result: List<String> = if (configuration is PyRerunAwareConfiguration) { (configuration as PyRerunAwareConfiguration).getTestSpecsForRerun(myConsoleProperties.scope, failedTestLocations) } else { failedTestLocations.mapNotNull { configuration.getTestSpec(it.first, it.second) } } if (result.isEmpty()) { val locations = failedTests.map { it.locationUrl } LOG.warn("Can't resolve specs for the following tests: ${locations.joinToString(separator = ", ")}") } return result } @RequiresReadLock private fun getTestSpecImpl(request: TargetEnvironmentRequest): List<TargetEnvironmentFunction<String>> { val failedTests = getFailedTests(project) val failedTestLocations = getTestLocations(failedTests) val result: List<TargetEnvironmentFunction<String>> = if (configuration is PyRerunAwareConfiguration) { (configuration as PyRerunAwareConfiguration).getTestSpecsForRerun(request, myConsoleProperties.scope, failedTestLocations) } else { failedTestLocations.mapNotNull { configuration.getTestSpec(request, it.first, it.second) } } if (result.isEmpty()) { val locations = failedTests.map { it.locationUrl } LOG.warn("Can't resolve specs for the following tests: ${locations.joinToString(separator = ", ")}") } return result } private fun getTestLocations(tests: List<AbstractTestProxy>): List<Pair<Location<*>, AbstractTestProxy>> { val testLocations = mutableListOf<Pair<Location<*>, AbstractTestProxy>>() for (test in tests) { if (test.isLeaf) { val location = test.getLocation(project, myConsoleProperties.scope) if (location != null) { testLocations.add(Pair.create(location, test)) } } } return testLocations } override fun addAfterParameters(cmd: GeneralCommandLine) { state.addAfterParameters(cmd) } override fun addBeforeParameters(cmd: GeneralCommandLine) { state.addBeforeParameters(cmd) } override fun addBeforeParameters(testScriptExecution: PythonScriptExecution) { state.addBeforeParameters(testScriptExecution) } override fun addAfterParameters(targetEnvironmentRequest: TargetEnvironmentRequest, testScriptExecution: PythonScriptExecution) { state.addAfterParameters(targetEnvironmentRequest, testScriptExecution) } override fun customizeEnvironmentVars(envs: Map<String, String>, passParentEnvs: Boolean) { super.customizeEnvironmentVars(envs, passParentEnvs) state.customizeEnvironmentVars(envs, passParentEnvs) } override fun customizePythonExecutionEnvironmentVars(helpersAwareTargetRequest: HelpersAwareTargetEnvironmentRequest, envs: Map<String, Function<TargetEnvironment, String>>, passParentEnvs: Boolean) { super.customizePythonExecutionEnvironmentVars(helpersAwareTargetRequest, envs, passParentEnvs) state.customizePythonExecutionEnvironmentVars(helpersAwareTargetRequest, envs, passParentEnvs) } } companion object { private val LOG = logger<PyRerunFailedTestsAction>() } }
python/src/com/jetbrains/python/testing/PyRerunFailedTestsAction.kt
3026295956
// PROBLEM: none val foo = "foo" val bar = <caret>"$foo$foo"
plugins/kotlin/code-insight/inspections-k2/tests/testData/inspectionsLocal/removeSingleExpressionStringTemplate/multipleStringTemplate.kt
2958646134
// 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.lang.documentation.ide.impl import com.intellij.lang.documentation.DocumentationTarget import com.intellij.lang.documentation.ide.DocumentationBrowserFacade import com.intellij.lang.documentation.ide.ui.DocumentationUI import com.intellij.lang.documentation.ide.ui.UISnapshot import com.intellij.lang.documentation.impl.DocumentationRequest import com.intellij.lang.documentation.impl.InternalLinkResult import com.intellij.model.Pointer import com.intellij.openapi.Disposable import com.intellij.openapi.application.EDT import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.roots.OrderEntry import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService import com.intellij.util.lateinitVal import kotlinx.coroutines.* import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.* import kotlin.coroutines.EmptyCoroutineContext internal class DocumentationBrowser private constructor( private val project: Project, initialPage: DocumentationPage, ) : DocumentationBrowserFacade, Disposable { var ui: DocumentationUI by lateinitVal() private sealed class BrowserRequest { class Load(val request: DocumentationRequest, val reset: Boolean) : BrowserRequest() object Reload : BrowserRequest() class Link(val url: String) : BrowserRequest() class Restore(val snapshot: HistorySnapshot) : BrowserRequest() } private val myRequestFlow: MutableSharedFlow<BrowserRequest> = MutableSharedFlow( replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST, ) private val cs = CoroutineScope(EmptyCoroutineContext) init { cs.launch(CoroutineName("DocumentationBrowser requests")) { myRequestFlow.collectLatest { handleBrowserRequest(it) } } } override fun dispose() { cs.cancel("DocumentationBrowser disposal") myHistory.clear() } fun resetBrowser(request: DocumentationRequest) { load(request, reset = true) } private fun load(request: DocumentationRequest, reset: Boolean) { check(myRequestFlow.tryEmit(BrowserRequest.Load(request, reset))) } override fun reload() { check(myRequestFlow.tryEmit(BrowserRequest.Reload)) } fun navigateByLink(url: String) { check(myRequestFlow.tryEmit(BrowserRequest.Link(url))) } private val myPageFlow = MutableStateFlow(initialPage) val pageFlow: SharedFlow<DocumentationPage> = myPageFlow.asSharedFlow() private var page: DocumentationPage get() = myPageFlow.value set(value) { myPageFlow.value = value } override val targetPointer: Pointer<out DocumentationTarget> get() = page.request.targetPointer private suspend fun handleBrowserRequest(request: BrowserRequest): Unit = when (request) { is BrowserRequest.Load -> handleLoadRequest(request.request, request.reset) is BrowserRequest.Reload -> page.loadPage() is BrowserRequest.Link -> handleLink(request.url) is BrowserRequest.Restore -> handleRestore(request.snapshot) } private suspend fun handleLoadRequest(request: DocumentationRequest, reset: Boolean) { val page = withContext(Dispatchers.EDT) { if (reset) { myHistory.clear() } else { myHistory.nextPage() } DocumentationPage(request).also { this@DocumentationBrowser.page = it } } page.loadPage() } private suspend fun handleLink(url: String) { val targetPointer = this.targetPointer val internalResult = try { handleLink(project, targetPointer, url) } catch (e: IndexNotReadyException) { return // normal situation, nothing to do } when (internalResult) { is OrderEntry -> withContext(Dispatchers.EDT) { if (internalResult.isValid) { ProjectSettingsService.getInstance(project).openLibraryOrSdkSettings(internalResult) } } InternalLinkResult.InvalidTarget -> { // TODO ? target was invalidated } InternalLinkResult.CannotResolve -> withContext(Dispatchers.EDT) { @Suppress("ControlFlowWithEmptyBody") if (!openUrl(project, targetPointer, url)) { // TODO ? can't resolve link to target & nobody can open the link } } is InternalLinkResult.Request -> { load(internalResult.request, reset = false) } is InternalLinkResult.Updater -> { page.updatePage(internalResult.updater) } } } private suspend fun handleRestore(snapshot: HistorySnapshot) { val page = snapshot.page val restored = page.restorePage(snapshot.ui) this.page = page if (!restored) { page.loadPage() } } fun currentExternalUrl(): String? { return page.currentContent?.links?.externalUrl } val history: DocumentationHistory get() = myHistory private val myHistory = DocumentationBrowserHistory(::historySnapshot, ::restore) private class HistorySnapshot( val page: DocumentationPage, val ui: UISnapshot, ) private fun historySnapshot(): HistorySnapshot { return HistorySnapshot(page, ui.uiSnapshot()) } private fun restore(snapshot: HistorySnapshot) { check(myRequestFlow.tryEmit(BrowserRequest.Restore(snapshot))) } companion object { fun createBrowser(project: Project, initialRequest: DocumentationRequest): DocumentationBrowser { val browser = DocumentationBrowser(project, DocumentationPage(request = initialRequest)) browser.reload() // init loading return browser } /** * @return `true` if a loaded page has some content, * or `false` if a loaded page is empty */ suspend fun DocumentationBrowser.waitForContent(): Boolean { return pageFlow.first().waitForContent() } } }
platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/DocumentationBrowser.kt
546662489