content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.selector import io.mockk.* import kotlinx.coroutines.* import org.junit.* import org.junit.Test import java.io.* import kotlin.test.* class ActorSelectorManagerTest { val manager = ActorSelectorManager(Dispatchers.Default) @After fun tearDown() { manager.close() } @Test fun testSelectableIsClosed(): Unit = runBlocking { val selectable: Selectable = mockk() every { selectable.interestedOps } returns SelectInterest.READ.flag every { selectable.isClosed } returns true assertFailsWith<IOException> { manager.select(selectable, SelectInterest.READ) } } @Test fun testSelectOnWrongInterest(): Unit = runBlocking { val selectable: Selectable = mockk() every { selectable.interestedOps } returns SelectInterest.READ.flag every { selectable.isClosed } returns false assertFailsWith<IllegalStateException> { manager.select(selectable, SelectInterest.WRITE) } } }
ktor-network/jvm/test/io/ktor/network/selector/ActorSelectorManagerTest.kt
3326201073
package eu.kanade.tachiyomi.widget import android.content.Context import android.util.AttributeSet import android.widget.EditText import androidx.core.view.inputmethod.EditorInfoCompat import com.google.android.material.textfield.TextInputEditText import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.util.preference.asImmediateFlow import eu.kanade.tachiyomi.widget.TachiyomiTextInputEditText.Companion.setIncognito import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.launchIn import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * A custom [TextInputEditText] that sets [EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING] to imeOptions * if [PreferencesHelper.incognitoMode] is true. Some IMEs may not respect this flag. * * @see setIncognito */ class TachiyomiTextInputEditText @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.editTextStyle ) : TextInputEditText(context, attrs, defStyleAttr) { private var scope: CoroutineScope? = null override fun onAttachedToWindow() { super.onAttachedToWindow() scope = CoroutineScope(SupervisorJob() + Dispatchers.Main) setIncognito(scope!!) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() scope?.cancel() scope = null } companion object { /** * Sets Flow to this [EditText] that sets [EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING] to imeOptions * if [PreferencesHelper.incognitoMode] is true. Some IMEs may not respect this flag. */ fun EditText.setIncognito(viewScope: CoroutineScope) { Injekt.get<PreferencesHelper>().incognitoMode().asImmediateFlow { imeOptions = if (it) { imeOptions or EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING } else { imeOptions and EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING.inv() } }.launchIn(viewScope) } } }
app/src/main/java/eu/kanade/tachiyomi/widget/TachiyomiTextInputEditText.kt
872892757
package org.jetbrains.bio.viktor import org.jetbrains.bio.npy.NpyArray import org.jetbrains.bio.npy.NpyFile import org.jetbrains.bio.npy.NpzFile import java.nio.file.Path /** Returns a view of the [NpyArray] as an n-dimensional array. */ fun NpyArray.asF64Array() = asDoubleArray().asF64Array().reshape(*shape) /** Writes a given matrix to [path] in NPY format. */ fun NpyFile.write(path: Path, a: F64Array) { val dense = if (a.isFlattenable) a else a.copy() write(path, dense.flatten().toDoubleArray(), shape = a.shape) } /** Writes a given array into an NPZ file under the specified [name]. */ fun NpzFile.Writer.write(name: String, a: F64Array) { val dense = if (a.isFlattenable) a else a.copy() write(name, dense.flatten().toDoubleArray(), shape = a.shape) }
src/main/kotlin/org/jetbrains/bio/viktor/Serialization.kt
1838172527
/* * Copyright (C) 2017 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.userprefs.density import android.content.Context import android.util.AttributeSet import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import com.doctoror.particleswallpaper.framework.di.inject import com.doctoror.particleswallpaper.framework.preference.SeekBarPreference import com.doctoror.particleswallpaper.framework.preference.SeekBarPreferenceView import org.koin.core.parameter.parametersOf class DensityPreference @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : SeekBarPreference(context, attrs, defStyle), SeekBarPreferenceView, LifecycleObserver { private val presenter: DensityPreferencePresenter by inject( context = context, parameters = { parametersOf(this as SeekBarPreferenceView) } ) init { isPersistent = false setOnPreferenceChangeListener { _, v -> presenter.onPreferenceChange(v as Int?) true } } @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onStart() { presenter.onStart() } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onStop() { presenter.onStop() } override fun setMaxInt(max: Int) { this.max = max } override fun setProgressInt(progress: Int) { this.progress = progress this.summary = (progress + 1).toString() } override fun getMaxInt() = max }
app/src/main/java/com/doctoror/particleswallpaper/userprefs/density/DensityPreference.kt
391100008
package org.fountainmc.api.world.block.plants interface DoublePlant : Plant
src/main/kotlin/org/fountainmc/api/world/block/plants/DoublePlant.kt
3914786230
package org.wikipedia.bridge import android.content.Context import org.wikipedia.BuildConfig import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.auth.AccountUtil import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.page.Namespace import org.wikipedia.page.PageTitle import org.wikipedia.page.PageViewModel import org.wikipedia.settings.Prefs import org.wikipedia.util.DimenUtil import org.wikipedia.util.DimenUtil.densityScalar import org.wikipedia.util.DimenUtil.leadImageHeightForDevice import org.wikipedia.util.L10nUtil import java.util.* import java.util.concurrent.TimeUnit import kotlin.math.roundToInt object JavaScriptActionHandler { @JvmStatic fun setTopMargin(top: Int): String { return String.format(Locale.ROOT, "pcs.c1.Page.setMargins({ top:'%dpx', right:'%dpx', bottom:'%dpx', left:'%dpx' })", top + 16, 16, 48, 16) } @JvmStatic fun getTextSelection(): String { return "pcs.c1.InteractionHandling.getSelectionInfo()" } @JvmStatic fun getOffsets(): String { return "pcs.c1.Sections.getOffsets(document.body);" } @JvmStatic fun getSections(): String { return "pcs.c1.Page.getTableOfContents()" } @JvmStatic fun getProtection(): String { return "pcs.c1.Page.getProtection()" } @JvmStatic fun getRevision(): String { return "pcs.c1.Page.getRevision();" } @JvmStatic fun expandCollapsedTables(expand: Boolean): String { return "pcs.c1.Page.expandOrCollapseTables($expand);" + "var hideableSections = document.getElementsByClassName('pcs-section-hideable-header'); " + "for (var i = 0; i < hideableSections.length; i++) { " + " pcs.c1.Sections.setHidden(hideableSections[i].parentElement.getAttribute('data-mw-section-id'), ${!expand});" + "}" } @JvmStatic fun scrollToFooter(context: Context): String { return "window.scrollTo(0, document.getElementById('pcs-footer-container-menu').offsetTop - ${DimenUtil.getNavigationBarHeight(context)});" } @JvmStatic fun scrollToAnchor(anchorLink: String): String { val anchor = if (anchorLink.contains("#")) anchorLink.substring(anchorLink.indexOf("#") + 1) else anchorLink return "var el = document.getElementById('$anchor');" + "window.scrollTo(0, el.offsetTop - (screen.height / 2));" + "setTimeout(function(){ el.style.backgroundColor='#fc3';" + " setTimeout(function(){ el.style.backgroundColor=null; }, 500);" + "}, 250);" } @JvmStatic fun prepareToScrollTo(anchorLink: String, highlight: Boolean): String { return "pcs.c1.Page.prepareForScrollToAnchor(\"${anchorLink.replace("\"", "\\\"")}\", { highlight: $highlight } )" } @JvmStatic fun setUp(context: Context, title: PageTitle, isPreview: Boolean, toolbarMargin: Int): String { val app: WikipediaApp = WikipediaApp.getInstance() val topActionBarHeight = if (isPreview) 0 else DimenUtil.roundedPxToDp(toolbarMargin.toFloat()) val res = L10nUtil.getStringsForArticleLanguage(title, intArrayOf(R.string.description_edit_add_description, R.string.table_infobox, R.string.table_other, R.string.table_close)) val leadImageHeight = if (isPreview) 0 else (if (DimenUtil.isLandscape(context) || !Prefs.isImageDownloadEnabled()) 0 else (leadImageHeightForDevice(context) / densityScalar).roundToInt() - topActionBarHeight) val topMargin = topActionBarHeight + 16 return String.format(Locale.ROOT, "{" + " \"platform\": \"android\"," + " \"clientVersion\": \"${BuildConfig.VERSION_NAME}\"," + " \"l10n\": {" + " \"addTitleDescription\": \"${res[R.string.description_edit_add_description]}\"," + " \"tableInfobox\": \"${res[R.string.table_infobox]}\"," + " \"tableOther\": \"${res[R.string.table_other]}\"," + " \"tableClose\": \"${res[R.string.table_close]}\"" + " }," + " \"theme\": \"${app.currentTheme.funnelName}\"," + " \"bodyFont\": \"${Prefs.getFontFamily()}\"," + " \"dimImages\": ${(app.currentTheme.isDark && Prefs.shouldDimDarkModeImages())}," + " \"margins\": { \"top\": \"%dpx\", \"right\": \"%dpx\", \"bottom\": \"%dpx\", \"left\": \"%dpx\" }," + " \"leadImageHeight\": \"%dpx\"," + " \"areTablesInitiallyExpanded\": ${!Prefs.isCollapseTablesEnabled()}," + " \"textSizeAdjustmentPercentage\": \"100%%\"," + " \"loadImages\": ${Prefs.isImageDownloadEnabled()}," + " \"userGroups\": \"${AccountUtil.groups}\"" + "}", topMargin, 16, 48, 16, leadImageHeight) } @JvmStatic fun setUpEditButtons(isEditable: Boolean, isProtected: Boolean): String { return "pcs.c1.Page.setEditButtons($isEditable, $isProtected)" } @JvmStatic fun setFooter(model: PageViewModel): String { if (model.page == null) { return "" } val showTalkLink = !(model.page!!.title.namespace() === Namespace.TALK) val showMapLink = model.page!!.pageProperties.geo != null val editedDaysAgo = TimeUnit.MILLISECONDS.toDays(Date().time - model.page!!.pageProperties.lastModified.time) // TODO: page-library also supports showing disambiguation ("similar pages") links and // "page issues". We should be mindful that they exist, even if we don't want them for now. val baseURL = ServiceFactory.getRestBasePath(model.title?.wikiSite!!).trimEnd('/') return "pcs.c1.Footer.add({" + " platform: \"android\"," + " clientVersion: \"${BuildConfig.VERSION_NAME}\"," + " menu: {" + " items: [" + "pcs.c1.Footer.MenuItemType.lastEdited, " + (if (showTalkLink) "pcs.c1.Footer.MenuItemType.talkPage, " else "") + (if (showMapLink) "pcs.c1.Footer.MenuItemType.coordinate, " else "") + " pcs.c1.Footer.MenuItemType.referenceList " + " ]," + " fragment: \"pcs-menu\"," + " editedDaysAgo: $editedDaysAgo" + " }," + " readMore: { " + " itemCount: 3," + " baseURL: \"$baseURL\"," + " fragment: \"pcs-read-more\"" + " }" + "})" } @JvmStatic fun mobileWebChromeShim(): String { return "(function() {" + "let style = document.createElement('style');" + "style.innerHTML = '.header-chrome { visibility: hidden; margin-top: 48px; height: 0px; } #page-secondary-actions { display: none; } .mw-footer { padding-bottom: 72px; } .page-actions-menu { display: none; } .minerva__tab-container { display: none; }';" + "document.head.appendChild(style);" + "})();" } @JvmStatic fun getElementAtPosition(x: Int, y: Int): String { return "(function() {" + " let element = document.elementFromPoint($x, $y);" + " let result = {};" + " result.left = element.getBoundingClientRect().left;" + " result.top = element.getBoundingClientRect().top;" + " result.width = element.clientWidth;" + " result.height = element.clientHeight;" + " result.src = element.src;" + " return result;" + "})();" } data class ImageHitInfo(val left: Float = 0f, val top: Float = 0f, val width: Float = 0f, val height: Float = 0f, val src: String = "", val centerCrop: Boolean = false) }
app/src/main/java/org/wikipedia/bridge/JavaScriptActionHandler.kt
4068715728
/* * * MIT License * * Copyright (c) 2017 Frederik Ar. Mikkelsen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package fredboat.commandmeta.abs /** * Created by napster on 09.11.17. * * Commands that allow guilds / users to change any kind of FredBoat settings */ interface IConfigCommand
FredBoat/src/main/java/fredboat/commandmeta/abs/IConfigCommand.kt
3983688379
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * 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 org.hisp.dhis.android.core.period import java.lang.IllegalArgumentException import java.util.* import kotlin.Throws @Suppress("MagicNumber") enum class PeriodType( val defaultStartPeriods: Int, val defaultEndPeriods: Int, val pattern: String, val sortOrder: Int ) { Daily(-59, 1, "\\b(\\d{4})(\\d{2})(\\d{2})\\b", 1), Weekly(-12, 1, "\\b(\\d{4})W(\\d[\\d]?)\\b", 2), WeeklySaturday(-12, 1, "\\b(\\d{4})SatW(\\d[\\d]?)\\b", 3), WeeklySunday(-12, 1, "\\b(\\d{4})SunW(\\d[\\d]?)\\b", 4), WeeklyThursday(-12, 1, "\\b(\\d{4})ThuW(\\d[\\d]?)\\b", 5), WeeklyWednesday(-12, 1, "\\b(\\d{4})WedW(\\d[\\d]?)\\b", 6), BiWeekly(-12, 1, "\\b(\\d{4})BiW(\\d[\\d]?)\\b", 7), Monthly(-11, 1, "\\b(\\d{4})[-]?(\\d{2})\\b", 8), BiMonthly(-5, 1, "\\b(\\d{4})(\\d{2})B\\b", 9), Quarterly(-4, 1, "\\b(\\d{4})Q(\\d)\\b", 10), SixMonthly(-4, 1, "\\b(\\d{4})S(\\d)\\b", 11), SixMonthlyApril(-4, 1, "\\b(\\d{4})AprilS(\\d)\\b", 12), SixMonthlyNov(-4, 1, "\\b(\\d{4})NovS(\\d)\\b", 13), Yearly(-4, 1, "\\b(\\d{4})\\b", 14), FinancialApril(-4, 1, "\\b(\\d{4})April\\b", 15), FinancialJuly(-4, 1, "\\b(\\d{4})July\\b", 16), FinancialOct(-4, 1, "\\b(\\d{4})Oct\\b", 17), FinancialNov(-4, 1, "\\b(\\d{4})Nov\\b", 18); companion object { @JvmStatic @Throws(IllegalArgumentException::class) fun periodTypeFromPeriodId(periodId: String): PeriodType { return values().find { periodId.matches(it.pattern.toRegex()) } ?: throw IllegalArgumentException("The period id does not match any period type") } @JvmStatic fun firstDayOfTheWeek(periodType: PeriodType?): Int { return when (periodType) { WeeklySunday -> Calendar.SUNDAY WeeklyWednesday -> Calendar.WEDNESDAY WeeklyThursday -> Calendar.THURSDAY WeeklySaturday -> Calendar.SATURDAY else -> Calendar.MONDAY } } } }
core/src/main/java/org/hisp/dhis/android/core/period/PeriodType.kt
1793600690
// FIR_IDENTICAL // FIR_COMPARISON object NamedObject fun test() { val a : Named<caret> } // EXIST: NamedObject
plugins/kotlin/completion/tests/testData/basic/common/ObjectInTypePosition.kt
2802034918
package bar fun buz() { Color.<caret> } // EXIST: RED // EXIST: GREEN // EXIST: BLUE // EXIST: values // EXIST: valueOf // NOTHING_ELSE
plugins/kotlin/completion/tests/testData/basic/multifile/EntriesOfNotImportedEnumFromKotlin/EntriesOfNotImportedEnumFromKotlin.kt
3515714991
package a fun bar(s: String) { val t: A.X = A().X("test") }
plugins/kotlin/idea/tests/testData/refactoring/move/java/moveClass/moveInnerToTop/moveNestedClassToTopLevelInTheSamePackageAndAddOuterInstance/before/a/noImports.kt
1664915223
package inlineFun1 class A<T> { fun test() = 1 inline fun myFun1(f: () -> T): T { test() return f() } }
plugins/kotlin/idea/tests/testData/internal/toolWindow/inlineFunctionBodyResolve/inlineFun1.kt
4203320826
/* * Copyright 2016 Jasmine Villadarez * * 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.jv.practice.notes.presentation.presenters import com.jv.practice.notes.domain.interactors.base.Interactor import com.jv.practice.notes.domain.model.response.Note import com.jv.practice.notes.presentation.views.NoteListView import rx.Subscriber import javax.inject.Inject class NoteListPresenter @Inject constructor(getNotes: Interactor) : Presenter<NoteListView>() { private val getNotes: Interactor = getNotes internal val getNotesSubscriber: Subscriber<List<Note>> = GetNotesSubscriber() override fun initializeView() { } override fun onViewCreated() { getNotes() } override fun onViewHidden() { } override fun onViewDestroyed() { getNotes.unsubscribe() } fun getNotes() { getNotes.execute(getNotesSubscriber as Subscriber<kotlin.Any>) } inner class GetNotesSubscriber() : Subscriber<List<Note>>() { override fun onStart() { view.showLoadingView() } override fun onCompleted() { view.hideLoadingView() } override fun onNext(notes: List<Note>) { view.renderNotes(notes) } override fun onError(p0: Throwable?) { } } }
Notes/app/src/main/kotlin/com/jv/practice/notes/presentation/presenters/NoteListPresenter.kt
1342371397
package io.github.tobyhs.weatherweight.data.adapter import java.time.LocalDate import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class LocalDateAdapterTest { private val adapter = LocalDateAdapter() @Test fun fromJson() { val date = adapter.fromJson("2022-12-30") assertThat(date.year, equalTo(2022)) assertThat(date.monthValue, equalTo(12)) assertThat(date.dayOfMonth, equalTo(30)) } @Test fun toJson() { val date = LocalDate.of(2022, 11, 25) assertThat(adapter.toJson(date), equalTo("2022-11-25")) } }
app/src/test/java/io/github/tobyhs/weatherweight/data/adapter/LocalDateAdapterTest.kt
3300172620
// 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.console import com.intellij.execution.console.LanguageConsoleImpl import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.markup.HighlighterLayer import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.console.gutter.ConsoleIndicatorRenderer import org.jetbrains.kotlin.console.gutter.ReplIcons class HistoryUpdater(private val runner: KotlinConsoleRunner) { private val consoleView: LanguageConsoleImpl by lazy { runner.consoleView as LanguageConsoleImpl } fun printNewCommandInHistory(trimmedCommandText: String): TextRange { val historyEditor = consoleView.historyViewer addLineBreakIfNeeded(historyEditor) val startOffset = historyEditor.document.textLength addCommandTextToHistoryEditor(trimmedCommandText) val endOffset = historyEditor.document.textLength addFoldingRegion(historyEditor, startOffset, endOffset, trimmedCommandText) historyEditor.markupModel.addRangeHighlighter( startOffset, endOffset, HighlighterLayer.LAST, null, HighlighterTargetArea.EXACT_RANGE ).apply { val historyMarker = if (runner.isReadLineMode) ReplIcons.READLINE_MARKER else ReplIcons.COMMAND_MARKER gutterIconRenderer = ConsoleIndicatorRenderer(historyMarker) } historyEditor.scrollingModel.scrollVertically(endOffset) return TextRange(startOffset, endOffset) } private fun addCommandTextToHistoryEditor(trimmedCommandText: String) { val consoleEditor = consoleView.consoleEditor val consoleDocument = consoleEditor.document consoleDocument.setText(trimmedCommandText) LanguageConsoleImpl.printWithHighlighting(consoleView, consoleEditor, TextRange(0, consoleDocument.textLength)) consoleView.flushDeferredText() consoleDocument.setText("") } private fun addLineBreakIfNeeded(historyEditor: EditorEx) { if (runner.isReadLineMode) return val historyDocument = historyEditor.document val historyText = historyDocument.text val textLength = historyText.length if (!historyText.endsWith('\n')) { historyDocument.insertString(textLength, "\n") if (textLength == 0) // this will work first time after 'Clear all' action runner.addGutterIndicator(historyEditor, ReplIcons.HISTORY_INDICATOR) else historyDocument.insertString(textLength + 1, "\n") } else if (!historyText.endsWith("\n\n")) { historyDocument.insertString(textLength, "\n") } } private fun addFoldingRegion(historyEditor: EditorEx, startOffset: Int, endOffset: Int, command: String) { val cmdLines = command.lines() val linesCount = cmdLines.size if (linesCount < 2) return val foldingModel = historyEditor.foldingModel foldingModel.runBatchFoldingOperation { foldingModel.addFoldRegion(startOffset, endOffset, "${cmdLines[0]} ...") } } }
plugins/kotlin/repl/src/org/jetbrains/kotlin/console/HistoryUpdater.kt
1473744641
// 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.openapi.util.TextRange import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.getDeepestSuperDeclarations import org.jetbrains.kotlin.idea.util.hasNonSuppressAnnotation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JavaDescriptorVisibilities import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import org.jetbrains.kotlin.synthetic.canBePropertyAccessor import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.types.typeUtil.makeNotNullable class KotlinRedundantOverrideInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = namedFunctionVisitor(fun(function) { val funKeyword = function.funKeyword ?: return val modifierList = function.modifierList ?: return if (!modifierList.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return if (MODIFIER_EXCLUDE_OVERRIDE.any { modifierList.hasModifier(it) }) return if (function.hasNonSuppressAnnotation) return if (function.containingClass()?.isData() == true) return val bodyExpression = function.bodyExpression ?: return val qualifiedExpression = when (bodyExpression) { is KtDotQualifiedExpression -> bodyExpression is KtBlockExpression -> { when (val body = bodyExpression.statements.singleOrNull()) { is KtReturnExpression -> body.returnedExpression is KtDotQualifiedExpression -> body.takeIf { _ -> function.typeReference.let { it == null || it.text == "Unit" } } else -> null } } else -> null } as? KtDotQualifiedExpression ?: return val superExpression = qualifiedExpression.receiverExpression as? KtSuperExpression ?: return if (superExpression.superTypeQualifier != null) return val superCallElement = qualifiedExpression.selectorExpression as? KtCallElement ?: return if (!isSameFunctionName(superCallElement, function)) return if (!isSameArguments(superCallElement, function)) return val context = function.analyze() val functionDescriptor = context[BindingContext.FUNCTION, function] ?: return val functionParams = functionDescriptor.valueParameters val superCallDescriptor = superCallElement.resolveToCall()?.resultingDescriptor ?: return val superCallFunctionParams = superCallDescriptor.valueParameters if (functionParams.size == superCallFunctionParams.size && functionParams.zip(superCallFunctionParams).any { it.first.type != it.second.type } ) return if (function.hasDerivedProperty(functionDescriptor, context)) return val overriddenDescriptors = functionDescriptor.original.overriddenDescriptors if (overriddenDescriptors.any { it is JavaMethodDescriptor && it.visibility == JavaDescriptorVisibilities.PACKAGE_VISIBILITY }) return if (overriddenDescriptors.any { it.modality == Modality.ABSTRACT }) { if (superCallDescriptor.fqNameSafe in METHODS_OF_ANY) return if (superCallDescriptor.isOverridingMethodOfAny() && !superCallDescriptor.isImplementedInContainingClass()) return } if (function.isAmbiguouslyDerived(overriddenDescriptors, context)) return val descriptor = holder.manager.createProblemDescriptor( function, TextRange(modifierList.startOffsetInParent, funKeyword.endOffset - function.startOffset), KotlinBundle.message("redundant.overriding.method"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, RedundantOverrideFix() ) holder.registerProblem(descriptor) }) private fun isSameArguments(superCallElement: KtCallElement, function: KtNamedFunction): Boolean { val arguments = superCallElement.valueArguments val parameters = function.valueParameters if (arguments.size != parameters.size) return false return arguments.zip(parameters).all { (argument, parameter) -> argument.getArgumentExpression()?.text == parameter.name } } private fun isSameFunctionName(superSelectorExpression: KtCallElement, function: KtNamedFunction): Boolean { val superCallMethodName = superSelectorExpression.getCallNameExpression()?.text ?: return false return function.name == superCallMethodName } private fun CallableDescriptor.isOverridingMethodOfAny() = (this as? CallableMemberDescriptor)?.getDeepestSuperDeclarations().orEmpty().any { it.fqNameSafe in METHODS_OF_ANY } private fun CallableDescriptor.isImplementedInContainingClass() = (containingDeclaration as? LazyClassDescriptor)?.declaredCallableMembers.orEmpty().any { it == this } private fun KtNamedFunction.hasDerivedProperty(functionDescriptor: FunctionDescriptor?, context: BindingContext): Boolean { if (functionDescriptor == null) return false val functionName = nameAsName ?: return false if (!canBePropertyAccessor(functionName.asString())) return false val functionType = functionDescriptor.returnType val isSetter = functionType?.isUnit() == true val valueParameters = valueParameters val singleValueParameter = valueParameters.singleOrNull() if (isSetter && singleValueParameter == null || !isSetter && valueParameters.isNotEmpty()) return false val propertyType = (if (isSetter) context[BindingContext.VALUE_PARAMETER, singleValueParameter]?.type else functionType)?.makeNotNullable() return SyntheticJavaPropertyDescriptor.propertyNamesByAccessorName(functionName).any { val propertyName = it.asString() containingClassOrObject?.declarations?.find { d -> d is KtProperty && d.name == propertyName && d.resolveToDescriptorIfAny()?.type?.makeNotNullable() == propertyType } != null } } private class RedundantOverrideFix : LocalQuickFix { override fun getName() = KotlinBundle.message("redundant.override.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { descriptor.psiElement.delete() } } companion object { private val MODIFIER_EXCLUDE_OVERRIDE = KtTokens.MODIFIER_KEYWORDS_ARRAY.asList() - KtTokens.OVERRIDE_KEYWORD private val METHODS_OF_ANY = listOf("equals", "hashCode", "toString").map { FqName("kotlin.Any.$it") } } } private fun KtNamedFunction.isAmbiguouslyDerived(overriddenDescriptors: Collection<FunctionDescriptor>?, context: BindingContext): Boolean { if (overriddenDescriptors == null || overriddenDescriptors.size < 2) return false // Two+ functions // At least one default in interface or abstract in class, or just something from Java if (overriddenDescriptors.any { overriddenFunction -> overriddenFunction is JavaMethodDescriptor || when ((overriddenFunction.containingDeclaration as? ClassDescriptor)?.kind) { ClassKind.CLASS -> overriddenFunction.modality == Modality.ABSTRACT ClassKind.INTERFACE -> overriddenFunction.modality != Modality.ABSTRACT else -> false } } ) return true val delegatedSuperTypeEntries = containingClassOrObject?.superTypeListEntries?.filterIsInstance<KtDelegatedSuperTypeEntry>() ?: return false if (delegatedSuperTypeEntries.isEmpty()) return false val delegatedSuperDeclarations = delegatedSuperTypeEntries.mapNotNull { entry -> context[BindingContext.TYPE, entry.typeReference]?.constructor?.declarationDescriptor } return overriddenDescriptors.any { it.containingDeclaration in delegatedSuperDeclarations } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinRedundantOverrideInspection.kt
3093556620
// "Remove 'suspend' modifier from all functions in hierarchy" "true" open class A { open fun foo() { } open fun foo(n: Int) { } } open class B : A() { override fun foo() { } override fun foo(n: Int) { } } open class B1 : A() { override fun foo() { } override fun foo(n: Int) { } } open class C : B() { override suspend fun <caret>foo() { } override fun foo(n: Int) { } } open class C1 : B() { override fun foo() { } override fun foo(n: Int) { } }
plugins/kotlin/idea/tests/testData/quickfix/removeSuspend/nonOverridden.kt
3197430575
package org.moire.ultrasonic.domain enum class PlayerState { IDLE, DOWNLOADING, PREPARING, PREPARED, STARTED, STOPPED, PAUSED, COMPLETED }
core/domain/src/main/kotlin/org/moire/ultrasonic/domain/PlayerState.kt
1541184412
fun user1(j: J<Int>) { }
java/ql/integration-tests/all-platforms/kotlin/kotlin_compiler_java_source/K.kt
205958758
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.intellij.ideabuck.actions.select import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test /** Tests [BuckKotlinTestDetector] */ class BuckKotlinTestClassDetectorTest { @Test fun testAbstractClassNotATest() { val notATestClass = MockPotentialTestClass(isAbstract = true) assertFalse(BuckKotlinTestDetector.isTestClass(notATestClass)) } @Test fun testSimpleClassNotATest() { val notATestClass = MockPotentialTestClass() assertFalse(BuckKotlinTestDetector.isTestClass(notATestClass)) } @Test fun testJUnit3TestCase() { val testClass = MockPotentialTestClass(superClass = "junit.framework.TestCase") assertTrue(BuckKotlinTestDetector.isTestClass(testClass)) } @Test fun testPrivateJUnit3TestCaseNotATest() { val notATestClass = MockPotentialTestClass(superClass = "junit.framework.TestCase", isPrivate = true) assertFalse(BuckKotlinTestDetector.isTestClass(notATestClass)) } @Test fun testAbstractJUnit3TestCaseNotATest() { val notATestClass = MockPotentialTestClass(superClass = "junit.framework.TestCase", isAbstract = true) assertFalse(BuckKotlinTestDetector.isTestClass(notATestClass)) } @Test fun testNotAccessibleJUnit3TestCaseNotATest() { val notATestClass = MockPotentialTestClass(superClass = "junit.framework.TestCase", isData = true) assertFalse(BuckKotlinTestDetector.isTestClass(notATestClass)) } @Test fun testJUnit4TestClassWithJUnitTestFunctionAnnotated() { val testClass = MockPotentialTestClass(functionAnnotations = listOf("org.junit.Test")) assertTrue(BuckKotlinTestDetector.isTestClass(testClass)) } @Test fun testJUnit4ClassWithRunWithAnnotation() { val testClass = MockPotentialTestClass(classAnnotations = listOf("org.junit.runner.RunWith")) assertTrue(BuckKotlinTestDetector.isTestClass(testClass)) } @Test fun testJUnit4TestClassWithNGTestFunctionAnnotated() { val testClass = MockPotentialTestClass(functionAnnotations = listOf("org.testng.annotations.Test")) assertTrue(BuckKotlinTestDetector.isTestClass(testClass)) } class MockPotentialTestClass( private val superClass: String = "", private val functionAnnotations: List<String> = emptyList(), private val classAnnotations: List<String> = emptyList(), private val isAbstract: Boolean = false, private val isPrivate: Boolean = false, private val isData: Boolean = false ) : PotentialTestClass { override fun hasSuperClass(superClassQualifiedName: String): Boolean { return superClass == superClassQualifiedName } override fun hasTestFunction(annotationName: String): Boolean { return functionAnnotations.contains(annotationName) } override fun hasAnnotation(annotationName: String): Boolean { return classAnnotations.contains(annotationName) } override fun isPotentialTestClass(): Boolean { return !isAbstract && !isPrivate && !isData } } }
tools/ideabuck/tests/unit/com/facebook/buck/intellij/ideabuck/actions/select/BuckKotlinTestClassDetectorTest.kt
2839630354
package com.tm.blplayer.mvp.presenter import com.tm.blplayer.listener.OnNetworkCallBackListener import com.tm.blplayer.mvp.model.BaseModel import com.tm.blplayer.mvp.model.VideoDetailModel import com.tm.blplayer.mvp.view.BaseView /** * @author wutongming * * * @description 视频详情页 * * * @since 2017/5/18 */ class VideoDetailPresenter : BasePresenter<BaseView>(), OnNetworkCallBackListener { private val mModel: BaseModel init { mModel = VideoDetailModel() } override fun requestData() { } override fun requestData(params: Map<String, String>) { mModel.requestData(params, this)?.let { addDisposable(it) } } }
app/src/main/java/com/tm/blplayer/mvp/presenter/VideoDetailPresenter.kt
3200602051
package com.elpassion.mainframerplugin.configuration import com.elpassion.mainframerplugin.common.StringsBundle import com.elpassion.mainframerplugin.util.MainframerIcons import com.intellij.execution.configurations.ConfigurationType import javax.swing.Icon class MainframerConfigurationType : ConfigurationType { override fun getDisplayName() = StringsBundle.getMessage("configuration.name") override fun getConfigurationTypeDescription() = StringsBundle.getMessage("configuration.description") override fun getIcon(): Icon = MainframerIcons.mainIcon override fun getId() = "MAINFRAMER_RUN_CONFIGURATION" override fun getConfigurationFactories() = arrayOf(MainframerConfigurationFactory(this)) }
src/main/kotlin/com/elpassion/mainframerplugin/configuration/MainframerConfigurationType.kt
1480835068
package de.ph1b.audiobook.features import android.content.Context import android.content.Intent import android.os.Bundle import android.view.ViewGroup import com.bluelinelabs.conductor.Conductor import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.Router import com.bluelinelabs.conductor.RouterTransaction import de.ph1b.audiobook.R import de.ph1b.audiobook.data.repo.BookRepository import de.ph1b.audiobook.features.bookOverview.BookOverviewController import de.ph1b.audiobook.features.bookPlaying.BookPlayController import de.ph1b.audiobook.features.bookSearch.BookSearchHandler import de.ph1b.audiobook.features.bookSearch.BookSearchParser import de.ph1b.audiobook.injection.PrefKeys import de.ph1b.audiobook.injection.appComponent import de.ph1b.audiobook.misc.PermissionHelper import de.ph1b.audiobook.misc.Permissions import de.ph1b.audiobook.misc.RouterProvider import de.ph1b.audiobook.misc.conductor.asTransaction import de.ph1b.audiobook.persistence.pref.Pref import de.ph1b.audiobook.playback.PlayerController import kotlinx.android.synthetic.main.activity_book.* import java.util.UUID import javax.inject.Inject import javax.inject.Named /** * Activity that coordinates the book shelf and play screens. */ class MainActivity : BaseActivity(), RouterProvider { private lateinit var permissionHelper: PermissionHelper private lateinit var permissions: Permissions @field:[Inject Named(PrefKeys.CURRENT_BOOK)] lateinit var currentBookIdPref: Pref<UUID> @field:[Inject Named(PrefKeys.SINGLE_BOOK_FOLDERS)] lateinit var singleBookFolderPref: Pref<Set<String>> @field:[Inject Named(PrefKeys.COLLECTION_BOOK_FOLDERS)] lateinit var collectionBookFolderPref: Pref<Set<String>> @Inject lateinit var playerController: PlayerController @Inject lateinit var repo: BookRepository @Inject lateinit var bookSearchParser: BookSearchParser @Inject lateinit var bookSearchHandler: BookSearchHandler private lateinit var router: Router override fun onCreate(savedInstanceState: Bundle?) { appComponent.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_book) permissions = Permissions(this) permissionHelper = PermissionHelper(this, permissions) router = Conductor.attachRouter(this, root, savedInstanceState) if (!router.hasRootController()) { setupRouter() } router.addChangeListener( object : ControllerChangeHandler.ControllerChangeListener { override fun onChangeStarted( to: Controller?, from: Controller?, isPush: Boolean, container: ViewGroup, handler: ControllerChangeHandler ) { from?.setOptionsMenuHidden(true) } override fun onChangeCompleted( to: Controller?, from: Controller?, isPush: Boolean, container: ViewGroup, handler: ControllerChangeHandler ) { from?.setOptionsMenuHidden(false) } } ) setupFromIntent(intent) } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) setupFromIntent(intent) } private fun setupFromIntent(intent: Intent?) { bookSearchParser.parse(intent)?.let { bookSearchHandler.handle(it) } } private fun setupRouter() { // if we should enter a book set the backstack and return early intent.getStringExtra(NI_GO_TO_BOOK) ?.let(UUID::fromString) ?.let(repo::bookById) ?.let { val bookShelf = RouterTransaction.with(BookOverviewController()) val bookPlay = BookPlayController(it.id).asTransaction() router.setBackstack(listOf(bookShelf, bookPlay), null) return } // if we should play the current book, set the backstack and return early if (intent?.action == "playCurrent") { repo.bookById(currentBookIdPref.value)?.let { val bookShelf = RouterTransaction.with(BookOverviewController()) val bookPlay = BookPlayController(it.id).asTransaction() router.setBackstack(listOf(bookShelf, bookPlay), null) playerController.play() return } } val rootTransaction = RouterTransaction.with(BookOverviewController()) router.setRoot(rootTransaction) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) this.permissions.onRequestPermissionsResult(requestCode, permissions, grantResults) } override fun provideRouter() = router override fun onStart() { super.onStart() val anyFolderSet = collectionBookFolderPref.value.size + singleBookFolderPref.value.size > 0 if (anyFolderSet) { permissionHelper.storagePermission() } } override fun onBackPressed() { if (router.backstackSize == 1) { super.onBackPressed() } else router.handleBack() } companion object { private const val NI_GO_TO_BOOK = "niGotoBook" /** Returns an intent that lets you go directly to the playback screen for a certain book **/ fun goToBookIntent(c: Context, bookId: UUID) = Intent(c, MainActivity::class.java).apply { putExtra(NI_GO_TO_BOOK, bookId.toString()) flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK } } }
app/src/main/java/de/ph1b/audiobook/features/MainActivity.kt
1688242508
// 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.quickfixes import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.codeStyle.CodeStyleManager import org.editorconfig.language.messages.EditorConfigBundle import org.editorconfig.language.psi.EditorConfigOptionValueList import org.editorconfig.language.services.EditorConfigElementFactory class EditorConfigCleanupValueListQuickFix(private val badCommas: List<PsiElement>) : LocalQuickFix { override fun getFamilyName() = EditorConfigBundle["quickfix.values.list.cleanup.description"] override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val list = descriptor.psiElement?.parent as? EditorConfigOptionValueList ?: return val manager = CodeStyleManager.getInstance(project) manager.performActionWithFormatterDisabled { badCommas.forEach(PsiElement::delete) } val factory = EditorConfigElementFactory.getInstance(project) val newValue = factory.createAnyValue(list.text) manager.reformat(newValue, true) manager.performActionWithFormatterDisabled { list.replace(newValue) } } }
plugins/editorconfig/src/org/editorconfig/language/codeinsight/quickfixes/EditorConfigCleanupValueListQuickFix.kt
1200687685
// 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.starter.report.publisher.impl import com.intellij.ide.starter.models.IDEStartResult import com.intellij.ide.starter.report.publisher.ReportPublisher import com.intellij.ide.starter.report.qodana.QodanaClient import com.intellij.ide.starter.report.sarif.TestContextToQodanaSarifMapper object QodanaTestResultPublisher : ReportPublisher { override fun publish(ideStartResult: IDEStartResult) { QodanaClient.report(TestContextToQodanaSarifMapper.map(ideStartResult)) } }
tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/report/publisher/impl/QodanaTestResultPublisher.kt
2728791659
package reactor.adapter.rxjava import io.reactivex.BackpressureStrategy import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Maybe import io.reactivex.Observable import io.reactivex.Single import reactor.core.publisher.Flux import reactor.core.publisher.Mono /** * Wraps a Flowable instance into a Flux instance, composing the micro-fusion * properties of the Flowable through. * @param <T> the value type * @return the new Flux instance */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("toFlux()", "reactor.kotlin.adapter.rxjava.toFlux")) fun <T> Flowable<T>.toFlux(): Flux<T> { return RxJava2Adapter.flowableToFlux<T>(this) } /** * Wraps a Flux instance into a Flowable instance, composing the micro-fusion * properties of the Flux through. * @param <T> the value type * @return the new Flux instance */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("toFlowable()", "reactor.kotlin.adapter.rxjava.toFlowable")) fun <T> Flux<T>.toFlowable(): Flowable<T> { return RxJava2Adapter.fluxToFlowable(this) } /** * Wraps a Mono instance into a Flowable instance, composing the micro-fusion * properties of the Flux through. * @param <T> the value type * @return the new Flux instance */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("toFlowable()", "reactor.kotlin.adapter.rxjava.toFlowable")) fun <T> Mono<T>.toFlowable(): Flowable<T> { return RxJava2Adapter.monoToFlowable<T>(this) } /** * Wraps a void-Mono instance into a RxJava Completable. * @return the new Completable instance */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("toCompletable()", "reactor.kotlin.adapter.rxjava.toCompletable")) fun Mono<*>.toCompletable(): Completable { return RxJava2Adapter.monoToCompletable(this) } /** * Wraps a RxJava Completable into a Mono instance. * @return the new Mono instance */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("toMono()", "reactor.kotlin.adapter.rxjava.toMono")) fun Completable.toMono(): Mono<Void> { return RxJava2Adapter.completableToMono(this) } /** * Wraps a Mono instance into a RxJava Single. * * If the Mono is empty, the single will signal a * [NoSuchElementException]. * @param <T> the value type * @return the new Single instance */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("toSingle()", "reactor.kotlin.adapter.rxjava.toSingle")) fun <T> Mono<T>.toSingle(): Single<T> { return RxJava2Adapter.monoToSingle(this) } /** * Wraps a RxJava Single into a Mono instance. * @param <T> the value type * @return the new Mono instance */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("toMono()", "reactor.kotlin.adapter.rxjava.toMono")) fun <T> Single<T>.toMono(): Mono<T> { return RxJava2Adapter.singleToMono<T>(this) } /** * Wraps an RxJava Observable and applies the given backpressure strategy. * @param <T> the value type * @param strategy the back-pressure strategy, default is BUFFER * @return the new Flux instance */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("toFlux(strategy)", "reactor.kotlin.adapter.rxjava.toFlux")) fun <T> Observable<T>.toFlux(strategy: BackpressureStrategy = BackpressureStrategy.BUFFER): Flux<T> { return RxJava2Adapter.observableToFlux(this, strategy) } /** * Wraps a Flux instance into a RxJava Observable. * @param <T> the value type * @return the new Observable instance */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("toObservable()", "reactor.kotlin.adapter.rxjava.toObservable")) fun <T> Flux<T>.toObservable(): Observable<T> { return RxJava2Adapter.fluxToFlowable(this).toObservable() } /** * Wraps an RxJava Maybe into a Mono instance. * @param <T> the value type * @return the new Mono instance */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("toMono()", "reactor.kotlin.adapter.rxjava.toMono")) fun <T> Maybe<T>.toMono(): Mono<T> { return RxJava2Adapter.maybeToMono(this) } /** * WRaps Mono instance into an RxJava Maybe. * @param <T> the value type * @return the new Maybe instance */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("toMaybe()", "reactor.kotlin.adapter.rxjava.toMaybe")) fun <T> Mono<T>.toMaybe(): Maybe<T> { return RxJava2Adapter.monoToMaybe(this) }
reactor-adapter/src/main/kotlin/reactor/adapter/rxjava/RxJava2AdapterExt.kt
3555937187
// 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.debugger.test import com.intellij.debugger.engine.ContextUtil import com.intellij.debugger.engine.SuspendContextImpl import com.intellij.debugger.engine.evaluation.CodeFragmentKind import com.intellij.debugger.engine.evaluation.EvaluateException import com.intellij.debugger.engine.evaluation.TextWithImportsImpl import com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilderImpl import com.intellij.debugger.impl.DebuggerContextImpl import com.intellij.debugger.impl.DebuggerContextImpl.createDebuggerContext import com.intellij.debugger.impl.DebuggerUtilsImpl import com.intellij.debugger.memory.utils.InstanceJavaValue import com.intellij.debugger.memory.utils.InstanceValueDescriptor import com.intellij.debugger.ui.impl.watch.NodeDescriptorImpl import com.intellij.execution.process.ProcessOutputTypes import com.intellij.openapi.util.io.FileUtil import com.intellij.ui.treeStructure.Tree import com.intellij.xdebugger.XDebuggerTestUtil import com.intellij.xdebugger.impl.ui.tree.ValueMarkup import com.sun.jdi.ObjectReference import org.jetbrains.eval4j.ObjectValue import org.jetbrains.eval4j.Value import org.jetbrains.eval4j.jdi.asValue import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinCodeFragmentFactory import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferences import org.jetbrains.kotlin.idea.debugger.test.util.FramePrinter import org.jetbrains.kotlin.idea.debugger.test.util.FramePrinterDelegate import org.jetbrains.kotlin.idea.debugger.test.util.KotlinOutputChecker import org.jetbrains.kotlin.idea.debugger.test.util.SteppingInstruction import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils.findLinesWithPrefixesRemoved import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils.findStringWithPrefixes import org.jetbrains.kotlin.idea.test.KotlinBaseTest import org.jetbrains.kotlin.idea.util.application.runReadAction import java.io.File import java.util.concurrent.ConcurrentHashMap import javax.swing.tree.TreeNode private data class CodeFragment(val text: String, val result: String, val kind: CodeFragmentKind) private data class DebugLabel(val name: String, val localName: String) private class EvaluationTestData( val instructions: List<SteppingInstruction>, val fragments: List<CodeFragment>, val debugLabels: List<DebugLabel> ) abstract class AbstractKotlinEvaluateExpressionTest : KotlinDescriptorTestCaseWithStepping(), FramePrinterDelegate { private companion object { private val ID_PART_REGEX = "id=[0-9]*".toRegex() } override val debuggerContext: DebuggerContextImpl get() = super.debuggerContext private var isMultipleBreakpointsTest = false private var isFrameTest = false override fun fragmentCompilerBackend() = FragmentCompilerBackend.JVM private val exceptions = ConcurrentHashMap<String, Throwable>() fun doSingleBreakpointTest(path: String) { isMultipleBreakpointsTest = false doTest(path) } fun doMultipleBreakpointsTest(path: String) { isMultipleBreakpointsTest = true doTest(path) } override fun doMultiFileTest(files: TestFiles, preferences: DebuggerPreferences) { val wholeFile = files.wholeFile val instructions = SteppingInstruction.parse(wholeFile) val expressions = loadExpressions(wholeFile) val blocks = loadCodeBlocks(files.originalFile) val debugLabels = loadDebugLabels(wholeFile) val data = EvaluationTestData(instructions, expressions + blocks, debugLabels) isFrameTest = preferences[DebuggerPreferenceKeys.PRINT_FRAME] if (isMultipleBreakpointsTest) { performMultipleBreakpointTest(data) } else { performSingleBreakpointTest(data) } } override fun tearDown() { try { exceptions.clear() } catch (e: Throwable) { addSuppressedException(e) } finally { super.tearDown() } } private fun performSingleBreakpointTest(data: EvaluationTestData) { process(data.instructions) doOnBreakpoint { createDebugLabels(data.debugLabels) for ((expression, expected, kind) in data.fragments) { mayThrow(expression) { evaluate(this, expression, kind, expected) } } printFrame(this) { resume(this) } } finish() } private fun performMultipleBreakpointTest(data: EvaluationTestData) { for ((expression, expected) in data.fragments) { doOnBreakpoint { mayThrow(expression) { try { evaluate(this, expression, CodeFragmentKind.EXPRESSION, expected) } finally { printFrame(this) { resume(this) } } } } } finish() } private fun printFrame(suspendContext: SuspendContextImpl, completion: () -> Unit) { if (!isFrameTest) { completion() return } processStackFramesOnPooledThread { for (stackFrame in this) { val result = FramePrinter(suspendContext).print(stackFrame) print(result, ProcessOutputTypes.SYSTEM) } suspendContext.invokeInManagerThread(completion) } } override fun evaluate(suspendContext: SuspendContextImpl, textWithImports: TextWithImportsImpl) { evaluate(suspendContext, textWithImports, null) } private fun evaluate(suspendContext: SuspendContextImpl, text: String, codeFragmentKind: CodeFragmentKind, expectedResult: String?) { val textWithImports = TextWithImportsImpl(codeFragmentKind, text, "", KotlinFileType.INSTANCE) return evaluate(suspendContext, textWithImports, expectedResult) } private fun evaluate(suspendContext: SuspendContextImpl, item: TextWithImportsImpl, expectedResult: String?) { val evaluationContext = this.evaluationContext val sourcePosition = ContextUtil.getSourcePosition(suspendContext) // Default test debuggerContext doesn't provide a valid stackFrame so we have to create one more for evaluation purposes. val frameProxy = suspendContext.frameProxy val threadProxy = frameProxy?.threadProxy() val debuggerContext = createDebuggerContext(myDebuggerSession, suspendContext, threadProxy, frameProxy) debuggerContext.initCaches() val contextElement = ContextUtil.getContextElement(debuggerContext)!! assert(KotlinCodeFragmentFactory().isContextAccepted(contextElement)) { val text = runReadAction { contextElement.text } "KotlinCodeFragmentFactory should be accepted for context element otherwise default evaluator will be called. " + "ContextElement = $text" } contextElement.putCopyableUserData(KotlinCodeFragmentFactory.DEBUG_CONTEXT_FOR_TESTS, debuggerContext) suspendContext.runActionInSuspendCommand { try { val evaluator = runReadAction { EvaluatorBuilderImpl.build( item, contextElement, sourcePosition, [email protected] ) } val value = evaluator.evaluate(evaluationContext) val actualResult = value.asValue().asString() if (expectedResult != null) { assertEquals( "Evaluate expression returns wrong result for ${item.text}:\n" + "expected = $expectedResult\n" + "actual = $actualResult\n", expectedResult, actualResult ) } } catch (e: EvaluateException) { val expectedMessage = e.message?.replaceFirst( ID_PART_REGEX, "id=ID" ) assertEquals( "Evaluate expression throws wrong exception for ${item.text}:\n" + "expected = $expectedResult\n" + "actual = $expectedMessage\n", expectedResult, expectedMessage ) } } } override fun logDescriptor(descriptor: NodeDescriptorImpl, text: String) { super.logDescriptor(descriptor, text) } override fun expandAll(tree: Tree, runnable: () -> Unit, filter: (TreeNode) -> Boolean, suspendContext: SuspendContextImpl) { super.expandAll(tree, runnable, HashSet(), filter, suspendContext) } private fun mayThrow(expression: String, f: () -> Unit) { try { f() } catch (e: Throwable) { exceptions[expression] = e } } override fun throwExceptionsIfAny() { super.throwExceptionsIfAny() if (exceptions.isNotEmpty()) { if (!isTestIgnored()) { for (exc in exceptions.values) { exc.printStackTrace() } val expressionsText = exceptions.entries.joinToString("\n") { (k, v) -> "expression: $k, exception: ${v.message}" } throw AssertionError("Test failed:\n$expressionsText") } else { (checker as KotlinOutputChecker).threwException = true } } } private fun Value.asString(): String { if (this is ObjectValue && this.value is ObjectReference) { return this.toString().replaceFirst(ID_PART_REGEX, "id=ID") } return this.toString() } private fun loadExpressions(testFile: KotlinBaseTest.TestFile): List<CodeFragment> { val directives = findLinesWithPrefixesRemoved(testFile.content, "// EXPRESSION: ") val expected = findLinesWithPrefixesRemoved(testFile.content, "// RESULT: ") assert(directives.size == expected.size) { "Sizes of test directives are different" } return directives.zip(expected).map { (text, result) -> CodeFragment(text, result, CodeFragmentKind.EXPRESSION) } } private fun loadCodeBlocks(wholeFile: File): List<CodeFragment> { val regexp = (Regex.escape(wholeFile.name) + ".fragment\\d*").toRegex() val fragmentFiles = wholeFile.parentFile.listFiles { _, name -> regexp.matches(name) } ?: emptyArray() val codeFragments = mutableListOf<CodeFragment>() for (fragmentFile in fragmentFiles) { val contents = FileUtil.loadFile(fragmentFile, true) val value = findStringWithPrefixes(contents, "// RESULT: ") ?: error("'RESULT' directive is missing in $fragmentFile") codeFragments += CodeFragment(contents, value, CodeFragmentKind.CODE_BLOCK) } return codeFragments } private fun loadDebugLabels(testFile: KotlinBaseTest.TestFile): List<DebugLabel> { return findLinesWithPrefixesRemoved(testFile.content, "// DEBUG_LABEL: ") .map { text -> val labelParts = text.split("=") assert(labelParts.size == 2) { "Wrong format for DEBUG_LABEL directive: // DEBUG_LABEL: {localVariableName} = {labelText}" } val localName = labelParts[0].trim() val name = labelParts[1].trim() DebugLabel(name, localName) } } private fun createDebugLabels(labels: List<DebugLabel>) { if (labels.isEmpty()) { return } val valueMarkers = DebuggerUtilsImpl.getValueMarkers(debugProcess) for ((name, localName) in labels) { val localVariable = evaluationContext.frameProxy!!.visibleVariableByName(localName) assert(localVariable != null) { "Cannot find localVariable for label: name = $localName" } val localVariableValue = evaluationContext.frameProxy!!.getValue(localVariable) as? ObjectReference assert(localVariableValue != null) { "Local variable $localName should be an ObjectReference" } // just need a wrapper XValue to pass into markValue val instanceValue = InstanceJavaValue( InstanceValueDescriptor(project, localVariableValue), evaluationContext, debugProcess.xdebugProcess?.nodeManager ) XDebuggerTestUtil.markValue(valueMarkers, instanceValue, ValueMarkup(name, null, name)) } } }
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/AbstractKotlinEvaluateExpressionTest.kt
3376423357
package com.intellij.settingsSync import com.intellij.ide.plugins.IdeaPluginDependency import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.openapi.extensions.PluginId import com.intellij.settingsSync.plugins.SettingsSyncPluginInstaller import java.nio.file.Path import java.util.* class TestPluginInstaller : SettingsSyncPluginInstaller { val installedPluginIds = HashSet<String>() override fun installPlugins(pluginsToInstall: List<PluginId>) { installedPluginIds += pluginsToInstall.map { it.idString } } } class TestPluginDependency(private val idString: String, override val isOptional: Boolean) : IdeaPluginDependency { override val pluginId get() = PluginId.getId(idString) } data class TestPluginDescriptor(val idString: String, var pluginDependencies: List<TestPluginDependency> = emptyList()) : IdeaPluginDescriptor { private var _enabled = true private val _pluginId = PluginId.getId(idString) override fun getPluginId(): PluginId = _pluginId override fun getPluginClassLoader() = classLoader override fun getPluginPath(): Path { throw UnsupportedOperationException("Not supported") } // region non-essential methods override fun getDescription(): String? = null override fun getChangeNotes(): String? = null override fun getName(): String = "Test plugin name" override fun getProductCode(): String? = null override fun getReleaseDate(): Date? = null override fun getReleaseVersion(): Int = 1 override fun isLicenseOptional(): Boolean = true @Deprecated("Deprecated in Java") override fun getOptionalDependentPluginIds(): Array<PluginId> = PluginId.EMPTY_ARRAY override fun getVendor(): String? = null override fun getVersion(): String = "1.0" override fun getResourceBundleBaseName(): String? = null override fun getCategory(): String? = null override fun getVendorEmail(): String? = null override fun getVendorUrl(): String? = null override fun getUrl(): String? = null override fun getSinceBuild(): String? = null override fun getUntilBuild(): String? = null // endregion override fun isEnabled(): Boolean = _enabled override fun setEnabled(enabled: Boolean) { _enabled = enabled } override fun getDependencies(): MutableList<IdeaPluginDependency> = pluginDependencies.toMutableList() override fun getDescriptorPath(): String? = null }
plugins/settings-sync/tests/com/intellij/settingsSync/SettingsSyncPluginManagerTestUtil.kt
1837822548
open class A { open fun <caret>f() {} } class B : A() { override fun f() {} }
plugins/kotlin/kotlin.searching/testData/inheritorsSearch/kotlinFunction/withJavaInheritor.kt
2658805394
package xyz.swagbot.extensions import com.sedmelluq.discord.lavaplayer.track.* import discord4j.common.util.* import discord4j.core.`object`.entity.* import discord4j.core.`object`.entity.channel.* import xyz.swagbot.features.music.* val AudioTrack.context: TrackContext get() = getUserData(TrackContext::class.java) fun AudioTrack.setTrackContext(member: Member, channel: MessageChannel) = setTrackContext(member.id, channel.id) fun AudioTrack.setTrackContext(memberId: Snowflake, channelId: Snowflake) { userData = TrackContext(memberId, channelId) } val AudioTrack.formattedPosition: String get() = getFormattedTime(position/1000) val AudioTrack.formattedLength: String get() = getFormattedTime(duration/1000)
src/main/kotlin/extensions/AudioTrack.kt
2093193070
@Deprecated("Use A instead") interface MyInterface { } fun test() { val a: <warning descr="[DEPRECATION] 'MyInterface' is deprecated. Use A instead">MyInterface</warning>? = null val b: List<<warning descr="[DEPRECATION] 'MyInterface' is deprecated. Use A instead">MyInterface</warning>>? = null a == b } class Test(): <warning descr="[DEPRECATION] 'MyInterface' is deprecated. Use A instead">MyInterface</warning> { } class Test2(<warning descr="[UNUSED_PARAMETER] Parameter 'param' is never used">param</warning>: <warning descr="[DEPRECATION] 'MyInterface' is deprecated. Use A instead">MyInterface</warning>) {} // NO_CHECK_INFOS // NO_CHECK_WEAK_WARNINGS
plugins/kotlin/idea/tests/testData/highlighter/deprecated/Interface.kt
194274727
// 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.quickfix.createFromUsage.createCallable import com.intellij.util.SmartList import org.jetbrains.kotlin.builtins.ReflectionTypes import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.VariableAccessorDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptorWithAccessors import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.util.OperatorNameConventions object CreatePropertyDelegateAccessorsActionFactory : CreateCallableMemberFromUsageFactory<KtExpression>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtExpression? { return diagnostic.psiElement as? KtExpression } override fun extractFixData(element: KtExpression, diagnostic: Diagnostic): List<CallableInfo> { val context = element.analyze() fun isApplicableForAccessor(accessor: VariableAccessorDescriptor?): Boolean = accessor != null && context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, accessor] == null val property = element.getNonStrictParentOfType<KtProperty>() ?: return emptyList() val propertyDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, property] as? VariableDescriptorWithAccessors ?: return emptyList() if (propertyDescriptor is LocalVariableDescriptor && !element.languageVersionSettings.supportsFeature(LanguageFeature.LocalDelegatedProperties) ) { return emptyList() } val propertyReceiver = propertyDescriptor.extensionReceiverParameter ?: propertyDescriptor.dispatchReceiverParameter val propertyType = propertyDescriptor.type val accessorReceiverType = TypeInfo(element, Variance.IN_VARIANCE) val builtIns = propertyDescriptor.builtIns val thisRefParam = ParameterInfo(TypeInfo(propertyReceiver?.type ?: builtIns.nullableNothingType, Variance.IN_VARIANCE)) val kPropertyStarType = ReflectionTypes.createKPropertyStarType(propertyDescriptor.module) ?: return emptyList() val metadataParam = ParameterInfo(TypeInfo(kPropertyStarType, Variance.IN_VARIANCE), "property") val callableInfos = SmartList<CallableInfo>() val psiFactory = KtPsiFactory(element.project) if (isApplicableForAccessor(propertyDescriptor.getter)) { val getterInfo = FunctionInfo( name = OperatorNameConventions.GET_VALUE.asString(), receiverTypeInfo = accessorReceiverType, returnTypeInfo = TypeInfo(propertyType, Variance.OUT_VARIANCE), parameterInfos = listOf(thisRefParam, metadataParam), modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD) ) callableInfos.add(getterInfo) } if (propertyDescriptor.isVar && isApplicableForAccessor(propertyDescriptor.setter)) { val newValueParam = ParameterInfo(TypeInfo(propertyType, Variance.IN_VARIANCE)) val setterInfo = FunctionInfo( name = OperatorNameConventions.SET_VALUE.asString(), receiverTypeInfo = accessorReceiverType, returnTypeInfo = TypeInfo(builtIns.unitType, Variance.OUT_VARIANCE), parameterInfos = listOf(thisRefParam, metadataParam, newValueParam), modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD) ) callableInfos.add(setterInfo) } return callableInfos } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreatePropertyDelegateAccessorsActionFactory.kt
2582353968
package com.github.vhromada.catalog.repository import com.github.vhromada.catalog.domain.Movie import com.github.vhromada.catalog.domain.io.MediaStatistics import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Query import org.springframework.data.querydsl.QuerydslPredicateExecutor import java.util.Optional /** * An interface represents repository for movies. * * @author Vladimir Hromada */ interface MovieRepository : JpaRepository<Movie, Int>, QuerydslPredicateExecutor<Movie> { /** * Finds movie by UUID. * * @param uuid UUID * @return movie */ fun findByUuid(uuid: String): Optional<Movie> /** * Returns statistics for media. * * @return statistics for media */ @Query("SELECT new com.github.vhromada.catalog.domain.io.MediaStatistics(COUNT(m.id), SUM(m.length)) FROM Medium m") fun getMediaStatistics(): MediaStatistics }
core/src/main/kotlin/com/github/vhromada/catalog/repository/MovieRepository.kt
340551648
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.concurrency import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Getter import com.intellij.util.Consumer import com.intellij.util.Function import org.jetbrains.concurrency.Promise.State import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import java.util.concurrent.atomic.AtomicReference private val LOG = Logger.getInstance(AsyncPromise::class.java) open class AsyncPromise<T> : Promise<T>, Getter<T> { private val doneRef = AtomicReference<Consumer<in T>?>() private val rejectedRef = AtomicReference<Consumer<in Throwable>?>() private val stateRef = AtomicReference(State.PENDING) // result object or error message @Volatile private var result: Any? = null override fun getState() = stateRef.get()!! override fun done(done: Consumer<in T>): Promise<T> { setHandler(doneRef, done, State.FULFILLED) return this } override fun rejected(rejected: Consumer<Throwable>): Promise<T> { setHandler(rejectedRef, rejected, State.REJECTED) return this } @Suppress("UNCHECKED_CAST") override fun get() = if (state == State.FULFILLED) result as T? else null override fun <SUB_RESULT> then(handler: Function<in T, out SUB_RESULT>): Promise<SUB_RESULT> { @Suppress("UNCHECKED_CAST") when (state) { State.PENDING -> { } State.FULFILLED -> return DonePromise<SUB_RESULT>(handler.`fun`(result as T?)) State.REJECTED -> return rejectedPromise(result as Throwable) } val promise = AsyncPromise<SUB_RESULT>() addHandlers(Consumer({ result -> promise.catchError { if (handler is Obsolescent && handler.isObsolete) { promise.cancel() } else { promise.setResult(handler.`fun`(result)) } } }), Consumer({ promise.setError(it) })) return promise } override fun notify(child: AsyncPromise<in T>) { LOG.assertTrue(child !== this) when (state) { State.PENDING -> { addHandlers(Consumer({ child.catchError { child.setResult(it) } }), Consumer({ child.setError(it) })) } State.FULFILLED -> { @Suppress("UNCHECKED_CAST") child.setResult(result as T) } State.REJECTED -> { child.setError((result as Throwable?)!!) } } } override fun <SUB_RESULT> thenAsync(handler: Function<in T, Promise<SUB_RESULT>>): Promise<SUB_RESULT> { @Suppress("UNCHECKED_CAST") when (state) { State.PENDING -> { } State.FULFILLED -> return handler.`fun`(result as T?) State.REJECTED -> return rejectedPromise(result as Throwable) } val promise = AsyncPromise<SUB_RESULT>() val rejectedHandler = Consumer<Throwable>({ promise.setError(it) }) addHandlers(Consumer({ promise.catchError { handler.`fun`(it) .done { promise.catchError { promise.setResult(it) } } .rejected(rejectedHandler) } }), rejectedHandler) return promise } override fun processed(fulfilled: AsyncPromise<in T>): Promise<T> { when (state) { State.PENDING -> { addHandlers(Consumer({ result -> fulfilled.catchError { fulfilled.setResult(result) } }), Consumer({ fulfilled.setError(it) })) } State.FULFILLED -> { @Suppress("UNCHECKED_CAST") fulfilled.setResult(result as T) } State.REJECTED -> { fulfilled.setError((result as Throwable?)!!) } } return this } private fun addHandlers(done: Consumer<T>, rejected: Consumer<Throwable>) { setHandler(doneRef, done, State.FULFILLED) setHandler(rejectedRef, rejected, State.REJECTED) } fun setResult(result: T?) { if (!stateRef.compareAndSet(State.PENDING, State.FULFILLED)) { return } this.result = result val done = doneRef.getAndSet(null) rejectedRef.set(null) if (done != null && !isObsolete(done)) { done.consume(result) } } fun setError(error: String) = setError(createError(error)) fun cancel() { setError(OBSOLETE_ERROR) } open fun setError(error: Throwable): Boolean { if (!stateRef.compareAndSet(State.PENDING, State.REJECTED)) { LOG.errorIfNotMessage(error) return false } result = error val rejected = rejectedRef.getAndSet(null) doneRef.set(null) if (rejected == null) { LOG.errorIfNotMessage(error) } else if (!isObsolete(rejected)) { rejected.consume(error) } return true } override fun processed(processed: Consumer<in T>): Promise<T> { done(processed) rejected { processed.consume(null) } return this } override fun blockingGet(timeout: Int, timeUnit: TimeUnit): T? { if (isPending) { val latch = CountDownLatch(1) processed { latch.countDown() } if (!latch.await(timeout.toLong(), timeUnit)) { throw TimeoutException() } } @Suppress("UNCHECKED_CAST") if (isRejected) { throw (result as Throwable) } else { return result as T? } } private fun <T> setHandler(ref: AtomicReference<Consumer<in T>?>, newConsumer: Consumer<in T>, targetState: State) { if (isObsolete(newConsumer)) { return } if (state != State.PENDING) { if (state == targetState) { @Suppress("UNCHECKED_CAST") newConsumer.consume(result as T?) } return } while (true) { val oldConsumer = ref.get() val newEffectiveConsumer = when (oldConsumer) { null -> newConsumer is CompoundConsumer<*> -> { @Suppress("UNCHECKED_CAST") val compoundConsumer = oldConsumer as CompoundConsumer<T> var executed = true synchronized(compoundConsumer) { compoundConsumer.consumers?.let { it.add(newConsumer) executed = false } } // clearHandlers was called - just execute newConsumer if (executed) { if (state == targetState) { @Suppress("UNCHECKED_CAST") newConsumer.consume(result as T?) } return } compoundConsumer } else -> CompoundConsumer(oldConsumer, newConsumer) } if (ref.compareAndSet(oldConsumer, newEffectiveConsumer)) { break } } if (state == targetState) { ref.getAndSet(null)?.let { @Suppress("UNCHECKED_CAST") it.consume(result as T?) } } } } private class CompoundConsumer<T>(c1: Consumer<in T>, c2: Consumer<in T>) : Consumer<T> { var consumers: MutableList<Consumer<in T>>? = ArrayList() init { synchronized(this) { consumers!!.add(c1) consumers!!.add(c2) } } override fun consume(t: T) { val list = synchronized(this) { val list = consumers consumers = null list } ?: return for (consumer in list) { if (!isObsolete(consumer)) { consumer.consume(t) } } } } internal fun isObsolete(consumer: Consumer<*>?) = consumer is Obsolescent && consumer.isObsolete inline fun <T> AsyncPromise<*>.catchError(runnable: () -> T): T? { try { return runnable() } catch (e: Throwable) { setError(e) return null } }
platform/projectModel-api/src/org/jetbrains/concurrency/AsyncPromise.kt
1378525757
package com.foebalapp.backend.security import org.springframework.context.annotation.Configuration import org.springframework.web.context.request.RequestContextListener import javax.servlet.ServletRequestEvent // This class exists to stop the Web autoconfig from registering // the RequestContextFilter. @Configuration class HoaxRequestContextListener : RequestContextListener() { override fun requestInitialized(requestEvent: ServletRequestEvent) { // Do nothing } override fun requestDestroyed(requestEvent: ServletRequestEvent) { // Do nothing } }
backend/src/main/kotlin/com/foebalapp/backend/security/HoaxRequestContextListener.kt
647883751
package io.github.chrislo27.rhre3.entity.model interface IEditableText { var text: String val canInputNewlines: Boolean get() = false }
core/src/main/kotlin/io/github/chrislo27/rhre3/entity/model/IEditableText.kt
4069554904
enum class MeetupSchedule { FIRST, SECOND, THIRD, FOURTH, LAST, TEENTH }
exercises/practice/meetup/src/main/kotlin/MeetupSchedule.kt
63882904
package com.github.droibit.plugin.truth.postfix.example import com.google.common.truth.Truth.assertThat import org.junit.Test /** * @author kumagai */ class TruthPostfixTest { private val field = 100 @Test fun assertThatWithInt() { val actual = 100 assertThat(actual).isEqualTo(100) } @Test fun assertThatWithIntField() { assertThat(field).isEqualTo(100) } @Test fun assertThatWithIntLiteral() { assertThat(100).isEqualTo(100) } @Test fun assertThatWithFloat() { val actual = 100f assertThat(actual).isWithin(100f) } @Test fun assertThatWithDouble() { val actual = 100.0 assertThat(actual).isWithin(100.0) } @Test fun assertThatWithStringMethod() { val actual = "hoge" assertThat(actual.isNotEmpty()).isTrue() } @Test fun assertThatWithDefinedClass() { class Foo(val value: Int) val foo = Foo(value = 100) assertThat(foo).isNotNull() } }
example-kotlin/src/test/kotlin/com/github/droibit/plugin/truth/postfix/example/TruthPostfixTest.kt
985896498
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.ex import com.intellij.diff.util.DiffUtil import com.intellij.diff.util.Side import com.intellij.ide.GeneralSettings import com.intellij.ide.lightEdit.LightEditCompatible import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.markup.MarkupEditorFilter import com.intellij.openapi.editor.markup.MarkupEditorFilterFactory import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.ex.DocumentTracker.Block import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.concurrency.annotations.RequiresEdt import org.jetbrains.annotations.CalledInAny import java.awt.Point import java.util.* interface LineStatusTracker<out R : Range> : LineStatusTrackerI<R> { override val project: Project override val virtualFile: VirtualFile @RequiresEdt fun isAvailableAt(editor: Editor): Boolean { return editor.settings.isLineMarkerAreaShown && !DiffUtil.isDiffEditor(editor) } @RequiresEdt fun scrollAndShowHint(range: Range, editor: Editor) @RequiresEdt fun showHint(range: Range, editor: Editor) } interface LocalLineStatusTracker<R : Range> : LineStatusTracker<R> { fun release() @CalledInAny fun freeze() @CalledInAny fun unfreeze() var mode: Mode class Mode(val isVisible: Boolean, val showErrorStripeMarkers: Boolean, val detectWhitespaceChangedLines: Boolean) @RequiresEdt override fun isAvailableAt(editor: Editor): Boolean { return mode.isVisible && super.isAvailableAt(editor) } } abstract class LocalLineStatusTrackerImpl<R : Range>( final override val project: Project, document: Document, final override val virtualFile: VirtualFile ) : LineStatusTrackerBase<R>(project, document), LocalLineStatusTracker<R> { abstract override val renderer: LocalLineStatusMarkerRenderer private val innerRangesHandler = MyInnerRangesDocumentTrackerHandler() override var mode: LocalLineStatusTracker.Mode = LocalLineStatusTracker.Mode(true, true, false) set(value) { if (value == mode) return field = value innerRangesHandler.resetInnerRanges() updateHighlighters() } init { documentTracker.addHandler(LocalDocumentTrackerHandler()) documentTracker.addHandler(innerRangesHandler) } @RequiresEdt override fun isDetectWhitespaceChangedLines(): Boolean = mode.isVisible && mode.detectWhitespaceChangedLines override fun isClearLineModificationFlagOnRollback(): Boolean = true protected abstract var Block.innerRanges: List<Range.InnerRange>? @RequiresEdt abstract fun setBaseRevision(vcsContent: CharSequence) override fun scrollAndShowHint(range: Range, editor: Editor) { renderer.scrollAndShow(editor, range) } override fun showHint(range: Range, editor: Editor) { renderer.showAfterScroll(editor, range) } protected open class LocalLineStatusMarkerRenderer(open val tracker: LocalLineStatusTrackerImpl<*>) : LineStatusMarkerPopupRenderer(tracker) { override fun getEditorFilter(): MarkupEditorFilter? = MarkupEditorFilterFactory.createIsNotDiffFilter() override fun shouldPaintGutter(): Boolean { return tracker.mode.isVisible } override fun shouldPaintErrorStripeMarkers(): Boolean { return tracker.mode.isVisible && tracker.mode.showErrorStripeMarkers } override fun createToolbarActions(editor: Editor, range: Range, mousePosition: Point?): List<AnAction> { val actions = ArrayList<AnAction>() actions.add(ShowPrevChangeMarkerAction(editor, range)) actions.add(ShowNextChangeMarkerAction(editor, range)) actions.add(RollbackLineStatusRangeAction(editor, range)) actions.add(ShowLineStatusRangeDiffAction(editor, range)) actions.add(CopyLineStatusRangeAction(editor, range)) actions.add(ToggleByWordDiffAction(editor, range, mousePosition)) return actions } private inner class RollbackLineStatusRangeAction(editor: Editor, range: Range) : RangeMarkerAction(editor, range, IdeActions.SELECTED_CHANGES_ROLLBACK), LightEditCompatible { override fun isEnabled(editor: Editor, range: Range): Boolean = true override fun actionPerformed(editor: Editor, range: Range) { RollbackLineStatusAction.rollback(tracker, range, editor) } } } private inner class LocalDocumentTrackerHandler : DocumentTracker.Handler { override fun afterBulkRangeChange(isDirty: Boolean) { if (blocks.isEmpty()) { fireFileUnchanged() } } @RequiresEdt private fun fireFileUnchanged() { if (GeneralSettings.getInstance().isSaveOnFrameDeactivation) { // later to avoid saving inside document change event processing and deadlock with CLM. ApplicationManager.getApplication().invokeLater(Runnable { FileDocumentManager.getInstance().saveDocument(document) }, project.disposed) } } } private inner class MyInnerRangesDocumentTrackerHandler : InnerRangesDocumentTrackerHandler() { override fun isDetectWhitespaceChangedLines(): Boolean = mode.let { it.isVisible && it.detectWhitespaceChangedLines } override var Block.innerRanges: List<Range.InnerRange>? get() { val block = this with(this@LocalLineStatusTrackerImpl) { return block.innerRanges } } set(value) { val block = this with(this@LocalLineStatusTrackerImpl) { block.innerRanges = value } } } @CalledInAny override fun freeze() { documentTracker.freeze(Side.LEFT) documentTracker.freeze(Side.RIGHT) } @RequiresEdt override fun unfreeze() { documentTracker.unfreeze(Side.LEFT) documentTracker.unfreeze(Side.RIGHT) } }
platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.kt
343816022
package com.aemtools.lang.clientlib.file import com.aemtools.lang.clientlib.CdLanguage import com.intellij.icons.AllIcons import com.intellij.openapi.fileTypes.LanguageFileType import javax.swing.Icon /** * @author Dmytro_Troynikov */ object CdFileType : LanguageFileType(CdLanguage) { override fun getIcon(): Icon = AllIcons.FileTypes.Text override fun getName() = "Clientlib definition" override fun getDefaultExtension(): String = "cd" override fun getDescription(): String = "Clientlib definition" }
lang/src/main/kotlin/com/aemtools/lang/clientlib/file/CdFileType.kt
1394264102
package com.polidea.androidthings.driver.a4988.driver import android.util.Log import com.polidea.androidthings.driver.steppermotor.Direction import com.polidea.androidthings.driver.steppermotor.awaiter.Awaiter import com.polidea.androidthings.driver.steppermotor.awaiter.DefaultAwaiter import com.polidea.androidthings.driver.steppermotor.driver.StepDuration import com.polidea.androidthings.driver.steppermotor.driver.StepperMotorDriver import com.polidea.androidthings.driver.steppermotor.gpio.GpioFactory import com.polidea.androidthings.driver.steppermotor.gpio.StepperMotorGpio import java.io.IOException class A4988 internal constructor(private val stepGpioId: String, private val dirGpioId: String?, private val ms1GpioId: String?, private val ms2GpioId: String?, private val ms3GpioId: String?, private val enGpioId: String?, private val gpioFactory: GpioFactory, private val awaiter: Awaiter) : StepperMotorDriver() { constructor(stepGpioId: String) : this(stepGpioId, null, null, null, null, null, GpioFactory(), DefaultAwaiter()) constructor(stepGpioId: String, dirGpioId: String) : this(stepGpioId, dirGpioId, null, null, null, null, GpioFactory(), DefaultAwaiter()) constructor(stepGpioId: String, dirGpioId: String?, ms1GpioId: String?, ms2GpioId: String?, ms3GpioId: String?, enGpioId: String?) : this(stepGpioId, dirGpioId, ms1GpioId, ms2GpioId, ms3GpioId, enGpioId, GpioFactory(), DefaultAwaiter()) override var direction = Direction.CLOCKWISE set(value) { setDirectionOnBoard(value) field = value } var resolution = A4988Resolution.SIXTEENTH set(value) { setResolutionOnBoard(value) field = value } var enabled = false set(value) { setEnabledOnBoard(value) field = value } private lateinit var stepGpio: StepperMotorGpio private var dirGpio: StepperMotorGpio? = null private var ms1Gpio: StepperMotorGpio? = null private var ms2Gpio: StepperMotorGpio? = null private var ms3Gpio: StepperMotorGpio? = null private var enGpio: StepperMotorGpio? = null private var gpiosOpened = false override fun open() { if (gpiosOpened) { return } try { stepGpio = stepGpioId.openGpio()!! dirGpio = dirGpioId.openGpio() ms1Gpio = ms1GpioId.openGpio() ms2Gpio = ms2GpioId.openGpio() ms3Gpio = ms3GpioId.openGpio() enGpio = enGpioId.openGpio() gpiosOpened = true } catch (e: Exception) { close() throw e } direction = Direction.CLOCKWISE resolution = A4988Resolution.SIXTEENTH enabled = false } override fun close() { arrayOf(stepGpio, dirGpio, ms1Gpio, ms2Gpio, ms3Gpio, enGpio).forEach { try { it?.close() } catch (e: IOException) { Log.e(TAG, "Couldn't close a gpio correctly.", e.cause) } } gpiosOpened = false } override fun performStep(stepDuration: StepDuration) { if (enGpio != null && !enabled) { throw IllegalStateException("A4988 is disabled. Enable it before performing a stepDuration.") } val pulseDurationMillis = stepDuration.millis / 2 val pulseDurationNanos = stepDuration.nanos / 2 stepGpio.value = true awaiter.await(pulseDurationMillis, pulseDurationNanos) stepGpio.value = false awaiter.await(pulseDurationMillis, pulseDurationNanos) } private fun setDirectionOnBoard(direction: Direction) { when (direction) { Direction.CLOCKWISE -> dirGpio?.value = true Direction.COUNTERCLOCKWISE -> dirGpio?.value = false } } private fun setResolutionOnBoard(a4988Resolution: A4988Resolution) { when (a4988Resolution) { A4988Resolution.FULL -> setResolutionGpios(true, true, true) A4988Resolution.HALF -> setResolutionGpios(true, true, false) A4988Resolution.QUARTER -> setResolutionGpios(false, true, false) A4988Resolution.EIGHT -> setResolutionGpios(true, false, false) A4988Resolution.SIXTEENTH -> setResolutionGpios(false, false, false) } } private fun setEnabledOnBoard(enabled: Boolean) { enGpio?.value = !enabled } private fun setResolutionGpios(ms1Value: Boolean, ms2Value: Boolean, ms3Value: Boolean) { ms1Gpio?.value = ms1Value ms2Gpio?.value = ms2Value ms3Gpio?.value = ms3Value } private fun String?.openGpio(): StepperMotorGpio? = if (this != null) StepperMotorGpio(gpioFactory.openGpio(this)) else null companion object { val TAG = "A4988" } }
a4988/src/main/java/com/polidea/androidthings/driver/a4988/driver/A4988.kt
2157475690
package com.faendir.acra.ui.view.error import com.faendir.acra.i18n.Messages import com.faendir.acra.navigation.View import com.faendir.acra.ui.component.Translatable import com.faendir.acra.ui.ext.SizeUnit import com.faendir.acra.ui.ext.flexLayout import com.faendir.acra.ui.ext.paragraph import com.faendir.acra.ui.ext.setMargin import com.faendir.acra.ui.ext.translatableButton import com.faendir.acra.ui.ext.translatableParagraph import com.faendir.acra.ui.view.Overview import com.vaadin.flow.component.HasComponents import com.vaadin.flow.component.HasSize import com.vaadin.flow.component.html.Paragraph import com.vaadin.flow.component.orderedlayout.FlexComponent import com.vaadin.flow.component.orderedlayout.FlexLayout import com.vaadin.flow.router.BeforeEnterEvent import com.vaadin.flow.router.ErrorParameter import com.vaadin.flow.router.HasErrorParameter import com.vaadin.flow.router.NotFoundException import com.vaadin.flow.router.RouterLink import com.vaadin.flow.spring.annotation.SpringComponent import com.vaadin.flow.spring.annotation.UIScope import com.vaadin.flow.spring.router.SpringRouteNotFoundError @Suppress("LeakingThis") @View class ErrorView : SpringRouteNotFoundError() /*need to extend RouteNotFoundError due to vaadin-spring bug: TODO: Remove when https://github.com/vaadin/spring/issues/661 is fixed*/, HasErrorParameter<NotFoundException>, HasComponents, HasSize { init { setSizeFull() flexLayout { setSizeFull() setFlexDirection(FlexLayout.FlexDirection.COLUMN) alignItems = FlexComponent.Alignment.CENTER justifyContentMode = FlexComponent.JustifyContentMode.CENTER paragraph("404") { style["font-size"] = "200px" style["line-height"] = "80%" setMargin(0, SizeUnit.PIXEL) } translatableParagraph(Messages.URL_NOT_FOUND) add(RouterLink("", Overview::class.java).apply { translatableButton(Messages.GO_HOME) }) } } override fun setErrorParameter(event: BeforeEnterEvent?, parameter: ErrorParameter<NotFoundException>): Int = 404 }
acrarium/src/main/kotlin/com/faendir/acra/ui/view/error/ErrorView.kt
723161267
package jetbrains.buildServer.dotnet import java.io.File interface DotnetSdksProvider { fun getSdks(dotnetExecutable: File): Sequence<DotnetSdk> }
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotnet/DotnetSdksProvider.kt
2212599091
// 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.internal.statistics.whitelist.validator import com.intellij.featureStatistics.* import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.validator.ValidationResultType import com.intellij.internal.statistic.eventLog.validator.rules.EventContext import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomWhiteListRule import com.intellij.openapi.application.ApplicationManager import com.intellij.testFramework.registerExtension import junit.framework.TestCase import org.junit.Test class ProductivityValidatorTest : ProductivityFeaturesTest() { private fun doValidateEventData(validator: CustomWhiteListRule, name: String, eventData: FeatureUsageData) { val context = EventContext.create("event_id", eventData.build()) val data = context.eventData[name] as String TestCase.assertEquals(ValidationResultType.ACCEPTED, validator.validate(data, context)) } override fun setUp() { super.setUp() ApplicationManager.getApplication().registerExtension( ProductivityFeaturesProvider.EP_NAME, TestProductivityFeatureProvider(), testRootDisposable ) } @Test fun `test validate productivity feature by id`() { val validator = FeatureUsageTrackerImpl.ProductivityUtilValidator() val data = FeatureUsageData().addData("id", "testFeatureId").addData("group", "testFeatureGroup") doValidateEventData(validator, "id", data) } @Test fun `test validate productivity feature by group`() { val validator = FeatureUsageTrackerImpl.ProductivityUtilValidator() val data = FeatureUsageData().addData("id", "testFeatureId").addData("group", "testFeatureGroup") doValidateEventData(validator, "group", data) } @Test fun `test validate productivity feature by id without group`() { val validator = FeatureUsageTrackerImpl.ProductivityUtilValidator() val data = FeatureUsageData().addData("id", "secondTestFeatureId").addData("group", "unknown") doValidateEventData(validator, "id", data) } @Test fun `test validate productivity feature by unknown group`() { val validator = FeatureUsageTrackerImpl.ProductivityUtilValidator() val data = FeatureUsageData().addData("id", "secondTestFeatureId").addData("group", "unknown") doValidateEventData(validator, "group", data) } } class TestProductivityFeatureProvider : ProductivityFeaturesProvider() { override fun getFeatureDescriptors(): Array<FeatureDescriptor> { val withGroup = FeatureDescriptor("testFeatureId", "testFeatureGroup", "TestTip.html", "test", 0, 0, null, 0, this) val noGroup = FeatureDescriptor("secondTestFeatureId", null, "TestTip.html", "test", 0, 0, null, 0, this) return arrayOf(withGroup, noGroup) } override fun getGroupDescriptors(): Array<GroupDescriptor> { return arrayOf(GroupDescriptor("testFeatureGroup", "test")) } override fun getApplicabilityFilters(): Array<ApplicabilityFilter?> { return arrayOfNulls(0) } }
platform/platform-tests/testSrc/com/intellij/internal/statistics/whitelist/validator/ProductivityValidatorTest.kt
1988005373
// 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.testFramework.assertions import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.text.StringUtilRt import com.intellij.rt.execution.junit.FileComparisonFailure import com.intellij.testFramework.UsefulTestCase import com.intellij.util.io.readChars import com.intellij.util.io.write import org.assertj.core.api.ListAssert import org.yaml.snakeyaml.DumperOptions import org.yaml.snakeyaml.Yaml import org.yaml.snakeyaml.nodes.Node import org.yaml.snakeyaml.nodes.Tag import org.yaml.snakeyaml.representer.Represent import org.yaml.snakeyaml.representer.Representer import java.nio.file.NoSuchFileException import java.nio.file.Path import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.regex.Pattern internal interface SnapshotFileUsageListener { fun beforeMatch(file: Path) } internal val snapshotFileUsageListeners = Collections.newSetFromMap<SnapshotFileUsageListener>(ConcurrentHashMap()) class ListAssertEx<ELEMENT>(actual: List<ELEMENT>?) : ListAssert<ELEMENT>(actual) { fun toMatchSnapshot(snapshotFile: Path) { snapshotFileUsageListeners.forEach { it.beforeMatch(snapshotFile) } isNotNull compareFileContent(actual, snapshotFile) } } fun dumpData(data: Any): String { val dumperOptions = DumperOptions() dumperOptions.isAllowReadOnlyProperties = true dumperOptions.lineBreak = DumperOptions.LineBreak.UNIX val yaml = Yaml(DumpRepresenter(), dumperOptions) return yaml.dump(data) } private class DumpRepresenter : Representer() { init { representers.put(Pattern::class.java, RepresentDump()) } private inner class RepresentDump : Represent { override fun representData(data: Any): Node = representScalar(Tag.STR, data.toString()) } } internal fun loadSnapshotContent(snapshotFile: Path, convertLineSeparators: Boolean = SystemInfo.isWindows): CharSequence { // because developer can open file and depending on editor settings, newline maybe added to the end of file var content = snapshotFile.readChars().trimEnd() if (convertLineSeparators) { content = StringUtilRt.convertLineSeparators(content, "\n") } return content } @Throws(FileComparisonFailure::class) fun compareFileContent(actual: Any, snapshotFile: Path, updateIfMismatch: Boolean = isUpdateSnapshotIfMismatch(), writeIfNotFound: Boolean = true) { val actualContent = if (actual is CharSequence) getNormalizedActualContent(actual) else dumpData(actual).trimEnd() val expected = try { loadSnapshotContent(snapshotFile) } catch (e: NoSuchFileException) { if (!writeIfNotFound || UsefulTestCase.IS_UNDER_TEAMCITY) { throw e } println("Write a new snapshot ${snapshotFile.fileName}") snapshotFile.write(actualContent) return } if (StringUtil.equal(actualContent, expected, true)) { return } if (updateIfMismatch) { System.out.println("UPDATED snapshot ${snapshotFile.fileName}") snapshotFile.write(StringBuilder(actualContent)) } else { val firstMismatch = StringUtil.commonPrefixLength(actualContent, expected) @Suppress("SpellCheckingInspection") val message = "Received value does not match stored snapshot ${snapshotFile.fileName} at ${firstMismatch}.\n" + "Expected: '${expected.contextAround(firstMismatch, 10)}'\n" + "Actual : '${actualContent.contextAround(firstMismatch, 10)}'\n" + "Inspect your code changes or run with `-Dtest.update.snapshots` to update" throw FileComparisonFailure(message, expected.toString(), actualContent.toString(), snapshotFile.toString()) } } internal fun getNormalizedActualContent(actual: CharSequence): CharSequence { var actualContent = actual if (SystemInfo.isWindows) { actualContent = StringUtilRt.convertLineSeparators(actualContent, "\n") } return actualContent.trimEnd() } private fun isUpdateSnapshotIfMismatch(): Boolean { if (UsefulTestCase.IS_UNDER_TEAMCITY) { return false } val value = System.getProperty("test.update.snapshots") return value != null && (value.isEmpty() || value.toBoolean()) } private fun CharSequence.contextAround(offset: Int, context: Int): String = substring((offset - context).coerceAtLeast(0), (offset + context).coerceAtMost(length))
platform/testFramework/extensions/src/com/intellij/testFramework/assertions/snapshot.kt
3636437678
package gr.tsagi.jekyllforandroid.app.utils import android.util.Log import org.apache.http.NameValuePair import org.apache.http.client.ClientProtocolException import org.apache.http.client.entity.UrlEncodedFormEntity import org.apache.http.client.methods.HttpPost import org.apache.http.impl.client.DefaultHttpClient import org.apache.http.message.BasicNameValuePair import org.json.JSONException import org.json.JSONObject import java.io.* import java.util.* /** \* Created with IntelliJ IDEA. \* User: jchanghong \* Date: 7/7/14 \* Time: 15:14 \*/ class GetAccessToken { internal var jsondel = "" internal var params: MutableList<NameValuePair> = ArrayList() lateinit internal var httpClient: DefaultHttpClient lateinit internal var httpPost: HttpPost fun gettoken(address: String, token: String, client_id: String, client_secret: String, redirect_uri: String, grant_type: String): JSONObject { // Making HTTP request try { // DefaultHttpClient httpClient = DefaultHttpClient() httpPost = HttpPost(address) params.add(BasicNameValuePair("code", token)) params.add(BasicNameValuePair("client_id", client_id)) params.add(BasicNameValuePair("client_secret", client_secret)) params.add(BasicNameValuePair("redirect_uri", redirect_uri)) params.add(BasicNameValuePair("grant_type", grant_type)) httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded") httpPost.entity = UrlEncodedFormEntity(params) val httpResponse = httpClient.execute(httpPost) val httpEntity = httpResponse.entity `is` = httpEntity.content } catch (e: UnsupportedEncodingException) { e.printStackTrace() } catch (e: ClientProtocolException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } try { val reader = BufferedReader(InputStreamReader( `is`!!, "iso-8859-1"), 8) val sb = StringBuilder() var line: String? = reader.readLine() while (line != null) { sb.append(line + "n") line = reader.readLine() } `is`!!.close() json = sb.toString() Log.e("JSONStr", json) jsondel = json.replace("&", "\",\"").replace("=", "\"=\"") Log.e("JSONStrDel", jsondel) } catch (e: Exception) { e.message Log.e("Buffer Error", "Error converting result " + e.toString()) } // Parse the String to a JSON Object try { jObj = JSONObject("{\"$jsondel\"}") } catch (e: JSONException) { Log.e("JSON Parser", "Error parsing data " + e.toString()) } // Return JSON String return jObj!! } companion object { internal var `is`: InputStream? = null internal var jObj: JSONObject? = null internal var json = "" } }
app/src/main/java/gr/tsagi/jekyllforandroid/app/utils/GetAccessToken.kt
3312729109
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.lang.slicer class GroovySliceBackwardTest : GroovySliceTestCase(true) { fun testSimple() = doTest() fun testGroovyJavaGroovy() = doTest { listOf("$it.groovy", "$it.java") } fun testJavaGroovyJava() = doTest { listOf("$it.java", "$it.groovy") } }
plugins/groovy/test/org/jetbrains/plugins/groovy/lang/slicer/GroovySliceBackwardTest.kt
2741140436
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: NATIVE object A { const val a: String = "$" const val b = "1234$a" const val c = 10000 val bNonConst = "1234$a" val bNullable: String? = "1234$a" } object B { const val a: String = "$" const val b = "1234$a" const val c = 10000 val bNonConst = "1234$a" val bNullable: String? = "1234$a" } fun box(): String { if (A.a !== B.a) return "Fail 1: A.a !== B.a" if (A.b !== B.b) return "Fail 2: A.b !== B.b" if (A.c !== B.c) return "Fail 3: A.c !== B.c" if (A.bNonConst !== B.bNonConst) return "Fail 4: A.bNonConst !== B.bNonConst" if (A.bNullable !== B.bNullable) return "Fail 5: A.bNullable !== B.bNullable" return "OK" }
backend.native/tests/external/codegen/box/constants/kt9532.kt
4168025837
package net.ndrei.teslacorelib.gui import net.minecraft.util.EnumFacing import net.ndrei.teslacorelib.MOD_ID import net.ndrei.teslacorelib.TeslaCoreLib import net.ndrei.teslacorelib.capabilities.inventory.SidedItemHandlerConfig import net.ndrei.teslacorelib.localization.GUI_SIDE_CONFIG import net.ndrei.teslacorelib.localization.localizeModString import net.ndrei.teslacorelib.netsync.SimpleNBTMessage import net.ndrei.teslacorelib.tileentities.SidedTileEntity /** * Created by CF on 2017-06-28. */ class SideConfigurator(left: Int, top: Int, width: Int, height: Int, private val sidedConfig: SidedItemHandlerConfig, private val entity: SidedTileEntity) : BasicContainerGuiPiece(left, top, width, height) { private var selectedInventory = -1 private var lockPiece: LockedInventoryTogglePiece? = null init { this.setSelectedInventory(-1) } fun setSelectedInventory(index: Int) { this.selectedInventory = index this.lockPiece = null this.setVisibility(this.selectedInventory >= 0) val colors = this.sidedConfig.coloredInfo if (this.selectedInventory in 0 until colors.size) { val color = colors[this.selectedInventory].color if (this.entity.getInventoryLockState(color) != null) { this.lockPiece = LockedInventoryTogglePiece( this.left + 6 * 18 + 2, this.top + 1 * 18 + 2, this.entity, color) } } } override fun drawBackgroundLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, partialTicks: Float, mouseX: Int, mouseY: Int) { val colors = this.sidedConfig.coloredInfo if (this.selectedInventory < 0 || this.selectedInventory >= colors.size) { return } val color = colors[this.selectedInventory].color val sides = this.sidedConfig.getSidesForColor(color) container.bindDefaultTexture() this.drawSide(container, sides, EnumFacing.UP, 2, 0, mouseX, mouseY) this.drawSide(container, sides, EnumFacing.WEST, 1, 1, mouseX, mouseY) this.drawSide(container, sides, EnumFacing.SOUTH, 2, 1, mouseX, mouseY) this.drawSide(container, sides, EnumFacing.EAST, 3, 1, mouseX, mouseY) this.drawSide(container, sides, EnumFacing.DOWN, 2, 2, mouseX, mouseY) this.drawSide(container, sides, EnumFacing.NORTH, 3, 2, mouseX, mouseY) this.lockPiece?.drawBackgroundLayer(container, guiX, guiY, partialTicks, mouseX, mouseY) } override fun drawForegroundLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, mouseX: Int, mouseY: Int) { super.drawForegroundLayer(container, guiX, guiY, mouseX, mouseY) this.lockPiece?.drawForegroundLayer(container, guiX, guiY, mouseX, mouseY) } override fun drawForegroundTopLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, mouseX: Int, mouseY: Int) { super.drawForegroundTopLayer(container, guiX, guiY, mouseX, mouseY) val facing = this.getSide(container, mouseX, mouseY) if (facing != null) { container.drawTooltip(listOf(when (facing) { EnumFacing.NORTH -> localizeModString(MOD_ID, GUI_SIDE_CONFIG, "back").formattedText EnumFacing.SOUTH -> localizeModString(MOD_ID, GUI_SIDE_CONFIG, "front").formattedText EnumFacing.EAST -> localizeModString(MOD_ID, GUI_SIDE_CONFIG, "right").formattedText EnumFacing.WEST -> localizeModString(MOD_ID, GUI_SIDE_CONFIG, "left").formattedText else -> localizeModString(MOD_ID, GUI_SIDE_CONFIG, facing.toString()).formattedText }.capitalize()), (mouseX - guiX) - (mouseX - guiX - this.left) % 18 + 9, (mouseY - guiY) - (mouseY - guiY - this.top) % 18 + 9) } this.lockPiece?.drawForegroundTopLayer(container, guiX, guiY, mouseX, mouseY) } override fun mouseClicked(container: BasicTeslaGuiContainer<*>, mouseX: Int, mouseY: Int, mouseButton: Int) { if (this.selectedInventory >= 0 && this.isInside(container, mouseX, mouseY)) { // var localY = mouseY - container.guiTop - this.top // val row = localY / 18 // if (row in 0..2) { // var localX = mouseX - container.guiLeft - this.left // val column = localX / 18 // if (column in 1..3) { // localX -= column * 18 // localY -= row * 18 // if (localX in 2..15 && localY in 2..15) { // var facing: EnumFacing? = null // if (row == 0) { // if (column == 2) { // facing = EnumFacing.UP // } // } else if (row == 1) { // if (column == 1) { // facing = EnumFacing.WEST // } else if (column == 2) { // facing = EnumFacing.SOUTH // } else if (column == 3) { // facing = EnumFacing.EAST // } // } else if (row == 2) { // if (column == 2) { // facing = EnumFacing.DOWN // } else if (column == 3) { // facing = EnumFacing.NORTH // } // } val facing = this.getSide(container, mouseX, mouseY) if (facing != null) { val color = this.sidedConfig.coloredInfo[this.selectedInventory].color this.sidedConfig.toggleSide(color, facing) val nbt = this.entity.setupSpecialNBTMessage("TOGGLE_SIDE") nbt.setInteger("color", color.metadata) nbt.setInteger("side", facing.index) TeslaCoreLib.network.sendToServer(SimpleNBTMessage(this.entity, nbt)) } // } // } } if ((this.lockPiece != null) && Companion.isInside(container, this.lockPiece!!, mouseX, mouseY)) { this.lockPiece?.mouseClicked(container, mouseX, mouseY, mouseButton) } } private fun getSide(container: BasicTeslaGuiContainer<*>, mouseX: Int, mouseY: Int): EnumFacing? { var localY = mouseY - container.guiTop - this.top val row = localY / 18 var facing: EnumFacing? = null if (row in 0..2) { var localX = mouseX - container.guiLeft - this.left val column = localX / 18 if (column in 1..3) { localX -= column * 18 localY -= row * 18 if (localX in 2..15 && localY in 2..15) { when (row) { 0 -> when (column) { 2 -> facing = EnumFacing.UP } 1 -> when (column) { 1 -> facing = EnumFacing.WEST 2 -> facing = EnumFacing.SOUTH 3 -> facing = EnumFacing.EAST } 2 -> when (column) { 2 -> facing = EnumFacing.DOWN 3 -> facing = EnumFacing.NORTH } } } } } return facing } private fun drawSide(container: BasicTeslaGuiContainer<*>, sides: List<EnumFacing>, side: EnumFacing, column: Int, row: Int, mouseX: Int, mouseY: Int) { // var mouseX = mouseX // var mouseY = mouseY val x = this.left + column * 18 + 2 val y = this.top + row * 18 + 2 container.drawTexturedRect(x, y, 110, 210, 14, 14) // mouseX -= container.guiLeft // mouseY -= container.guiTop //if (mouseX >= x && mouseX <= x + 14 && mouseY >= y && mouseY <= y + 14) { if (((mouseX - container.guiLeft) in x..(x + 14)) && ((mouseY - container.guiTop) in y..(y + 14))) { container.drawFilledRect(container.guiLeft + x + 1, container.guiTop + y + 1, 12, 12, 0x42FFFFFF) } container.drawTexturedRect(x, y, if (sides.contains(side)) 182 else 146, 210, 14, 14) } }
src/main/kotlin/net/ndrei/teslacorelib/gui/SideConfigurator.kt
788175580
package net.ndrei.teslacorelib.items import net.minecraft.creativetab.CreativeTabs import net.minecraft.item.ItemStack import net.ndrei.teslacorelib.tileentities.SidedTileEntity /** * Created by CF on 2017-06-27. */ abstract class BaseAddon protected constructor(modId: String, tab: CreativeTabs, registryName: String) : RegisteredItem(modId, tab, registryName) { open fun canBeAddedTo(machine: SidedTileEntity) = false open fun onAdded(addon: ItemStack, machine: SidedTileEntity) { } open fun onRemoved(addon: ItemStack, machine: SidedTileEntity) { } open fun isValid(machine: SidedTileEntity): Boolean = true open val workEnergyMultiplier: Float get() = 1.0f }
src/main/kotlin/net/ndrei/teslacorelib/items/BaseAddon.kt
549831602
class A { companion object {} enum class E { OK } } fun box() = A.E.OK.toString()
backend.native/tests/external/codegen/box/enum/innerWithExistingClassObject.kt
1836122863
package cz.inventi.inventiskeleton.presentation.post.list import com.hannesdorfmann.mosby3.mvp.MvpNullObjectBasePresenter import cz.inventi.inventiskeleton.data.post.Post import cz.inventi.inventiskeleton.domain.post.GetPostListUseCase import cz.inventi.inventiskeleton.presentation.common.PresentationObserver import javax.inject.Inject /** * Created by semanticer on 05.05.2017. */ class PostListPresenter @Inject constructor(private val useCase: GetPostListUseCase) : MvpNullObjectBasePresenter<PostListView>() { override fun attachView(view: PostListView) { super.attachView(view) reloadList() } override fun detachView(retainInstance: Boolean) { useCase.dispose() } fun reloadList() { useCase.execute(PostListObserver(view), GetPostListUseCase.Params(limit = 20)) } fun onPostSelected(post: Post) { view.showDetailPost(post.id) } fun onPostLongClicked(post: Post) : Boolean { view.deletePost(post) return false } fun onAddPost() { view.showAddPost() } class PostListObserver constructor(view: PostListView): PresentationObserver<List<Post>, PostListView>(view) { override fun onNext(list: List<Post>) { onView { it.showPostList(list) } } } }
app/src/main/java/cz/inventi/inventiskeleton/presentation/post/list/PostListPresenter.kt
4036354175
package com.byoutline.kickmaterial.features.projectdetails import android.content.Context import android.util.TypedValue import com.byoutline.kickmaterial.R import com.byoutline.kickmaterial.databinding.ActivityProjectDetailsBinding import com.byoutline.secretsauce.utils.ViewUtils class ProjectDetailsScrollListener(context: Context, private val binding: ActivityProjectDetailsBinding) : ObservableScrollView.Callbacks { private val minTitlesMarginTop: Int private val maxTitlesMarginTop: Int private val maxTitlesMarginLeft: Int private val maxParallaxValue: Int private val titleFontMaxSize: Int private val titleFontMinSize: Int private val maxTitlePaddingRight: Int init { val applicationContext = context.applicationContext val res = context.resources minTitlesMarginTop = ViewUtils.dpToPx(32f, applicationContext) maxTitlesMarginTop = res.getDimensionPixelSize(R.dimen.titles_container_margin_top) - res.getDimensionPixelSize(R.dimen.status_bar_height) maxTitlesMarginLeft = ViewUtils.dpToPx(32f, applicationContext) maxTitlePaddingRight = ViewUtils.dpToPx(72f, applicationContext) maxParallaxValue = res.getDimensionPixelSize(R.dimen.project_details_photo_height) / 3 titleFontMaxSize = res.getDimensionPixelSize(R.dimen.font_21) titleFontMinSize = res.getDimensionPixelSize(R.dimen.font_16) } override fun onScrollChanged(deltaX: Int, deltaY: Int) { val scrollY = (binding.scrollView.scrollY * 0.6f).toInt() val newTitleLeft = Math.min(maxTitlesMarginLeft.toFloat(), scrollY * 0.5f) val newTitleTop = Math.min(maxTitlesMarginTop, scrollY).toFloat() val newTitlePaddingRight = Math.min(maxTitlePaddingRight, scrollY) binding.projectTitleTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, Math.max(titleFontMaxSize - scrollY * 0.05f, titleFontMinSize.toFloat())) binding.projectTitleTv.setPadding(0, 0, newTitlePaddingRight, 0) binding.projectDetailsTitleContainer.translationX = newTitleLeft binding.projectDetailsTitleContainer.translationY = -newTitleTop binding.detailsContainer.translationY = -newTitleTop binding.playVideoBtn.translationY = -newTitleTop /** Content of scroll view is hiding to early during scroll so we move it also by * changing to padding */ binding.scrollView.setPadding(0, (newTitleTop * 0.6f).toInt(), 0, 0) // Move background photo (parallax effect) val parallax = (scrollY * .3f).toInt() if (maxParallaxValue > parallax) { binding.projectPhotoContainer.translationY = (-parallax).toFloat() } } }
app/src/main/java/com/byoutline/kickmaterial/features/projectdetails/ProjectDetailsScrollListener.kt
133671755
interface A { fun foo(): Any? fun bar(): String } interface B { fun foo(): String } fun <T> bar(x: T): String where T : A, T : B { if (x.foo().length != 2 || x.foo() != "OK") return "fail 1" if (x.bar() != "ok") return "fail 2" return "OK" } class C : A, B { override fun foo() = "OK" override fun bar() = "ok" } fun box(): String = bar(C())
backend.native/tests/external/codegen/box/casts/intersectionTypeMultipleBounds.kt
1647961497
// WITH_STDLIB fun castMayFail(b: Boolean) { val x : Any = if (b) "x" else 5 val y = x as String if (<weak_warning descr="Value of 'b' is always true">b</weak_warning>) {} println(y) } fun castWillFail(b: Boolean) { val x : Any = if (b) X() else Y() val y : Any = if (b) x <warning descr="Cast will always fail">as</warning> Y else X() println(y) } fun castNumber() { val c: Number = 1 c <warning descr="Cast will always fail">as</warning> Float } fun castIntToFloat(c: Int) { c <warning descr="[CAST_NEVER_SUCCEEDS] This cast can never succeed">as</warning> Float } fun safeCast(b: Boolean) { val x : Any = if (b) "x" else 5 val y = x as? String if (y == null) { if (<weak_warning descr="Value of 'b' is always false">b</weak_warning>) {} } } fun nullAsNullableVoid() { // No warning: cast to set type val x = null as Void? println(x) } fun safeAs(v : Any?) { val b = (v as? String) if (v == null) { } println(b) } class X {} class Y {}
plugins/kotlin/idea/tests/testData/inspections/dfa/TypeCast.kt
2681489155
// "Make 'bar' internal" "true" class C { internal fun foo() = true inline fun bar(baz: () -> Unit) { if (<caret>foo()) { baz() } } }
plugins/kotlin/idea/tests/testData/quickfix/callFromPublicInline/nonPublic/internalFunction2.kt
3433125166
// EXTRACTION_TARGET: property with initializer val i = 1 fun foo(): Int { return <selection>2</selection> }
plugins/kotlin/idea/tests/testData/refactoring/introduceConstant/extractWithNameClash.kt
4279828479
// 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.impl import com.intellij.util.ReflectionUtil import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.ModifiableModuleEntity import com.intellij.workspaceModel.storage.bridgeEntities.ModuleDependencyItem import com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex import com.intellij.workspaceModel.storage.url.VirtualFileUrl import kotlin.properties.ReadWriteProperty import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.reflect.full.memberProperties /** * For creating a new entity, you should perform the following steps: * * - Choose the name of the entity, e.g. MyModuleEntity * - Create [WorkspaceEntity] representation: * - The entity should inherit [WorkspaceEntityBase] * - Properties (not references to other entities) should be listed in a primary constructor as val's * - If the entity has PersistentId, the entity should extend [WorkspaceEntityWithPersistentId] * - If the entity has references to other entities, they should be implement using property delegation objects listed in [com.intellij.workspaceModel.storage.impl.references] package. * E.g. [OneToMany] or [ManyToOne.NotNull] * * Example: * * ```kotlin * class MyModuleEntity(val name: String) : WorkspaceEntityBase(), WorkspaceEntityWithPersistentId { * * val childModule: MyModuleEntity? by OneToOneParent.Nullable(MyModuleEntity::class.java, true) * * fun persistentId() = NameId(name) * } * ``` * * The above entity describes an entity with `name` property, persistent id and the reference to "ChildModule" * * This object will be used by users and it's returned by methods like `resolve`, `entities` and so on. * * ------------------------------------------------------------------------------------------------------------------------------- * * - Create EntityData representation: * - Entity data should have the name ${entityName}Data. E.g. MyModuleEntityData. * - Entity data should inherit [WorkspaceEntityData] * - Properties (not references to other entities) should be listed in the body as lateinit var's or with default value (null, 0, false). * - If the entity has PersistentId, the Entity data should extend [WorkspaceEntityData.WithCalculablePersistentId] * - References to other entities should not be listed in entity data. * * - If the entity contains soft references to other entities (persistent id to other entities), entity data should extend SoftLinkable * interface and implement the required methods. Check out the [FacetEntityData] implementation, but keep in mind the this might * be more complicated like in [ModuleEntityData]. * - Entity data should implement [WorkspaceEntityData.createEntity] method. This method should return an instance of * [WorkspaceEntity]. This instance should be passed to [addMetaData] after creation! * E.g.: * * override fun createEntity(snapshot: WorkspaceEntityStorage): ModuleEntity = ModuleEntity(name, type, dependencies).also { * addMetaData(it, snapshot) * } * * Example: * * ```kotlin * class MyModuleEntityData : WorkspaceEntityData.WithCalculablePersistentId<MyModuleEntity>() { * lateinit var name: String * * override fun persistentId(): NameId = NameId(name) * * override fun createEntity(snapshot: WorkspaceEntityStorage): MyModuleEntity = MyModuleEntity(name).also { * addMetaData(it, snapshot) * } * } * ``` * * This is an internal representation of WorkspaceEntity. It's not passed to users. * * ------------------------------------------------------------------------------------------------------------------------------- * * - Create [ModifiableWorkspaceEntity] representation: * - The name should be: Modifiable${entityName}. E.g. ModifiableMyModuleEntity * - This should be inherited from [ModifiableWorkspaceEntityBase] * - Properties (not references to other entities) should be listed in the body as delegation to [EntityDataDelegation()] * - References to other entities should be listed as in [WorkspaceEntity], but with corresponding modifiable delegates * * Example: * * ```kotlin * class ModifiableMyModuleEntity : ModifiableWorkspaceEntityBase<MyModuleEntity>() { * var name: String by EntityDataDelegation() * * var childModule: MyModuleEntity? by MutableOneToOneParent.NotNull(MyModuleEntity::class.java, MyModuleEntity::class.java, true) * } * ``` */ abstract class WorkspaceEntityBase : ReferableWorkspaceEntity, Any() { override lateinit var entitySource: EntitySource internal set internal var id: EntityId = 0 internal lateinit var snapshot: AbstractEntityStorage override fun hasEqualProperties(e: WorkspaceEntity): Boolean { if (this.javaClass != e.javaClass) return false this::class.memberProperties.forEach { if (it.name == WorkspaceEntityBase::id.name) return@forEach if (it.name == WorkspaceEntityBase::snapshot.name) return@forEach if (it.getter.call(this) != it.getter.call(e)) return false } return true } override fun <R : WorkspaceEntity> referrers(entityClass: Class<R>, propertyName: String): Sequence<R> { val connectionId = snapshot.refs.findConnectionId(this::class.java, entityClass) if (connectionId == null) return emptySequence() return when (connectionId.connectionType) { ConnectionId.ConnectionType.ONE_TO_MANY -> snapshot.extractOneToManyChildren(connectionId, id) ConnectionId.ConnectionType.ONE_TO_ONE -> snapshot.extractOneToOneChild<R>(connectionId, id)?.let { sequenceOf(it) } ?: emptySequence() ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY -> snapshot.extractOneToAbstractManyChildren(connectionId, id.asParent()) ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE -> snapshot.extractAbstractOneToOneChild<R>(connectionId, id.asParent())?.let { sequenceOf(it) } ?: emptySequence() } } override fun <E : WorkspaceEntity> createReference(): EntityReference<E> { return EntityReferenceImpl(this.id) } override fun toString(): String = id.asString() override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as WorkspaceEntityBase if (id != other.id) return false if (this.snapshot.entityDataById(id) !== other.snapshot.entityDataById(other.id)) return false return true } override fun hashCode(): Int = id.hashCode() } abstract class ModifiableWorkspaceEntityBase<T : WorkspaceEntityBase> : WorkspaceEntityBase(), ModifiableWorkspaceEntity<T> { internal lateinit var original: WorkspaceEntityData<T> lateinit var diff: WorkspaceEntityStorageBuilder internal val modifiable = ThreadLocal.withInitial { false } internal inline fun allowModifications(action: () -> Unit) { modifiable.set(true) try { action() } finally { modifiable.remove() } } open fun getEntityClass(): KClass<T> = ClassConversion.modifiableEntityToEntity(this::class) open fun applyToBuilder(builder: WorkspaceEntityStorageBuilder, entitySource: EntitySource) { throw NotImplementedError() } open fun getEntityData(): WorkspaceEntityData<T> { throw NotImplementedError() } // For generated entities @Suppress("unused") fun addToBuilder() { val builder = diff as WorkspaceEntityStorageBuilderImpl builder.putEntity(getEntityData()) } // For generated entities @Suppress("unused") fun applyRef(connectionId: ConnectionId, child: WorkspaceEntityData<*>?, children: List<WorkspaceEntityData<*>>?) { val builder = diff as WorkspaceEntityStorageBuilderImpl when (connectionId.connectionType) { ConnectionId.ConnectionType.ONE_TO_ONE -> builder.updateOneToOneChildOfParent(connectionId, id, child!!.createEntityId().asChild()) ConnectionId.ConnectionType.ONE_TO_MANY -> builder.updateOneToManyChildrenOfParent(connectionId, id, children!!.map { it.createEntityId().asChild() }.asSequence()) ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY -> builder.updateOneToAbstractManyChildrenOfParent(connectionId, id.asParent(), children!!.map { it.createEntityId().asChild() }.asSequence()) ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE -> builder.updateOneToAbstractOneChildOfParent(connectionId, id.asParent(), child!!.createEntityId().asChild()) } } // For generated entities @Suppress("unused") fun index(entity: WorkspaceEntity, propertyName: String, virtualFileUrl: VirtualFileUrl?) { val builder = diff as WorkspaceEntityStorageBuilderImpl builder.getMutableVirtualFileUrlIndex().index(entity, propertyName, virtualFileUrl) } // For generated entities @Suppress("unused") fun index(entity: WorkspaceEntity, propertyName: String, virtualFileUrls: Set<VirtualFileUrl>) { val builder = diff as WorkspaceEntityStorageBuilderImpl (builder.getMutableVirtualFileUrlIndex() as VirtualFileIndex.MutableVirtualFileIndex).index((entity as WorkspaceEntityBase).id, propertyName, virtualFileUrls) } // For generated entities @Suppress("unused") fun indexJarDirectories(entity: WorkspaceEntity, virtualFileUrls: Set<VirtualFileUrl>) { val builder = diff as WorkspaceEntityStorageBuilderImpl (builder.getMutableVirtualFileUrlIndex() as VirtualFileIndex.MutableVirtualFileIndex).indexJarDirectories( (entity as WorkspaceEntityBase).id, virtualFileUrls) } } interface SoftLinkable { fun getLinks(): Set<PersistentEntityId<*>> fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean } abstract class WorkspaceEntityData<E : WorkspaceEntity> : Cloneable { lateinit var entitySource: EntitySource var id: Int = -1 internal fun createEntityId(): EntityId = createEntityId(id, ClassConversion.entityDataToEntity(javaClass).toClassId()) abstract fun createEntity(snapshot: WorkspaceEntityStorage): E fun addMetaData(res: E, snapshot: WorkspaceEntityStorage) { (res as WorkspaceEntityBase).entitySource = entitySource (res as WorkspaceEntityBase).id = createEntityId() (res as WorkspaceEntityBase).snapshot = snapshot as AbstractEntityStorage } fun addMetaData(res: E, snapshot: WorkspaceEntityStorage, classId: Int) { (res as WorkspaceEntityBase).entitySource = entitySource (res as WorkspaceEntityBase).id = createEntityId(id, classId) (res as WorkspaceEntityBase).snapshot = snapshot as AbstractEntityStorage } internal fun wrapAsModifiable(diff: WorkspaceEntityStorageBuilderImpl): ModifiableWorkspaceEntity<E> { val returnClass = ClassConversion.entityDataToModifiableEntity(this::class) val res = returnClass.java.getDeclaredConstructor().newInstance() res as ModifiableWorkspaceEntityBase res.original = this res.diff = diff res.id = createEntityId() res.entitySource = this.entitySource return res } @Suppress("UNCHECKED_CAST") public override fun clone(): WorkspaceEntityData<E> = super.clone() as WorkspaceEntityData<E> override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false return ReflectionUtil.collectFields(this.javaClass).filterNot { it.name == WorkspaceEntityData<*>::id.name } .onEach { it.isAccessible = true } .all { it.get(this) == it.get(other) } } open fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false return ReflectionUtil.collectFields(this.javaClass) .filterNot { it.name == WorkspaceEntityData<*>::id.name } .filterNot { it.name == WorkspaceEntityData<*>::entitySource.name } .onEach { it.isAccessible = true } .all { it.get(this) == it.get(other) } } override fun hashCode(): Int { return ReflectionUtil.collectFields(this.javaClass).filterNot { it.name == WorkspaceEntityData<*>::id.name } .onEach { it.isAccessible = true } .mapNotNull { it.get(this)?.hashCode() } .fold(31) { acc, i -> acc * 17 + i } } override fun toString(): String { val fields = ReflectionUtil.collectFields(this.javaClass).toList().onEach { it.isAccessible = true } .joinToString(separator = ", ") { f -> "${f.name}=${f.get(this)}" } return "${this::class.simpleName}($fields, id=${this.id})" } /** * Temporally solution. * Get persistent Id without creating of TypedEntity. Should be in sync with TypedEntityWithPersistentId. * But it doesn't everywhere. E.g. FacetEntity where we should resolve module before creating persistent id. */ abstract class WithCalculablePersistentId<E : WorkspaceEntity> : WorkspaceEntityData<E>() { abstract fun persistentId(): PersistentEntityId<*> } } fun WorkspaceEntityData<*>.persistentId(): PersistentEntityId<*>? = when (this) { is WorkspaceEntityData.WithCalculablePersistentId -> this.persistentId() else -> null } class EntityDataDelegation<A : ModifiableWorkspaceEntityBase<*>, B> : ReadWriteProperty<A, B> { override fun getValue(thisRef: A, property: KProperty<*>): B { val field = thisRef.original.javaClass.getDeclaredField(property.name) field.isAccessible = true @Suppress("UNCHECKED_CAST") return field.get(thisRef.original) as B } override fun setValue(thisRef: A, property: KProperty<*>, value: B) { if (!thisRef.modifiable.get()) { throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!") } val field = thisRef.original.javaClass.getDeclaredField(property.name) field.isAccessible = true field.set(thisRef.original, value) } } class ModuleDependencyEntityDataDelegation : ReadWriteProperty<ModifiableModuleEntity, List<ModuleDependencyItem>> { override fun getValue(thisRef: ModifiableModuleEntity, property: KProperty<*>): List<ModuleDependencyItem> { val field = thisRef.original.javaClass.getDeclaredField(property.name) field.isAccessible = true @Suppress("UNCHECKED_CAST") return field.get(thisRef.original) as List<ModuleDependencyItem> } override fun setValue(thisRef: ModifiableModuleEntity, property: KProperty<*>, value: List<ModuleDependencyItem>) { if (!thisRef.modifiable.get()) { throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!") } val field = thisRef.original.javaClass.getDeclaredField(property.name) thisRef.dependencyChanged = true field.isAccessible = true field.set(thisRef.original, value) } } /** * This interface is a solution for checking consistency of some entities that can't be checked automatically * * For example, we can mark LibraryPropertiesEntityData with this interface and check that entity source of properties is the same as * entity source of the library itself. * * Interface should be applied to *entity data*. * * [assertConsistency] method is called during [WorkspaceEntityStorageBuilderImpl.assertConsistency]. */ interface WithAssertableConsistency { fun assertConsistency(storage: WorkspaceEntityStorage) }
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/Entities.kt
137515905
// PROBLEM: none fun foo() { <caret>return }
plugins/kotlin/idea/tests/testData/inspectionsLocal/useExpressionBody/convertToExpressionBody/returnWithNoValue.kt
653946184
package bar public sealed class SealedClass { public class Impl1 : SealedClass() {} public class Impl2 : SealedClass() {} }
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/moveSealedClassWithNestedImplsToAnotherPackage/after/bar/SealedClass.kt
1363542314
// "Remove 'suspend' modifier from all functions in hierarchy" "true" open class A { open suspend fun foo() { } open fun foo(n: Int) { } } open class B : A() { override fun <caret>foo() { } override fun foo(n: Int) { } } open class B1 : A() { override suspend fun foo() { } override fun foo(n: Int) { } } open class C : B() { override fun foo() { } override fun foo(n: Int) { } } open class C1 : B() { override fun foo() { } override fun foo(n: Int) { } }
plugins/kotlin/idea/tests/testData/quickfix/removeSuspend/middleClass2.kt
3936372610
actual class <lineMarker descr="Has declaration in common module">My</lineMarker> { actual fun <lineMarker descr="Has declaration in common module">foo</lineMarker>() {} }
plugins/kotlin/idea/tests/testData/gradle/newMultiplatformHighlighting/noErrors/src/jvmMain/kotlin/My.kt
4177005177
package de.fabmax.kool.modules.ui2 import de.fabmax.kool.math.clamp import de.fabmax.kool.util.Time import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.round open class ScrollState { val xScrollDp = mutableStateOf(0f) val yScrollDp = mutableStateOf(0f) val xScrollDpDesired = mutableStateOf(0f) val yScrollDpDesired = mutableStateOf(0f) val contentWidthDp = mutableStateOf(0f) val contentHeightDp = mutableStateOf(0f) val viewWidthDp = mutableStateOf(0f) val viewHeightDp = mutableStateOf(0f) val relativeBarLenX: Float get() = (round(viewWidthDp.value) / round(contentWidthDp.value)).clamp() val relativeBarLenY: Float get() = (round(viewHeightDp.value) / round(contentHeightDp.value)).clamp() val relativeBarPosX: Float get() { val div = xScrollDp.value + contentWidthDp.value - (xScrollDp.value + viewWidthDp.value) return if (div == 0f) 1f else (xScrollDp.value / div) } val relativeBarPosY: Float get() { val div = yScrollDp.value + contentHeightDp.value - (yScrollDp.value + viewHeightDp.value) return if (div == 0f) 0f else (yScrollDp.value / (div)) } val remainingSpaceTop: Float get() = yScrollDp.value val remainingSpaceBottom: Float get() = contentHeightDp.value - (yScrollDp.value + viewHeightDp.value) val remainingSpaceStart: Float get() = xScrollDp.value val remainingSpaceEnd: Float get() = contentWidthDp.value - (xScrollDp.value + viewWidthDp.value) fun scrollDpX(amount: Float, smooth: Boolean = true) { if (smooth) { val x = min(max(0f, xScrollDpDesired.value + amount), contentWidthDp.value - viewWidthDp.value) xScrollDpDesired.set(x) } else { val x = min(max(0f, xScrollDp.value + amount), contentWidthDp.value - viewWidthDp.value) xScrollDp.set(x) xScrollDpDesired.set(x) } } fun scrollDpY(amount: Float, smooth: Boolean = true) { if (smooth) { val y = min(max(0f, yScrollDpDesired.value + amount), contentHeightDp.value - viewHeightDp.value) yScrollDpDesired.set(y) } else { val y = min(max(0f, yScrollDp.value + amount), contentHeightDp.value - viewHeightDp.value) yScrollDp.set(y) yScrollDpDesired.set(y) } } fun scrollRelativeX(relativeX: Float, smooth: Boolean = true) { val width = max(contentWidthDp.value, viewWidthDp.value) xScrollDpDesired.set((width - viewWidthDp.value) * relativeX) if (!smooth) { xScrollDp.set(xScrollDpDesired.value) } } fun scrollRelativeY(relativeY: Float, smooth: Boolean = true) { val height = max(contentHeightDp.value, viewHeightDp.value) yScrollDpDesired.set((height - viewHeightDp.value) * relativeY) if (!smooth) { yScrollDp.set(yScrollDpDesired.value) } } fun computeSmoothScrollPosDpX(): Float { return xScrollDp.value + computeSmoothScrollAmountDpX() } fun computeSmoothScrollPosDpY(): Float { return yScrollDp.value + computeSmoothScrollAmountDpY() } fun computeSmoothScrollAmountDpX(): Float { val error = xScrollDpDesired.value - xScrollDp.value return if (abs(error) < 1f) { error } else { var step = error * SMOOTHING_FAC * Time.deltaT if (abs(step) > abs(error)) { step = error } step } } fun computeSmoothScrollAmountDpY(): Float { val error = yScrollDpDesired.value - yScrollDp.value return if (abs(error) < 1f) { error } else { var step = error * SMOOTHING_FAC * Time.deltaT if (abs(step) > abs(error)) { step = error } step } } fun setSmoothScrollAmountDpX(step: Float) { val error = step / (SMOOTHING_FAC * Time.deltaT) xScrollDpDesired.set(xScrollDp.value + error) } fun setSmoothScrollAmountDpY(step: Float) { val error = step / (SMOOTHING_FAC * Time.deltaT) yScrollDpDesired.set(yScrollDp.value + error) } companion object { private const val SMOOTHING_FAC = 15f } } interface ScrollPaneScope : UiScope { override val modifier: ScrollPaneModifier } open class ScrollPaneModifier(surface: UiSurface) : UiModifier(surface) { var onScrollPosChanged: ((Float, Float) -> Unit)? by property(null) var allowOverscrollX by property(false) var allowOverscrollY by property(false) } fun <T: ScrollPaneModifier> T.allowOverScroll(x: Boolean, y: Boolean): T { allowOverscrollX = x allowOverscrollY = y return this } fun <T: ScrollPaneModifier> T.onScrollPosChanged(block: (Float, Float) -> Unit): T { onScrollPosChanged = block return this } inline fun UiScope.ScrollPane(state: ScrollState, block: ScrollPaneScope.() -> Unit): ScrollPaneScope { val scrollPane = uiNode.createChild(ScrollPaneNode::class, ScrollPaneNode.factory) scrollPane.state = state scrollPane.block() return scrollPane } open class ScrollPaneNode(parent: UiNode?, surface: UiSurface) : UiNode(parent, surface), ScrollPaneScope { override val modifier = ScrollPaneModifier(surface) lateinit var state: ScrollState override fun setBounds(minX: Float, minY: Float, maxX: Float, maxY: Float) { updateScrollPos() val scrollX = round(state.xScrollDp.use() * UiScale.measuredScale) val scrollY = round(state.yScrollDp.use() * UiScale.measuredScale) super.setBounds(minX - scrollX, minY - scrollY, maxX - scrollX, maxY - scrollY) } protected open fun updateScrollPos() { var currentScrollX = state.xScrollDp.use() var currentScrollY = state.yScrollDp.use() var desiredScrollX = state.xScrollDpDesired.use() var desiredScrollY = state.yScrollDpDesired.use() if (parent != null) { state.viewWidthDp.set(parent.widthPx / UiScale.measuredScale) state.viewHeightDp.set(parent.heightPx / UiScale.measuredScale) state.contentWidthDp.set(contentWidthPx / UiScale.measuredScale) state.contentHeightDp.set(contentHeightPx / UiScale.measuredScale) // clamp scroll positions to content size if (!modifier.allowOverscrollX) { if (currentScrollX + state.viewWidthDp.value > state.contentWidthDp.value) { currentScrollX = state.contentWidthDp.value - state.viewWidthDp.value } if (desiredScrollX + state.viewWidthDp.value > state.contentWidthDp.value) { desiredScrollX = state.contentWidthDp.value - state.viewWidthDp.value } state.xScrollDp.set(max(0f, currentScrollX)) state.xScrollDpDesired.set(max(0f, desiredScrollX)) } if (!modifier.allowOverscrollY) { if (currentScrollY + state.viewHeightDp.value > state.contentHeightDp.value) { currentScrollY = state.contentHeightDp.value - state.viewHeightDp.value } if (desiredScrollY + state.viewHeightDp.value > state.contentHeightDp.value) { desiredScrollY = state.contentHeightDp.value - state.viewHeightDp.value } state.yScrollDp.set(max(0f, currentScrollY)) state.yScrollDpDesired.set(max(0f, desiredScrollY)) } } state.xScrollDp.set(state.computeSmoothScrollPosDpX()) state.yScrollDp.set(state.computeSmoothScrollPosDpY()) if (state.xScrollDp.isStateChanged || state.yScrollDp.isStateChanged) { modifier.onScrollPosChanged?.invoke(state.xScrollDp.value, state.yScrollDp.value) } } companion object { val factory: (UiNode, UiSurface) -> ScrollPaneNode = { parent, surface -> ScrollPaneNode(parent, surface) } } }
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/ScrollPane.kt
2727335517
package info.nightscout.androidaps.utils import com.google.firebase.iid.FirebaseInstanceId object InstanceId { fun instanceId(): String { var id = FirebaseInstanceId.getInstance().id return id } }
core/src/main/java/info/nightscout/androidaps/utils/InstanceId.kt
4209374240
package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.setupwizard.SWEventListener import info.nightscout.androidaps.setupwizard.SWScreen import info.nightscout.androidaps.setupwizard.elements.* @Module @Suppress("unused") abstract class WizardModule { @ContributesAndroidInjector abstract fun swBreakInjector(): SWBreak @ContributesAndroidInjector abstract fun swButtonInjector(): SWButton @ContributesAndroidInjector abstract fun swEditNumberWithUnitsInjector(): SWEditNumberWithUnits @ContributesAndroidInjector abstract fun swEditStringInjector(): SWEditString @ContributesAndroidInjector abstract fun swEditEncryptedPasswordInjector(): SWEditEncryptedPassword @ContributesAndroidInjector abstract fun swEditUrlInjector(): SWEditUrl @ContributesAndroidInjector abstract fun swFragmentInjector(): SWFragment @ContributesAndroidInjector abstract fun swHtmlLinkInjector(): SWHtmlLink @ContributesAndroidInjector abstract fun swInfotextInjector(): SWInfotext @ContributesAndroidInjector abstract fun swItemInjector(): SWItem @ContributesAndroidInjector abstract fun swPluginInjector(): SWPlugin @ContributesAndroidInjector abstract fun swRadioButtonInjector(): SWRadioButton @ContributesAndroidInjector abstract fun swScreenInjector(): SWScreen @ContributesAndroidInjector abstract fun swEventListenerInjector(): SWEventListener }
app/src/main/java/info/nightscout/androidaps/dependencyInjection/WizardModule.kt
1545050417
package de.fabmax.kool.demo.physics.collision import de.fabmax.kool.AssetManager import de.fabmax.kool.KoolContext import de.fabmax.kool.demo.* import de.fabmax.kool.demo.menu.DemoMenu import de.fabmax.kool.math.* import de.fabmax.kool.math.spatial.BoundingBox import de.fabmax.kool.modules.ui2.* import de.fabmax.kool.physics.* import de.fabmax.kool.physics.geometry.* import de.fabmax.kool.pipeline.Attribute import de.fabmax.kool.pipeline.Texture2d import de.fabmax.kool.pipeline.ao.AoPipeline import de.fabmax.kool.pipeline.ibl.EnvironmentHelper import de.fabmax.kool.pipeline.ibl.EnvironmentMaps import de.fabmax.kool.pipeline.shadermodel.PbrMaterialNode import de.fabmax.kool.pipeline.shadermodel.StageInterfaceNode import de.fabmax.kool.pipeline.shadermodel.fragmentStage import de.fabmax.kool.pipeline.shadermodel.vertexStage import de.fabmax.kool.pipeline.shading.PbrMaterialConfig import de.fabmax.kool.pipeline.shading.PbrShader import de.fabmax.kool.pipeline.shading.pbrShader import de.fabmax.kool.scene.* import de.fabmax.kool.toString import de.fabmax.kool.util.* import kotlin.math.max import kotlin.math.roundToInt class CollisionDemo : DemoScene("Physics - Collision") { private lateinit var aoPipeline: AoPipeline private lateinit var ibl: EnvironmentMaps private lateinit var groundAlbedo: Texture2d private lateinit var groundNormal: Texture2d private val shadows = mutableListOf<ShadowMap>() private val shapeTypes = mutableListOf(*ShapeType.values()) private val selectedShapeType = mutableStateOf(6) private val numSpawnBodies = mutableStateOf(450) private val friction = mutableStateOf(0.5f) private val restitution = mutableStateOf(0.2f) private val drawBodyState = mutableStateOf(false) private val physicsTimeTxt = mutableStateOf("0.00 ms") private val activeActorsTxt = mutableStateOf("0") private val timeFactorTxt = mutableStateOf("1.00 x") private lateinit var physicsWorld: PhysicsWorld private val physicsStepper = SimplePhysicsStepper() private val bodies = mutableMapOf<ShapeType, MutableList<ColoredBody>>() private val shapeGenCtx = ShapeType.ShapeGeneratorContext() override suspend fun AssetManager.loadResources(ctx: KoolContext) { ibl = EnvironmentHelper.hdriEnvironment(mainScene, "${DemoLoader.hdriPath}/colorful_studio_1k.rgbe.png", this) groundAlbedo = loadAndPrepareTexture("${DemoLoader.materialPath}/tile_flat/tiles_flat_fine.png") groundNormal = loadAndPrepareTexture("${DemoLoader.materialPath}/tile_flat/tiles_flat_fine_normal.png") Physics.awaitLoaded() [email protected] = PhysicsWorld().apply { simStepper = physicsStepper } } override fun Scene.setupMainScene(ctx: KoolContext) { defaultCamTransform().apply { zoomMethod = OrbitInputTransform.ZoomMethod.ZOOM_TRANSLATE panMethod = yPlanePan() translationBounds = BoundingBox(Vec3f(-50f), Vec3f(50f)) minHorizontalRot = -90.0 maxHorizontalRot = -20.0 setZoom(75.0, min = 10.0) } (camera as PerspectiveCamera).apply { clipNear = 0.5f clipFar = 500f } val shadowMap = CascadedShadowMap(this, 0, maxRange = 300f) shadows.add(shadowMap) aoPipeline = AoPipeline.createForward(this) lighting.singleLight { setDirectional(Vec3f(0.8f, -1.2f, 1f)) } makeGround(ibl, physicsWorld) shapeGenCtx.material = Material(friction.value, friction.value, restitution.value) resetPhysics() shapeTypes.forEach { if (it != ShapeType.MIXED) { it.mesh.shader = instancedBodyShader(ibl) +it.mesh } } val matBuf = Mat4f() val removeBodies = mutableListOf<ColoredBody>() onUpdate += { for (i in shapeTypes.indices) { shapeTypes[i].instances.clear() } val activeColor = MutableColor(MdColor.RED.toLinear()) val inactiveColor = MutableColor(MdColor.LIGHT_GREEN.toLinear()) bodies.forEach { (type, typeBodies) -> type.instances.addInstances(typeBodies.size) { buf -> for (i in typeBodies.indices) { val body = typeBodies[i] matBuf.set(body.rigidActor.transform).scale(body.scale) buf.put(matBuf.matrix) if (drawBodyState.value) { if (body.rigidActor.isActive) { buf.put(activeColor.array) } else { buf.put(inactiveColor.array) } } else { buf.put(body.color.array) } if (body.rigidActor.position.length() > 500f) { removeBodies += body } } } if (removeBodies.isNotEmpty()) { removeBodies.forEach { body -> logI { "Removing out-of-range body" } typeBodies.remove(body) physicsWorld.removeActor(body.rigidActor) body.rigidActor.release() } removeBodies.clear() } } physicsTimeTxt.set("${physicsStepper.perfCpuTime.toString(2)} ms") activeActorsTxt.set("${physicsWorld.activeActors}") timeFactorTxt.set("${physicsStepper.perfTimeFactor.toString(2)} x") } +Skybox.cube(ibl.reflectionMap, 1f) physicsWorld.registerHandlers(this) } override fun dispose(ctx: KoolContext) { super.dispose(ctx) physicsWorld.clear() physicsWorld.release() shapeGenCtx.material.release() groundAlbedo.dispose() groundNormal.dispose() } private fun resetPhysics() { bodies.values.forEach { typedBodies -> typedBodies.forEach { physicsWorld.removeActor(it.rigidActor) it.rigidActor.release() } } bodies.clear() val types = if (shapeTypes[selectedShapeType.value] == ShapeType.MIXED) { ShapeType.values().toList().filter { it != ShapeType.MIXED } } else { listOf(shapeTypes[selectedShapeType.value]) } shapeGenCtx.material.release() shapeGenCtx.material = Material(friction.value, friction.value, restitution.value) val stacks = max(1, numSpawnBodies.value / 50) val centers = makeCenters(stacks) val rand = Random(39851564) for (i in 0 until numSpawnBodies.value) { val layer = i / stacks val stack = i % stacks val color = MdColor.PALETTE[layer % MdColor.PALETTE.size].toLinear() val x = centers[stack].x * 10f + rand.randomF(-1f, 1f) val z = centers[stack].y * 10f + rand.randomF(-1f, 1f) val y = layer * 5f + 10f val type = types[rand.randomI(types.indices)] val shapes = type.generateShapes(shapeGenCtx) val body = RigidDynamic(shapes.mass) shapes.primitives.forEach { s -> body.attachShape(s) // after shape is attached, geometry can be released s.geometry.release() } body.updateInertiaFromShapesAndMass() body.position = Vec3f(x, y, z) body.setRotation(Mat3f().rotate(rand.randomF(-90f, 90f), rand.randomF(-90f, 90f), rand.randomF(-90f, 90f))) physicsWorld.addActor(body) val coloredBody = ColoredBody(body, color, shapes) bodies.getOrPut(type) { mutableListOf() } += coloredBody } } private fun makeCenters(stacks: Int): List<Vec2f> { val dir = MutableVec2f(1f, 0f) val centers = mutableListOf(Vec2f(0f, 0f)) var steps = 1 var stepsSteps = 1 while (centers.size < stacks) { for (i in 1..steps) { centers += MutableVec2f(centers.last()).add(dir) if (centers.size == stacks) { break } } dir.rotate(90f) if (stepsSteps++ == 2) { stepsSteps = 1 steps++ } } return centers } private fun Scene.makeGround(ibl: EnvironmentMaps, physicsWorld: PhysicsWorld) { val frame = mutableListOf<RigidStatic>() val frameSimFilter = FilterData { setCollisionGroup(1) clearCollidesWith(1) } val groundMaterial = Material(0.5f, 0.5f, 0.2f) val groundShape = BoxGeometry(Vec3f(100f, 1f, 100f)) val ground = RigidStatic().apply { attachShape(Shape(groundShape, groundMaterial)) position = Vec3f(0f, -0.5f, 0f) simulationFilterData = frameSimFilter } physicsWorld.addActor(ground) val frameLtShape = BoxGeometry(Vec3f(3f, 6f, 100f)) val frameLt = RigidStatic().apply { attachShape(Shape(frameLtShape, groundMaterial)) position = Vec3f(-51.5f, 2f, 0f) simulationFilterData = frameSimFilter } physicsWorld.addActor(frameLt) frame += frameLt val frameRtShape = BoxGeometry(Vec3f(3f, 6f, 100f)) val frameRt = RigidStatic().apply { attachShape(Shape(frameRtShape, groundMaterial)) position = Vec3f(51.5f, 2f, 0f) simulationFilterData = frameSimFilter } physicsWorld.addActor(frameRt) frame += frameRt val frameFtShape = BoxGeometry(Vec3f(106f, 6f, 3f)) val frameFt = RigidStatic().apply { attachShape(Shape(frameFtShape, groundMaterial)) position = Vec3f(0f, 2f, 51.5f) simulationFilterData = frameSimFilter } physicsWorld.addActor(frameFt) frame += frameFt val frameBkShape = BoxGeometry(Vec3f(106f, 6f, 3f)) val frameBk = RigidStatic().apply { attachShape(Shape(frameBkShape, groundMaterial)) position = Vec3f(0f, 2f, -51.5f) simulationFilterData = frameSimFilter } physicsWorld.addActor(frameBk) frame += frameBk // render textured ground box +textureMesh(isNormalMapped = true) { generate { vertexModFun = { texCoord.set(x / 10, z / 10) } cube { size.set(groundShape.size) origin.set(size).scale(-0.5f).add(ground.position) } } shader = pbrShader { roughness = 0.75f shadowMaps += shadows useImageBasedLighting(ibl) useScreenSpaceAmbientOcclusion(aoPipeline.aoMap) useAlbedoMap(groundAlbedo) useNormalMap(groundNormal) } } // render frame +colorMesh { generate { frame.forEach { val shape = it.shapes[0].geometry as BoxGeometry cube { size.set(shape.size) origin.set(size).scale(-0.5f).add(it.position) } } } shader = pbrShader { roughness = 0.75f shadowMaps += shadows useImageBasedLighting(ibl) useScreenSpaceAmbientOcclusion(aoPipeline.aoMap) useStaticAlbedo(MdColor.BLUE_GREY toneLin 700) } } } private fun instancedBodyShader(ibl: EnvironmentMaps): PbrShader { val cfg = PbrMaterialConfig().apply { roughness = 1f isInstanced = true shadowMaps += shadows useImageBasedLighting(ibl) useScreenSpaceAmbientOcclusion(aoPipeline.aoMap) useStaticAlbedo(Color.WHITE) } val model = PbrShader.defaultPbrModel(cfg).apply { val ifInstColor: StageInterfaceNode vertexStage { ifInstColor = stageInterfaceNode("ifInstColor", instanceAttributeNode(Attribute.COLORS).output) } fragmentStage { findNodeByType<PbrMaterialNode>()!!.apply { inAlbedo = ifInstColor.output } } } return PbrShader(cfg, model) } private class ColoredBody(val rigidActor: RigidActor, val color: MutableColor, bodyShapes: ShapeType.CollisionShapes) { val scale = MutableVec3f() init { when (val shape = rigidActor.shapes[0].geometry) { is BoxGeometry -> { if (rigidActor.shapes.size == 1) { // Box scale.set(shape.size) } else { // Multi shape val s = shape.size.z / 2f scale.set(s, s, s) } } is CapsuleGeometry -> scale.set(shape.radius, shape.radius, shape.radius) is ConvexMeshGeometry -> { val s = bodyShapes.scale scale.set(s, s, s) } is CylinderGeometry -> scale.set(shape.length, shape.radius, shape.radius) is SphereGeometry -> scale.set(shape.radius, shape.radius, shape.radius) } } } override fun createMenu(menu: DemoMenu, ctx: KoolContext) = menuSurface { MenuRow { Text("Body shape") { labelStyle() } ComboBox { modifier .width(Grow.Std) .margin(start = sizes.largeGap) .items(shapeTypes) .selectedIndex(selectedShapeType.use()) .onItemSelected { selectedShapeType.set(it) } } } MenuSlider2("Number of Bodies", numSpawnBodies.use().toFloat(), 50f, 2000f, { "${it.roundToInt()}" }) { numSpawnBodies.set(it.roundToInt()) } MenuSlider2("Friction", friction.use(), 0f, 2f) { friction.set(it) } MenuSlider2("Restitution", restitution.use(), 0f, 1f) { restitution.set(it) } Button("Apply settings") { modifier .alignX(AlignmentX.Center) .width(Grow.Std) .margin(horizontal = 16.dp, vertical = 24.dp) .onClick { resetPhysics() } } Text("Statistics") { sectionTitleStyle() } MenuRow { LabeledSwitch("Show body state", drawBodyState) } MenuRow { Text("Active actors") { labelStyle(Grow.Std) } Text(activeActorsTxt.use()) { labelStyle() } } MenuRow { Text("Physics step CPU time") { labelStyle(Grow.Std) } Text(physicsTimeTxt.use()) { labelStyle() } } MenuRow { Text("Time factor") { labelStyle(Grow.Std) } Text(timeFactorTxt.use()) { labelStyle() } } } }
kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/physics/collision/CollisionDemo.kt
793071227
// 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 import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtNamedFunction fun KtElement.isMainFunction(computedDescriptor: DeclarationDescriptor? = null): Boolean { if (this !is KtNamedFunction) return false val mainFunctionDetector = MainFunctionDetector(languageVersionSettings) { it.resolveToDescriptorIfAny() } if (computedDescriptor != null) { return mainFunctionDetector.isMain(computedDescriptor) } return mainFunctionDetector.isMain(this) }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/mainDetectorUtil.kt
2978907505
actual fun foo(p: Any): Any { return p }
plugins/kotlin/idea/tests/testData/slicer/mpp/expectFunctionResultOut/jvm/jvm.kt
827672476
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * econsim-tr01 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01 import org.joda.time.DateTime /** * @author Dmitri Pisarenko ([email protected]) * @version $Id$ * @since 1.0 */ class Simulation1(val logTarget:StringBuilder, val flows:MutableList<ResourceFlow>, simParametersProvider: SimParametersProvider) : DefaultSimulation(simParametersProvider) { val foodStorage = DefaultResourceStorage("FoodStorage") val farmer = Farmer( foodStorage, flows, simParametersProvider.maxDaysWithoutFood, simParametersProvider.dailyPotatoConsumption ) override fun createSensors(): List<ISensor> = listOf( Accountant( foodStorage, farmer, logTarget) ) override fun createAgents(): List<IAgent> { foodStorage.put( Resource.POTATO.name, (simParametersProvider as SimParametersProvider).initialAmountOfPotatoes ) val agents = listOf( farmer, Field(), Nature() ) return agents } override fun continueCondition(tick: DateTime): Boolean = farmer.alive }
src/main/java/cc/altruix/econsimtr01/Simulation1.kt
3406654407
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.editor import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.testFramework.EditorTestUtil import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.formatter.KotlinObsoleteCodeStyle import org.jetbrains.kotlin.idea.formatter.kotlinCommonSettings import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.configureCodeStyleAndRun import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class TypedHandlerTest : KotlinLightCodeInsightFixtureTestCase() { private val dollar = '$' fun testTypeStringTemplateStart() = doTypeTest( '{', """val x = "$<caret>" """, """val x = "$dollar{}" """ ) fun testAutoIndentRightOpenBrace() = doTypeTest( '{', "fun test() {\n" + "<caret>\n" + "}", "fun test() {\n" + " {<caret>}\n" + "}" ) fun testAutoIndentLeftOpenBrace() = doTypeTest( '{', "fun test() {\n" + " <caret>\n" + "}", "fun test() {\n" + " {<caret>}\n" + "}" ) fun testTypeStringTemplateStartWithCloseBraceAfter() = doTypeTest( '{', """fun foo() { "$<caret>" }""", """fun foo() { "$dollar{}" }""" ) fun testTypeStringTemplateStartBeforeStringWithExistingDollar() = doTypeTest( '{', """fun foo() { "$<caret>something" }""", """fun foo() { "$dollar{something" }""" ) fun testTypeStringTemplateStartBeforeStringWithNoDollar() = doTypeTest( "$dollar{", """fun foo() { "<caret>something" }""", """fun foo() { "$dollar{<caret>}something" }""" ) fun testTypeStringTemplateWithUnmatchedBrace() = doTypeTest( "$dollar{", """val a = "<caret>bar}foo"""", """val a = "$dollar{<caret>bar}foo"""" ) fun testTypeStringTemplateWithUnmatchedBraceComplex() = doTypeTest( "$dollar{", """val a = "<caret>bar + more}foo"""", """val a = "$dollar{<caret>}bar + more}foo"""" ) fun testTypeStringTemplateStartInStringWithBraceLiterals() = doTypeTest( "$dollar{", """val test = "{ code <caret>other }"""", """val test = "{ code $dollar{<caret>}other }"""" ) fun testTypeStringTemplateStartInEmptyString() = doTypeTest( '{', """fun foo() { "$<caret>" }""", """fun foo() { "$dollar{<caret>}" }""" ) fun testKT3575() = doTypeTest( '{', """val x = "$<caret>]" """, """val x = "$dollar{}]" """ ) fun testAutoCloseRawStringInEnd() = doTypeTest( '"', """val x = ""<caret>""", """val x = ""${'"'}<caret>""${'"'}""" ) fun testNoAutoCloseRawStringInEnd() = doTypeTest( '"', """val x = ""${'"'}<caret>""", """val x = ""${'"'}"""" ) fun testAutoCloseRawStringInMiddle() = doTypeTest( '"', """ val x = ""<caret> val y = 12 """.trimIndent(), """ val x = ""${'"'}<caret>""${'"'} val y = 12 """.trimIndent() ) fun testNoAutoCloseBetweenMultiQuotes() = doTypeTest( '"', """val x = ""${'"'}<caret>${'"'}""/**/""", """val x = ""${'"'}${'"'}<caret>""/**/""" ) fun testNoAutoCloseBetweenMultiQuotes1() = doTypeTest( '"', """val x = ""${'"'}"<caret>"${'"'}/**/""", """val x = ""${'"'}""<caret>${'"'}/**/""" ) fun testNoAutoCloseAfterEscape() = doTypeTest( '"', """val x = "\""<caret>""", """val x = "\""${'"'}<caret>"""" ) fun testAutoCloseBraceInFunctionDeclaration() = doTypeTest( '{', "fun foo() <caret>", "fun foo() {<caret>}" ) fun testAutoCloseBraceInLocalFunctionDeclaration() = doTypeTest( '{', "fun foo() {\n" + " fun bar() <caret>\n" + "}", "fun foo() {\n" + " fun bar() {<caret>}\n" + "}" ) fun testAutoCloseBraceInAssignment() = doTypeTest( '{', "fun foo() {\n" + " val a = <caret>\n" + "}", "fun foo() {\n" + " val a = {<caret>}\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedIfSurroundOnSameLine() = doTypeTest( '{', "fun foo() {\n" + " if() <caret>foo()\n" + "}", "fun foo() {\n" + " if() {foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedElseSurroundOnSameLine() = doTypeTest( '{', "fun foo() {\n" + " if(true) {} else <caret>foo()\n" + "}", "fun foo() {\n" + " if(true) {} else {foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedTryOnSameLine() = doTypeTest( '{', "fun foo() {\n" + " try <caret>foo()\n" + "}", "fun foo() {\n" + " try {foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedCatchOnSameLine() = doTypeTest( '{', "fun foo() {\n" + " try {} catch (e: Exception) <caret>foo()\n" + "}", "fun foo() {\n" + " try {} catch (e: Exception) {foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedFinallyOnSameLine() = doTypeTest( '{', "fun foo() {\n" + " try {} catch (e: Exception) finally <caret>foo()\n" + "}", "fun foo() {\n" + " try {} catch (e: Exception) finally {foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedWhileSurroundOnSameLine() = doTypeTest( '{', "fun foo() {\n" + " while() <caret>foo()\n" + "}", "fun foo() {\n" + " while() {foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedWhileSurroundOnNewLine() = doTypeTest( '{', "fun foo() {\n" + " while()\n" + "<caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " while()\n" + " {\n" + " foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedIfSurroundOnOtherLine() = doTypeTest( '{', "fun foo() {\n" + " if(true) <caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " if(true) {<caret>\n" + " foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedElseSurroundOnOtherLine() = doTypeTest( '{', "fun foo() {\n" + " if(true) {} else <caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " if(true) {} else {<caret>\n" + " foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedTryOnOtherLine() = doTypeTest( '{', "fun foo() {\n" + " try <caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " try {<caret>\n" + " foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedIfSurroundOnNewLine() = doTypeTest( '{', "fun foo() {\n" + " if(true)\n" + " <caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " if(true)\n" + " {<caret>\n" + " foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedElseSurroundOnNewLine() = doTypeTest( '{', "fun foo() {\n" + " if(true) {} else\n" + " <caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " if(true) {} else\n" + " {<caret>\n" + " foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedTryOnNewLine() = doTypeTest( '{', "fun foo() {\n" + " try\n" + " <caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " try\n" + " {<caret>\n" + " foo()\n" + "}" ) fun testAutoCloseBraceInsideFor() = doTypeTest( '{', "fun foo() {\n" + " for (elem in some.filter <caret>) {\n" + " }\n" + "}", "fun foo() {\n" + " for (elem in some.filter {<caret>}) {\n" + " }\n" + "}" ) fun testAutoCloseBraceInsideForAfterCloseParen() = doTypeTest( '{', "fun foo() {\n" + " for (elem in some.foo(true) <caret>) {\n" + " }\n" + "}", "fun foo() {\n" + " for (elem in some.foo(true) {<caret>}) {\n" + " }\n" + "}" ) fun testAutoCloseBraceBeforeIf() = doTypeTest( '{', "fun foo() {\n" + " <caret>if (true) {}\n" + "}", "fun foo() {\n" + " {<caret>if (true) {}\n" + "}" ) fun testAutoCloseBraceInIfCondition() = doTypeTest( '{', "fun foo() {\n" + " if (some.hello (12) <caret>)\n" + "}", "fun foo() {\n" + " if (some.hello (12) {<caret>})\n" + "}" ) fun testInsertSpaceAfterRightBraceOfNestedLambda() = doTypeTest( '{', "val t = Array(100) { Array(200) <caret>}", "val t = Array(100) { Array(200) {<caret>} }" ) fun testAutoInsertParenInStringLiteral() = doTypeTest( '(', """fun f() { println("$dollar{f<caret>}") }""", """fun f() { println("$dollar{f(<caret>)}") }""" ) fun testAutoInsertParenInCode() = doTypeTest( '(', """fun f() { val a = f<caret> }""", """fun f() { val a = f(<caret>) }""" ) fun testSplitStringByEnter() = doTypeTest( '\n', """val s = "foo<caret>bar"""", "val s = \"foo\" +\n" + " \"bar\"" ) fun testSplitStringByEnterEmpty() = doTypeTest( '\n', """val s = "<caret>"""", "val s = \"\" +\n" + " \"\"" ) fun testSplitStringByEnterBeforeEscapeSequence() = doTypeTest( '\n', """val s = "foo<caret>\nbar"""", "val s = \"foo\" +\n" + " \"\\nbar\"" ) fun testSplitStringByEnterBeforeSubstitution() = doTypeTest( '\n', """val s = "foo<caret>${dollar}bar"""", "val s = \"foo\" +\n" + " \"${dollar}bar\"" ) fun testSplitStringByEnterAddParentheses() = doTypeTest( '\n', """val l = "foo<caret>bar".length()""", "val l = (\"foo\" +\n" + " \"bar\").length()" ) fun testSplitStringByEnterExistingParentheses() = doTypeTest( '\n', """val l = ("asdf" + "foo<caret>bar").length()""", "val l = (\"asdf\" + \"foo\" +\n" + " \"bar\").length()" ) fun testTypeLtInFunDeclaration() { doLtGtTest("fun <caret>") } fun testTypeLtInOngoingConstructorCall() { doLtGtTest("fun test() { Collection<caret> }") } fun testTypeLtInClassDeclaration() { doLtGtTest("class Some<caret> {}") } fun testTypeLtInPropertyType() { doLtGtTest("val a: List<caret> ") } fun testTypeLtInExtensionFunctionReceiver() { doLtGtTest("fun <T> Collection<caret> ") } fun testTypeLtInFunParam() { doLtGtTest("fun some(a : HashSet<caret>)") } fun testTypeLtInFun() { doLtGtTestNoAutoClose("fun some() { <<caret> }") } fun testTypeLtInLess() { doLtGtTestNoAutoClose("fun some() { val a = 12; a <<caret> }") } fun testColonOfSuperTypeList() { doTypeTest( ':', """ |open class A |class B |<caret> """, """ |open class A |class B | :<caret> """ ) } fun testColonOfSuperTypeListInObject() { doTypeTest( ':', """ |interface A |object B |<caret> """, """ |interface A |object B | :<caret> """ ) } fun testColonOfSuperTypeListInCompanionObject() { doTypeTest( ':', """ |interface A |class B { | companion object | <caret> |} """, """ |interface A |class B { | companion object | :<caret> |} """ ) } fun testColonOfSuperTypeListBeforeBody() { doTypeTest( ':', """ |open class A |class B |<caret> { |} """, """ |open class A |class B | :<caret> { |} """ ) } fun testColonOfSuperTypeListNotNullIndent() { doTypeTest( ':', """ |fun test() { | open class A | class B | <caret> |} """, """ |fun test() { | open class A | class B | :<caret> |} """ ) } fun testChainCallContinueWithDot() { doTypeTest( '.', """ |class Test{ fun test() = this } |fun some() { | Test() | <caret> |} """, """ |class Test{ fun test() = this } |fun some() { | Test() | .<caret> |} """, enableKotlinObsoleteCodeStyle, ) } fun testChainCallContinueWithDotWithOfficialCodeStyle() { doTypeTest( '.', """ |class Test{ fun test() = this } |fun some() { | Test() | <caret> |} """, """ |class Test{ fun test() = this } |fun some() { | Test() | .<caret> |} """, ) } fun testChainCallContinueWithSafeCall() { doTypeTest( '.', """ |class Test{ fun test() = this } |fun some() { | Test() | ?<caret> |} """, """ |class Test{ fun test() = this } |fun some() { | Test() | ?.<caret> |} """, enableKotlinObsoleteCodeStyle ) } fun testChainCallContinueWithSafeCallWithOfficialCodeStyle() { doTypeTest( '.', """ |class Test{ fun test() = this } |fun some() { | Test() | ?<caret> |} """, """ |class Test{ fun test() = this } |fun some() { | Test() | ?.<caret> |} """, enableKotlinObsoleteCodeStyle ) } fun testContinueWithElvis() { doTypeTest( ':', """ |fun test(): Any? = null |fun some() { | test() | ?<caret> |} """, """ |fun test(): Any? = null |fun some() { | test() | ?:<caret> |} """, enableKotlinObsoleteCodeStyle ) } fun testContinueWithElvisWithOfficialCodeStyle() { doTypeTest( ':', """ |fun test(): Any? = null |fun some() { | test() | ?<caret> |} """, """ |fun test(): Any? = null |fun some() { | test() | ?:<caret> |} """ ) } fun testContinueWithOr() { doTypeTest( '|', """ |fun some() { | if (true | |<caret>) |} """, """ |fun some() { | if (true | ||<caret>) |} """, enableKotlinObsoleteCodeStyle ) } fun testContinueWithOrWithOfficialCodeStyle() { doTypeTest( '|', """ |fun some() { | if (true | |<caret>) |} """, """ |fun some() { | if (true | ||<caret>) |} """ ) } fun testContinueWithAnd() { doTypeTest( '&', """ |fun some() { | val test = true | &<caret> |} """, """ |fun some() { | val test = true | &&<caret> |} """ ) } fun testSpaceAroundRange() { doTypeTest( '.', """ | val test = 1 <caret> """, """ | val test = 1 .<caret> """ ) } fun testIndentBeforeElseWithBlock() { doTypeTest( '\n', """ |fun test(b: Boolean) { | if (b) { | }<caret> | else if (!b) { | } |} """, """ |fun test(b: Boolean) { | if (b) { | } | <caret> | else if (!b) { | } |} """ ) } fun testIndentBeforeElseWithoutBlock() { doTypeTest( '\n', """ |fun test(b: Boolean) { | if (b) | foo()<caret> | else { | } |} """, """ |fun test(b: Boolean) { | if (b) | foo() | <caret> | else { | } |} """ ) } fun testIndentOnFinishedVariableEndAfterEquals() { doTypeTest( '\n', """ |fun test() { | val a =<caret> | foo() |} """, """ |fun test() { | val a = | <caret> | foo() |} """, enableKotlinObsoleteCodeStyle ) } fun testIndentOnFinishedVariableEndAfterEqualsWithOfficialCodeStyle() { doTypeTest( '\n', """ |fun test() { | val a =<caret> | foo() |} """, """ |fun test() { | val a = | <caret> | foo() |} """ ) } fun testIndentNotFinishedVariableEndAfterEquals() { doTypeTest( '\n', """ |fun test() { | val a =<caret> |} """, """ |fun test() { | val a = | <caret> |} """, enableKotlinObsoleteCodeStyle ) } fun testIndentNotFinishedVariableEndAfterEqualsWithOfficialCodeStyle() { doTypeTest( '\n', """ |fun test() { | val a =<caret> |} """, """ |fun test() { | val a = | <caret> |} """ ) } fun testSmartEnterWithTabsOnConstructorParameters() { doTypeTest( '\n', """ |class A( | a: Int,<caret> |) """, """ |class A( | a: Int, | <caret> |) """ ) { enableSmartEnter(it) enableTabs(it) } } fun testSmartEnterWithTabsInMethodParameters() { doTypeTest( '\n', """ |fun method( | arg1: String,<caret> |) {} """, """ |fun method( | arg1: String, | <caret> |) {} """ ) { enableSmartEnter(it) enableTabs(it) } } fun testEnterWithoutLineBreakBeforeClosingBracketInMethodParameters() { doTypeTest( '\n', """ |fun method( | arg1: String,<caret>) {} """, """ |fun method( | arg1: String, |<caret>) {} """, enableSmartEnter ) } fun testSmartEnterWithTrailingCommaAndWhitespaceBeforeLineBreak() { doTypeTest( '\n', """ |fun method( | arg1: String, <caret> |) {} """, """ |fun method( | arg1: String, | <caret> |) {} """, enableSmartEnter ) } fun testSmartEnterBetweenOpeningAndClosingBrackets() { doTypeTest( '\n', """ |fun method(<caret>) {} """, """ |fun method( | <caret> |) {} """ ) { enableKotlinObsoleteCodeStyle(it) enableSmartEnter(it) } } fun testSmartEnterBetweenOpeningAndClosingBracketsWithOfficialCodeStyle() { doTypeTest( '\n', """ |fun method(<caret>) {} """, """ |fun method( | <caret> |) {} """, enableSmartEnter ) } private val enableSettingsWithInvertedAlignWhenMultiline: (CodeStyleSettings) -> Unit get() = { val settings = it.kotlinCommonSettings settings.ALIGN_MULTILINE_PARAMETERS = !settings.ALIGN_MULTILINE_PARAMETERS settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS = !settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS } fun testSmartEnterWithTabsOnConstructorParametersWithInvertedAlignWhenMultiline() { doTypeTest( '\n', """ |class A( | a: Int,<caret> |) """, """ |class A( | a: Int, | <caret> |) """ ) { enableKotlinObsoleteCodeStyle(it) enableSettingsWithInvertedAlignWhenMultiline(it) enableSmartEnter(it) enableTabs(it) } } fun testSmartEnterWithTabsOnConstructorParametersWithInvertedAlignWhenMultilineWithOfficialCodeStyle() { doTypeTest( '\n', """ |class A( | a: Int,<caret> |) """, """ |class A( | a: Int, | <caret> |) """ ) { enableSettingsWithInvertedAlignWhenMultiline(it) enableSmartEnter(it) enableTabs(it) } } fun testSmartEnterWithTabsInMethodParametersWithInvertedAlignWhenMultiline() { doTypeTest( '\n', """ |fun method( | arg1: String,<caret> |) {} """, """ |fun method( | arg1: String, | <caret> |) {} """ ) { enableKotlinObsoleteCodeStyle(it) enableSettingsWithInvertedAlignWhenMultiline(it) enableSmartEnter(it) enableTabs(it) } } fun testEnterWithoutLineBreakBeforeClosingBracketInMethodParametersWithInvertedAlignWhenMultiline() { doTypeTest( '\n', """ |fun method( | arg1: String,<caret>) {} """, """ |fun method( | arg1: String, |<caret>) {} """, enableSettingsWithInvertedAlignWhenMultiline ) } fun testEnterWithTrailingCommaAndWhitespaceBeforeLineBreakWithInvertedAlignWhenMultiline() { doTypeTest( '\n', """ |fun method( | arg1: String, <caret> |) {} """, """ |fun method( | arg1: String, | <caret> |) {} """, enableSettingsWithInvertedAlignWhenMultiline ) } fun testSmartEnterBetweenOpeningAndClosingBracketsWithInvertedAlignWhenMultiline() { doTypeTest( '\n', """ |fun method(<caret>) {} """, """ |fun method( | <caret> |) {} """ ) { enableKotlinObsoleteCodeStyle(it) enableSettingsWithInvertedAlignWhenMultiline(it) enableSmartEnter(it) } } fun testSmartEnterBetweenOpeningAndClosingBracketsWithInvertedAlignWhenMultilineWithOfficialCodeStyle() { doTypeTest( '\n', """ |fun method(<caret>) {} """, """ |fun method( | <caret> |) {} """ ) { enableSettingsWithInvertedAlignWhenMultiline(it) enableSmartEnter(it) } } fun testAutoIndentInWhenClause() { doTypeTest( '\n', """ |fun test() { | when (2) { | is Int -><caret> | } |} """, """ |fun test() { | when (2) { | is Int -> | <caret> | } |} """ ) } fun testValInserterOnClass() = testValInserter(',', """data class xxx(val x: Int<caret>)""", """data class xxx(val x: Int,<caret>)""") fun testValInserterOnSimpleDataClass() = testValInserter(',', """data class xxx(x: Int<caret>)""", """data class xxx(val x: Int,<caret>)""") fun testValInserterOnValWithComment() = testValInserter(',', """data class xxx(x: Int /*comment*/ <caret>)""", """data class xxx(val x: Int /*comment*/ ,<caret>)""") fun testValInserterOnValWithInitializer() = testValInserter(',', """data class xxx(x: Int = 2<caret>)""", """data class xxx(val x: Int = 2,<caret>)""") fun testValInserterOnValWithInitializerWithOutType() = testValInserter(',', """data class xxx(x = 2<caret>)""", """data class xxx(x = 2,<caret>)""") fun testValInserterOnValWithGenericType() = testValInserter(',', """data class xxx(x: A<B><caret>)""", """data class xxx(val x: A<B>,<caret>)""") fun testValInserterOnValWithNoType() = testValInserter(',', """data class xxx(x<caret>)""", """data class xxx(x,<caret>)""") fun testValInserterOnValWithIncompleteGenericType() = testValInserter(',', """data class xxx(x: A<B,C<caret>)""", """data class xxx(x: A<B,C,<caret>)""") fun testValInserterOnValWithInvalidComma() = testValInserter(',', """data class xxx(x:<caret> A<B>)""", """data class xxx(x:,<caret> A<B>)""") fun testValInserterOnValWithInvalidGenericType() = testValInserter(',', """data class xxx(x: A><caret>)""", """data class xxx(x: A>,<caret>)""") fun testValInserterOnInMultiline() = testValInserter( ',', """ |data class xxx( | val a: A, | b: B<caret> | val c: C |) """, """ |data class xxx( | val a: A, | val b: B,<caret> | val c: C |) """ ) fun testValInserterOnValInsertedInsideOtherParameters() = testValInserter( ',', """data class xxx(val a: A, b: A<caret>val c: A)""", """data class xxx(val a: A, val b: A,<caret>val c: A)""" ) fun testValInserterOnSimpleInlineClass() = testValInserter(')', """inline class xxx(a: A<caret>)""", """inline class xxx(val a: A)<caret>""") fun testValInserterOnValInsertedWithSquare() = testValInserter(')', """data class xxx(val a: A, b: A<caret>)""", """data class xxx(val a: A, val b: A)<caret>""") fun testValInserterOnTypingMissedSquare() = testValInserter(')', """data class xxx(val a: A, b: A<caret>""", """data class xxx(val a: A, val b: A)<caret>""") fun testValInserterWithDisabledSetting() = testValInserter(',', """data class xxx(x: Int<caret>)""", """data class xxx(x: Int,<caret>)""", inserterEnabled = false) fun testEnterInFunctionWithExpressionBody() { doTypeTest( '\n', """ |fun test() =<caret> """, """ |fun test() = | <caret> """ ) } fun testEnterInMultiDeclaration() { doTypeTest( '\n', """ |fun test() { | val (a, b) =<caret> |} """, """ |fun test() { | val (a, b) = | <caret> |} """ ) } fun testEnterInVariableDeclaration() { doTypeTest( '\n', """ |val test =<caret> """, """ |val test = | <caret> """ ) } fun testMoveThroughGT() { myFixture.configureByText("a.kt", "val a: List<Set<Int<caret>>>") EditorTestUtil.performTypingAction(editor, '>') EditorTestUtil.performTypingAction(editor, '>') myFixture.checkResult("val a: List<Set<Int>><caret>") } fun testCharClosingQuote() { doTypeTest('\'', "val c = <caret>", "val c = ''") } private val enableSmartEnter: (CodeStyleSettings) -> Unit get() = { val indentOptions = it.getLanguageIndentOptions(KotlinLanguage.INSTANCE) indentOptions.SMART_TABS = true } private val enableTabs: (CodeStyleSettings) -> Unit get() = { val indentOptions = it.getLanguageIndentOptions(KotlinLanguage.INSTANCE) indentOptions.USE_TAB_CHARACTER = true } private fun doTypeTest(ch: Char, beforeText: String, afterText: String, settingsModifier: ((CodeStyleSettings) -> Unit) = { }) { doTypeTest(ch.toString(), beforeText, afterText, settingsModifier) } private fun doTypeTest(text: String, beforeText: String, afterText: String, settingsModifier: ((CodeStyleSettings) -> Unit) = { }) { configureCodeStyleAndRun(project, configurator = { settingsModifier(it) }) { myFixture.configureByText("a.kt", beforeText.trimMargin()) for (ch in text) { myFixture.type(ch) } myFixture.checkResult(afterText.trimMargin()) } } private fun testValInserter(ch: Char, beforeText: String, afterText: String, inserterEnabled: Boolean = true) { val editorOptions = KotlinEditorOptions.getInstance() val wasEnabled = editorOptions.isAutoAddValKeywordToDataClassParameters try { editorOptions.isAutoAddValKeywordToDataClassParameters = inserterEnabled doTypeTest(ch, beforeText, afterText) } finally { editorOptions.isAutoAddValKeywordToDataClassParameters = wasEnabled } } private fun doLtGtTestNoAutoClose(initText: String) { doLtGtTest(initText, false) } private fun doLtGtTest(initText: String, shouldCloseBeInsert: Boolean) { myFixture.configureByText("a.kt", initText) EditorTestUtil.performTypingAction(editor, '<') myFixture.checkResult( if (shouldCloseBeInsert) initText.replace("<caret>", "<<caret>>") else initText.replace( "<caret>", "<<caret>" ) ) EditorTestUtil.performTypingAction(editor, EditorTestUtil.BACKSPACE_FAKE_CHAR) myFixture.checkResult(initText) } private fun doLtGtTest(initText: String) { doLtGtTest(initText, true) } private val enableKotlinObsoleteCodeStyle: (CodeStyleSettings) -> Unit = { KotlinObsoleteCodeStyle.apply(it) } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/editor/TypedHandlerTest.kt
4293252161
package com.zhou.android.main import android.graphics.Bitmap import android.graphics.BitmapFactory import android.view.ViewGroup import android.widget.Button import android.widget.RelativeLayout import com.zhou.android.R import com.zhou.android.common.BaseActivity import com.zhou.android.ui.FocusDrawView import kotlinx.android.synthetic.main.layout_app.view.* /** * Created by mxz on 2019/9/3. */ class FocusDrawActivity : BaseActivity() { private lateinit var focus: FocusDrawView private lateinit var b: Bitmap override fun setContentView() { b = BitmapFactory.decodeResource(resources, R.drawable.pic_head) val layout = RelativeLayout(this).apply { layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) } focus = FocusDrawView(this) layout.addView(focus) val btn = Button(this).apply { text = "加载位图" layoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT).apply { addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) addRule(RelativeLayout.CENTER_HORIZONTAL) bottomMargin = 20 } setOnClickListener { focus.setBitmap(b) } } layout.addView(btn) setContentView(layout) } override fun init() { } override fun addListener() { } }
app/src/main/java/com/zhou/android/main/FocusDrawActivity.kt
1708640759
// 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.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.AbstractExternalEntityData import com.intellij.openapi.externalSystem.model.project.AbstractNamedData import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.util.Key import com.intellij.serialization.PropertyMapping import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.config.ExternalSystemRunTask import org.jetbrains.kotlin.gradle.* import org.jetbrains.kotlin.idea.util.CopyableDataNodeUserDataProperty import org.jetbrains.plugins.gradle.util.GradleConstants import java.io.File import java.io.Serializable import com.intellij.openapi.externalSystem.model.Key as ExternalKey var DataNode<out ModuleData>.kotlinSourceSet: KotlinSourceSetInfo? by CopyableDataNodeUserDataProperty(Key.create("KOTLIN_SOURCE_SET")) val DataNode<out ModuleData>.kotlinAndroidSourceSets: List<KotlinSourceSetInfo>? get() = ExternalSystemApiUtil.getChildren(this, KotlinAndroidSourceSetData.KEY).firstOrNull()?.data?.sourceSetInfos class KotlinSourceSetInfo @PropertyMapping("kotlinModule") constructor(val kotlinModule: KotlinModule) : Serializable { var moduleId: String? = null var gradleModuleId: String = "" var actualPlatforms: KotlinPlatformContainer = KotlinPlatformContainerImpl() @Deprecated("Returns only single TargetPlatform", ReplaceWith("actualPlatforms.actualPlatforms"), DeprecationLevel.ERROR) val platform: KotlinPlatform get() = actualPlatforms.platforms.singleOrNull() ?: KotlinPlatform.COMMON @Transient var defaultCompilerArguments: CommonCompilerArguments? = null @Transient var compilerArguments: CommonCompilerArguments? = null var dependencyClasspath: List<String> = emptyList() var isTestModule: Boolean = false var sourceSetIdsByName: MutableMap<String, String> = LinkedHashMap() var dependsOn: List<String> = emptyList() var externalSystemRunTasks: Collection<ExternalSystemRunTask> = emptyList() } class KotlinAndroidSourceSetData @PropertyMapping("sourceSetInfos") constructor(val sourceSetInfos: List<KotlinSourceSetInfo> ) : AbstractExternalEntityData(GradleConstants.SYSTEM_ID) { companion object { val KEY = ExternalKey.create(KotlinAndroidSourceSetData::class.java, KotlinTargetData.KEY.processingWeight + 1) } } class KotlinTargetData @PropertyMapping("externalName") constructor(externalName: String) : AbstractNamedData(GradleConstants.SYSTEM_ID, externalName) { var moduleIds: Set<String> = emptySet() var archiveFile: File? = null var konanArtifacts: Collection<KonanArtifactModel>? = null companion object { val KEY = ExternalKey.create(KotlinTargetData::class.java, ProjectKeys.MODULE.processingWeight + 1) } } class KotlinOutputPathsData @PropertyMapping("paths") constructor(val paths: MultiMap<ExternalSystemSourceType, String>) : AbstractExternalEntityData(GradleConstants.SYSTEM_ID) { companion object { val KEY = ExternalKey.create(KotlinOutputPathsData::class.java, ProjectKeys.CONTENT_ROOT.processingWeight + 1) } }
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/configuration/KotlinMPPDataNodes.kt
2120051
package test3 class C
plugins/kotlin/idea/tests/testData/configuration/project106InconsistentVersionInConfig/src/Test3.kt
229258025
package pl.ches.citybikes.presentation.screen.main.stations import android.content.Context import android.os.Bundle import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.LinearLayoutManager import android.view.View import com.hannesdorfmann.mosby.mvp.viewstate.lce.LceViewState import com.hannesdorfmann.mosby.mvp.viewstate.lce.data.RetainingLceViewState import com.jakewharton.rxbinding.support.design.widget.offsetChanges import com.jakewharton.rxbinding.support.v4.widget.refreshes import kotlinx.android.synthetic.main.app_bar_stations.* import kotlinx.android.synthetic.main.fragment_stations.* import pl.ches.citybikes.App import pl.ches.citybikes.R import pl.ches.citybikes.data.disk.entity.Station import pl.ches.citybikes.presentation.common.base.view.BaseLceViewStateFragmentSrl import pl.ches.citybikes.presentation.common.widget.DividerItemDecoration /** * @author Michał Seroczyński <[email protected]> */ class StationsFragment : BaseLceViewStateFragmentSrl<SwipeRefreshLayout, List<Pair<Station, Float>>, StationsView, StationsPresenter>(), StationsView, StationAdapter.Listener { private val component = App.component().plusStations() private lateinit var adapter: StationAdapter private lateinit var stationChooseListener: StationChooseListener //region Setup override val layoutRes by lazy { R.layout.fragment_stations } override fun injectDependencies() = component.inject(this) override fun createPresenter(): StationsPresenter = component.presenter() override fun onAttach(context: Context?) { super.onAttach(context) try { stationChooseListener = context as StationChooseListener } catch (e: ClassCastException) { throw ClassCastException(activity.toString() + " must implement ${StationChooseListener::class.java.simpleName}") } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) appBarLay.offsetChanges().subscribe { contentView.isEnabled = it == 0 } contentView.refreshes().subscribe { loadData(true) } adapter = StationAdapter(activity, this) recyclerView.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false) recyclerView.adapter = adapter recyclerView.isNestedScrollingEnabled = false val dividerItemDecoration = DividerItemDecoration(activity, R.drawable.bg_line_divider, false, false) recyclerView.addItemDecoration(dividerItemDecoration) } override fun loadData(pullToRefresh: Boolean) = presenter.loadData(pullToRefresh) override fun createViewState(): LceViewState<List<Pair<Station, Float>>, StationsView> = RetainingLceViewState() override fun getData(): List<Pair<Station, Float>> = adapter.getItems() override fun setData(data: List<Pair<Station, Float>>) { adapter.swapItems(data) // onStationClicked(data.first().first) } //endregion //region Events override fun onStationClicked(station: Station) = stationChooseListener.stationChosen(station) //endregion companion object { fun newInstance() = StationsFragment() } }
app/src/main/kotlin/pl/ches/citybikes/presentation/screen/main/stations/StationsFragment.kt
1066697012
// 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.cli.common.arguments import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion object CliArgumentStringBuilder { private const val LANGUAGE_FEATURE_FLAG_PREFIX = "-XXLanguage:" private const val LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX = "-X" private val LanguageFeature.dedicatedFlagInfo get() = when (this) { LanguageFeature.InlineClasses -> Pair("inline-classes", KotlinVersion(1, 3, 50)) else -> null } private val LanguageFeature.State.sign: String get() = when (this) { LanguageFeature.State.ENABLED -> "+" LanguageFeature.State.DISABLED -> "-" LanguageFeature.State.ENABLED_WITH_WARNING -> "+" // not supported normally LanguageFeature.State.ENABLED_WITH_ERROR -> "-" // not supported normally } private fun LanguageFeature.getFeatureMentionInCompilerArgsRegex(): Regex { val basePattern = "$LANGUAGE_FEATURE_FLAG_PREFIX(?:-|\\+)$name" val fullPattern = if (dedicatedFlagInfo != null) "(?:$basePattern)|$LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX${dedicatedFlagInfo!!.first}" else basePattern return Regex(fullPattern) } fun LanguageFeature.buildArgumentString(state: LanguageFeature.State, kotlinVersion: IdeKotlinVersion?): String { val shouldBeFeatureEnabled = state == LanguageFeature.State.ENABLED || state == LanguageFeature.State.ENABLED_WITH_WARNING val dedicatedFlag = dedicatedFlagInfo?.run { val (xFlag, xFlagSinceVersion) = this if (kotlinVersion == null || kotlinVersion.kotlinVersion >= xFlagSinceVersion) xFlag else null } return if (shouldBeFeatureEnabled && dedicatedFlag != null) { LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX + dedicatedFlag } else { "$LANGUAGE_FEATURE_FLAG_PREFIX${state.sign}$name" } } fun String.replaceLanguageFeature( feature: LanguageFeature, state: LanguageFeature.State, kotlinVersion: IdeKotlinVersion?, prefix: String = "", postfix: String = "", separator: String = ", ", quoted: Boolean = true ): String { val quote = if (quoted) "\"" else "" val featureArgumentString = feature.buildArgumentString(state, kotlinVersion) val existingFeatureMatchResult = feature.getFeatureMentionInCompilerArgsRegex().find(this) return if (existingFeatureMatchResult != null) { replace(existingFeatureMatchResult.value, featureArgumentString) } else { val splitText = if (postfix.isNotEmpty()) split(postfix) else listOf(this, "") if (splitText.size != 2) { "$prefix$quote$featureArgumentString$quote$postfix" } else { val (mainPart, commentPart) = splitText // In Groovy / Kotlin DSL, we can have comment after [...] or listOf(...) mainPart + "$separator$quote$featureArgumentString$quote$postfix" + commentPart } } } }
plugins/kotlin/jvm/src/org/jetbrains/kotlin/cli/common/arguments/CliArgumentStringBuilder.kt
801217085
// 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.actions import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.util.PlatformUtils import org.jetbrains.kotlin.idea.KotlinJvmBundle import org.jetbrains.kotlin.idea.configuration.* import org.jetbrains.kotlin.idea.util.ProgressIndicatorUtils.underModalProgress import org.jetbrains.kotlin.idea.util.projectStructure.allModules import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.platform.jvm.isJvm abstract class ConfigureKotlinInProjectAction : AnAction() { abstract fun getApplicableConfigurators(project: Project): Collection<KotlinProjectConfigurator> override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val (modules, configurators) = underModalProgress(project, KotlinJvmBundle.message("lookup.project.configurators.progress.text")) { val modules = getConfigurableModules(project) if (modules.all(::isModuleConfigured)) { return@underModalProgress modules to emptyList<KotlinProjectConfigurator>() } val configurators = getApplicableConfigurators(project) modules to configurators } if (modules.all(::isModuleConfigured)) { Messages.showInfoMessage(KotlinJvmBundle.message("all.modules.with.kotlin.files.are.configured"), e.presentation.text!!) return } when { configurators.size == 1 -> configurators.first().configure(project, emptyList()) configurators.isEmpty() -> Messages.showErrorDialog( KotlinJvmBundle.message("there.aren.t.configurators.available"), e.presentation.text!! ) else -> { val configuratorsPopup = KotlinSetupEnvironmentNotificationProvider.createConfiguratorsPopup(project, configurators.toList()) configuratorsPopup.showInBestPositionFor(e.dataContext) } } } } class ConfigureKotlinJsInProjectAction : ConfigureKotlinInProjectAction() { override fun getApplicableConfigurators(project: Project) = getAbleToRunConfigurators(project).filter { it.targetPlatform.isJs() } override fun update(e: AnActionEvent) { val project = e.project if (!PlatformUtils.isIntelliJ() && (project == null || project.allModules().all { it.getBuildSystemType() != BuildSystemType.JPS }) ) { e.presentation.isEnabledAndVisible = false } } } class ConfigureKotlinJavaInProjectAction : ConfigureKotlinInProjectAction() { override fun getApplicableConfigurators(project: Project) = getAbleToRunConfigurators(project).filter { it.targetPlatform.isJvm() } }
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/actions/ConfigureKotlinInProjectAction.kt
3111653290
/* * Copyright 2010-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 codegen.basics.unit1 import kotlin.test.* @Test fun runTest() { println(println("First").toString()) }
backend.native/tests/codegen/basics/unit1.kt
3506942551
// 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. @file:JvmName("PathManagerEx") package com.intellij.openapi.application import com.intellij.openapi.diagnostic.Logger import java.io.IOException import java.nio.file.Path import java.nio.file.Paths /** * Absolute canonical path to system cache dir. */ val appSystemDir: Path get() { val path = Paths.get(PathManager.getSystemPath()) try { return path.toRealPath() } catch (e: IOException) { Logger.getInstance(PathManager::class.java).warn(e) } return path }
platform/util-ex/src/com/intellij/openapi/application/pathManagerEx.kt
1099439517
// 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.caches.resolve import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.util.containers.ConcurrentFactoryMap import org.jetbrains.kotlin.asJava.LightClassBuilder import org.jetbrains.kotlin.asJava.LightClassGenerationSupport import org.jetbrains.kotlin.asJava.builder.InvalidLightClassDataHolder import org.jetbrains.kotlin.asJava.builder.LightClassDataHolder import org.jetbrains.kotlin.asJava.classes.* import org.jetbrains.kotlin.asJava.finder.JavaElementFinder import org.jetbrains.kotlin.codegen.ClassBuilderMode import org.jetbrains.kotlin.codegen.JvmCodegenUtil import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper import org.jetbrains.kotlin.config.JvmTarget import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.caches.lightClasses.IDELightClassContexts import org.jetbrains.kotlin.idea.caches.lightClasses.LazyLightClassDataHolder import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.project.platform import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.stubindex.KotlinTypeAliasShortNameIndex import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.platform.jvm.JdkPlatform import org.jetbrains.kotlin.platform.subplatformsOfType import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import java.util.concurrent.ConcurrentMap class IDELightClassGenerationSupport(project: Project) : LightClassGenerationSupport() { private class KtUltraLightSupportImpl(private val element: KtElement) : KtUltraLightSupport { private val module = ModuleUtilCore.findModuleForPsiElement(element) override val languageVersionSettings: LanguageVersionSettings get() = module?.languageVersionSettings ?: KotlinTypeMapper.LANGUAGE_VERSION_SETTINGS_DEFAULT private val resolutionFacade get() = element.getResolutionFacade() override val moduleDescriptor get() = resolutionFacade.moduleDescriptor override val moduleName: String by lazyPub { JvmCodegenUtil.getModuleName(moduleDescriptor) } override fun possiblyHasAlias(file: KtFile, shortName: Name): Boolean = allAliases(file)[shortName.asString()] == true private fun allAliases(file: KtFile): ConcurrentMap<String, Boolean> = CachedValuesManager.getCachedValue(file) { val importAliases = file.importDirectives.mapNotNull { it.aliasName }.toSet() val map = ConcurrentFactoryMap.createMap<String, Boolean> { s -> s in importAliases || KotlinTypeAliasShortNameIndex.get(s, file.project, file.resolveScope).isNotEmpty() } CachedValueProvider.Result.create<ConcurrentMap<String, Boolean>>(map, PsiModificationTracker.MODIFICATION_COUNT) } @OptIn(FrontendInternals::class) override val deprecationResolver: DeprecationResolver get() = resolutionFacade.getFrontendService(DeprecationResolver::class.java) override val typeMapper: KotlinTypeMapper by lazyPub { KotlinTypeMapper( BindingContext.EMPTY, ClassBuilderMode.LIGHT_CLASSES, moduleName, languageVersionSettings, useOldInlineClassesManglingScheme = false, jvmTarget = module?.platform?.subplatformsOfType<JdkPlatform>()?.firstOrNull()?.targetVersion ?: JvmTarget.DEFAULT, typePreprocessor = KotlinType::cleanFromAnonymousTypes, namePreprocessor = ::tryGetPredefinedName ) } } override fun getUltraLightClassSupport(element: KtElement): KtUltraLightSupport = KtUltraLightSupportImpl(element) override val useUltraLightClasses: Boolean get() = !KtUltraLightSupport.forceUsingOldLightClasses && Registry.`is`("kotlin.use.ultra.light.classes", true) private val scopeFileComparator = JavaElementFinder.byClasspathComparator(GlobalSearchScope.allScope(project)) override fun createDataHolderForClass(classOrObject: KtClassOrObject, builder: LightClassBuilder): LightClassDataHolder.ForClass { return when { classOrObject.shouldNotBeVisibleAsLightClass() -> InvalidLightClassDataHolder classOrObject.isLocal -> LazyLightClassDataHolder.ForClass( builder, exactContextProvider = { IDELightClassContexts.contextForLocalClassOrObject(classOrObject) }, dummyContextProvider = null, diagnosticsHolderProvider = { classOrObject.getDiagnosticsHolder() } ) else -> LazyLightClassDataHolder.ForClass( builder, exactContextProvider = { IDELightClassContexts.contextForNonLocalClassOrObject(classOrObject) }, dummyContextProvider = { IDELightClassContexts.lightContextForClassOrObject(classOrObject) }, diagnosticsHolderProvider = { classOrObject.getDiagnosticsHolder() } ) } } override fun createDataHolderForFacade(files: Collection<KtFile>, builder: LightClassBuilder): LightClassDataHolder.ForFacade { assert(!files.isEmpty()) { "No files in facade" } val sortedFiles = files.sortedWith(scopeFileComparator) return LazyLightClassDataHolder.ForFacade( builder, exactContextProvider = { IDELightClassContexts.contextForFacade(sortedFiles) }, dummyContextProvider = { IDELightClassContexts.lightContextForFacade(sortedFiles) }, diagnosticsHolderProvider = { files.first().getDiagnosticsHolder() } ) } override fun createDataHolderForScript(script: KtScript, builder: LightClassBuilder): LightClassDataHolder.ForScript { return LazyLightClassDataHolder.ForScript( builder, exactContextProvider = { IDELightClassContexts.contextForScript(script) }, dummyContextProvider = { null }, diagnosticsHolderProvider = { script.getDiagnosticsHolder() } ) } @OptIn(FrontendInternals::class) private fun KtElement.getDiagnosticsHolder() = getResolutionFacade().frontendService<LazyLightClassDataHolder.DiagnosticsHolder>() override fun resolveToDescriptor(declaration: KtDeclaration): DeclarationDescriptor? = declaration.resolveToDescriptorIfAny(BodyResolveMode.FULL) override fun analyze(element: KtElement) = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) override fun analyzeAnnotation(element: KtAnnotationEntry): AnnotationDescriptor? = element.resolveToDescriptorIfAny() override fun analyzeWithContent(element: KtClassOrObject) = element.safeAnalyzeWithContentNonSourceRootCode() }
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/IDELightClassGenerationSupport.kt
3793453166
// 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.uast.kotlin.psi import com.intellij.lang.Language import com.intellij.openapi.components.ServiceManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiParameter import com.intellij.psi.PsiType import com.intellij.psi.impl.light.LightParameter import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.uast.UDeclaration import org.jetbrains.uast.UElement import org.jetbrains.uast.UastErrorType import org.jetbrains.uast.getParentOfType import org.jetbrains.uast.kotlin.BaseKotlinUastResolveProviderService @ApiStatus.Internal class UastKotlinPsiParameter( name: String, type: PsiType, parent: PsiElement, language: Language, isVarArgs: Boolean, ktDefaultValue: KtExpression?, ktParameter: KtParameter ) : UastKotlinPsiParameterBase<KtParameter>(name, type, parent, ktParameter, language, isVarArgs, ktDefaultValue) { companion object { fun create( parameter: KtParameter, parent: PsiElement, containingElement: UElement, index: Int ): PsiParameter { val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java) val psiParent = containingElement.getParentOfType<UDeclaration>()?.javaPsi ?: parent return UastKotlinPsiParameter( parameter.name ?: "p$index", service.getType(parameter, containingElement) ?: UastErrorType, psiParent, KotlinLanguage.INSTANCE, parameter.isVarArg, parameter.defaultValue, parameter ) } } val ktParameter: KtParameter get() = ktOrigin } @ApiStatus.Internal open class UastKotlinPsiParameterBase<T : KtElement>( name: String, type: PsiType, private val parent: PsiElement, val ktOrigin: T, language: Language = ktOrigin.language, isVarArgs: Boolean = false, val ktDefaultValue: KtExpression? = null, ) : LightParameter(name, type, parent, language, isVarArgs) { override fun getParent(): PsiElement = parent override fun getContainingFile(): PsiFile? = ktOrigin.containingFile override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other::class.java != this::class.java) return false return ktOrigin == (other as? UastKotlinPsiParameterBase<*>)?.ktOrigin } override fun hashCode(): Int = ktOrigin.hashCode() }
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/psi/UastKotlinPsiParameter.kt
722497107
fun kotlinUsageSynthetic() { Kotlin().smth = "" }
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/members/javaMethodSyntheticSet/KotlinUsageSynthetic.kt
3100129454
// 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.toolWindow import com.intellij.openapi.application.EDT import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ex.ToolWindowManagerListener.ToolWindowManagerEventType import com.intellij.openapi.wm.impl.IdeFrameImpl import com.intellij.openapi.wm.impl.ProjectFrameHelper import com.intellij.openapi.wm.impl.ToolWindowManagerImpl import com.intellij.testFramework.LightPlatformTestCase import com.intellij.testFramework.SkipInHeadlessEnvironment import com.intellij.testFramework.replaceService import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext @SkipInHeadlessEnvironment abstract class ToolWindowManagerTestCase : LightPlatformTestCase() { @JvmField protected var manager: ToolWindowManagerImpl? = null final override fun runInDispatchThread() = false public override fun setUp() { super.setUp() runBlocking { val project = project manager = object : ToolWindowManagerImpl(project) { override fun fireStateChanged(changeType: ToolWindowManagerEventType) {} } project.replaceService(ToolWindowManager::class.java, manager!!, testRootDisposable) val frame = withContext(Dispatchers.EDT) { val frame = ProjectFrameHelper(IdeFrameImpl()) frame.init() frame } val reopeningEditorsJob = Job().also { it.complete() } manager!!.doInit(frame, project.messageBus.connect(testRootDisposable), reopeningEditorsJob, taskListDeferred = null) } } public override fun tearDown() { try { manager?.let { Disposer.dispose(it) } manager = null } catch (e: Throwable) { addSuppressedException(e) } finally { super.tearDown() } } }
platform/lang-impl/testSources/com/intellij/toolWindow/ToolWindowManagerTestCase.kt
3763502420
/* * 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.health.connect.client.records import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import java.time.Instant import kotlin.test.assertFailsWith import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class FloorsClimbedRecordTest { @Test fun validRecord_equals() { assertThat( FloorsClimbedRecord( startTime = Instant.ofEpochMilli(1234L), startZoneOffset = null, endTime = Instant.ofEpochMilli(1236L), endZoneOffset = null, floors = 10.0, ) ) .isEqualTo( FloorsClimbedRecord( startTime = Instant.ofEpochMilli(1234L), startZoneOffset = null, endTime = Instant.ofEpochMilli(1236L), endZoneOffset = null, floors = 10.0, ) ) } @Test fun invalidTimes_throws() { assertFailsWith<IllegalArgumentException> { FloorsClimbedRecord( startTime = Instant.ofEpochMilli(1234L), startZoneOffset = null, endTime = Instant.ofEpochMilli(1234L), endZoneOffset = null, floors = 10.0, ) } } }
health/connect/connect-client/src/test/java/androidx/health/connect/client/records/FloorsClimbedRecordTest.kt
678049009
/* * Copyright (C) 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.room.compiler.processing.javac import androidx.room.compiler.processing.XElement import androidx.room.compiler.processing.XMessager import androidx.room.compiler.processing.XNullability import androidx.room.compiler.processing.XProcessingEnv import androidx.room.compiler.processing.XProcessingEnvConfig import androidx.room.compiler.processing.XType import androidx.room.compiler.processing.XTypeElement import androidx.room.compiler.processing.javac.kotlin.KmType import com.google.auto.common.GeneratedAnnotations import com.google.auto.common.MoreTypes import java.util.Locale import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.ExecutableElement import javax.lang.model.element.PackageElement import javax.lang.model.element.TypeElement import javax.lang.model.element.VariableElement import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror import javax.lang.model.util.Elements import javax.lang.model.util.Types internal class JavacProcessingEnv( val delegate: ProcessingEnvironment, override val config: XProcessingEnvConfig, ) : XProcessingEnv { override val backend: XProcessingEnv.Backend = XProcessingEnv.Backend.JAVAC val elementUtils: Elements = delegate.elementUtils val typeUtils: Types = delegate.typeUtils private val typeElementStore = XTypeElementStore( findElement = { qName -> delegate.elementUtils.getTypeElement(qName) }, wrap = { typeElement -> JavacTypeElement.create(this, typeElement) }, getQName = { it.qualifiedName.toString() } ) override val messager: XMessager by lazy { JavacProcessingEnvMessager(delegate.messager) } override val filer = JavacFiler(this, delegate.filer) override val options: Map<String, String> get() = delegate.options // SourceVersion enum constants are named 'RELEASE_x' and since they are public APIs, its safe // to assume they won't change and we can extract the version from them. override val jvmVersion = delegate.sourceVersion.name.substringAfter("RELEASE_").toIntOrNull() ?: error("Invalid source version: ${delegate.sourceVersion}") override fun findTypeElement(qName: String): JavacTypeElement? { return typeElementStore[qName] } override fun getTypeElementsFromPackage(packageName: String): List<XTypeElement> { // Note, to support Java Modules we would need to use "getAllPackageElements", // but that is only available in Java 9+. val packageElement = delegate.elementUtils.getPackageElement(packageName) ?: return emptyList() return packageElement.enclosedElements .filterIsInstance<TypeElement>() .map { wrapTypeElement(it) } } override fun findType(qName: String): XType? { // check for primitives first PRIMITIVE_TYPES[qName]?.let { return wrap( typeMirror = typeUtils.getPrimitiveType(it), kotlinType = null, elementNullability = XNullability.NONNULL ) } // check no types, such as 'void' NO_TYPES[qName]?.let { return wrap( typeMirror = typeUtils.getNoType(it), kotlinType = null, elementNullability = XNullability.NONNULL ) } return findTypeElement(qName)?.type } override fun findGeneratedAnnotation(): XTypeElement? { val element = GeneratedAnnotations.generatedAnnotation(elementUtils, delegate.sourceVersion) return if (element.isPresent) { wrapTypeElement(element.get()) } else { null } } override fun getArrayType(type: XType): JavacArrayType { check(type is JavacType) { "given type must be from java, $type is not" } return JavacArrayType( env = this, typeMirror = typeUtils.getArrayType(type.typeMirror), nullability = XNullability.UNKNOWN, knownComponentNullability = type.nullability ) } override fun getDeclaredType(type: XTypeElement, vararg types: XType): JavacType { check(type is JavacTypeElement) val args = types.map { check(it is JavacType) it.typeMirror }.toTypedArray() return wrap<JavacDeclaredType>( typeMirror = typeUtils.getDeclaredType(type.element, *args), // type elements cannot have nullability hence we don't synthesize anything here kotlinType = null, elementNullability = type.element.nullability ) } override fun getWildcardType(consumerSuper: XType?, producerExtends: XType?): XType { check(consumerSuper == null || producerExtends == null) { "Cannot supply both super and extends bounds." } return wrap( typeMirror = typeUtils.getWildcardType( (producerExtends as? JavacType)?.typeMirror, (consumerSuper as? JavacType)?.typeMirror, ), kotlinType = null, elementNullability = null ) } fun wrapTypeElement(element: TypeElement) = typeElementStore[element] /** * Wraps the given java processing type into an XType. * * @param typeMirror TypeMirror from java processor * @param kotlinType If the type is derived from a kotlin source code, the KmType information * parsed from kotlin metadata * @param elementNullability The nullability information parsed from the code. This value is * ignored if [kotlinType] is provided. */ inline fun <reified T : JavacType> wrap( typeMirror: TypeMirror, kotlinType: KmType?, elementNullability: XNullability? ): T { return when (typeMirror.kind) { TypeKind.ARRAY -> when { kotlinType != null -> { JavacArrayType( env = this, typeMirror = MoreTypes.asArray(typeMirror), kotlinType = kotlinType ) } elementNullability != null -> { JavacArrayType( env = this, typeMirror = MoreTypes.asArray(typeMirror), nullability = elementNullability, knownComponentNullability = null ) } else -> { JavacArrayType( env = this, typeMirror = MoreTypes.asArray(typeMirror), ) } } TypeKind.DECLARED -> when { kotlinType != null -> { JavacDeclaredType( env = this, typeMirror = MoreTypes.asDeclared(typeMirror), kotlinType = kotlinType ) } elementNullability != null -> { JavacDeclaredType( env = this, typeMirror = MoreTypes.asDeclared(typeMirror), nullability = elementNullability ) } else -> { JavacDeclaredType( env = this, typeMirror = MoreTypes.asDeclared(typeMirror) ) } } else -> when { kotlinType != null -> { DefaultJavacType( env = this, typeMirror = typeMirror, kotlinType = kotlinType ) } elementNullability != null -> { DefaultJavacType( env = this, typeMirror = typeMirror, nullability = elementNullability ) } else -> { DefaultJavacType( env = this, typeMirror = typeMirror ) } } } as T } internal fun wrapAnnotatedElement( element: Element, annotationName: String ): XElement { return when (element) { is VariableElement -> { wrapVariableElement(element) } is TypeElement -> { wrapTypeElement(element) } is ExecutableElement -> { wrapExecutableElement(element) } is PackageElement -> { error( "Cannot get elements with annotation $annotationName. Package " + "elements are not supported by XProcessing." ) } else -> error("Unsupported element $element with annotation $annotationName") } } fun wrapExecutableElement(element: ExecutableElement): JavacExecutableElement { return when (element.kind) { ElementKind.CONSTRUCTOR -> { JavacConstructorElement( env = this, element = element ) } ElementKind.METHOD -> { JavacMethodElement( env = this, element = element ) } else -> error("Unsupported kind ${element.kind} of executable element $element") } } fun wrapVariableElement(element: VariableElement): JavacVariableElement { return when (val enclosingElement = element.enclosingElement) { is ExecutableElement -> { val executableElement = wrapExecutableElement(enclosingElement) executableElement.parameters.find { param -> param.element.simpleName == element.simpleName } ?: error("Unable to create variable element for $element") } is TypeElement -> JavacFieldElement(this, element) else -> error("Unsupported enclosing type $enclosingElement for $element") } } internal fun clearCache() { typeElementStore.clear() } companion object { val PRIMITIVE_TYPES = TypeKind.values().filter { it.isPrimitive }.associateBy { it.name.lowercase(Locale.US) } val NO_TYPES = listOf( TypeKind.VOID, TypeKind.NONE ).associateBy { it.name.lowercase(Locale.US) } } }
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/javac/JavacProcessingEnv.kt
459286401
/* * 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. */ // NOTE(b/190438045): // This file is intentionally left empty to temporarily work around a bug in AGP 7.1.0-alpha02
hilt/integration-tests/workerapp/src/test/kotlin/EmptyFile.kt
3241609917
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageOperationType import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion import kotlinx.coroutines.Deferred internal data class PackageOperations( val targetModules: TargetModules, val primaryOperations: Deferred<List<PackageSearchOperation<*>>>, val removeOperations: Deferred<List<PackageSearchOperation<*>>>, val targetVersion: NormalizedPackageVersion<*>?, val primaryOperationType: PackageOperationType?, val repoToAddWhenInstalling: RepositoryModel? ) { val canInstallPackage = primaryOperationType == PackageOperationType.INSTALL val canUpgradePackage = primaryOperationType == PackageOperationType.UPGRADE val canSetPackage = primaryOperationType == PackageOperationType.SET }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/PackageOperations.kt
1585362740
internal class C() { constructor(p: Int) : this() { println(staticField1 + staticField2) } companion object { private const val staticField1 = 0 private const val staticField2 = 0 } }
plugins/kotlin/j2k/new/tests/testData/newJ2k/constructors/staticFieldRefInFactoryFun.kt
2049579772
import com.intellij.ui.JBColor import java.awt.Color import java.awt.Color.GREEN class UseJBColorConstant { companion object { private val COLOR_CONSTANT = <warning descr="'java.awt.Color' used instead of 'JBColor'">Color.BLUE</warning> private val COLOR_CONSTANT_STATIC_IMPORT = <warning descr="'java.awt.Color' used instead of 'JBColor'">GREEN</warning> private val JB_COLOR_CONSTANT: Color = JBColor(Color.DARK_GRAY, Color.LIGHT_GRAY) // correct usage private val JB_COLOR_CONSTANT_STATIC_IMPORT: Color = JBColor(GREEN, GREEN) // correct usage } fun any() { @Suppress("UNUSED_VARIABLE") val myColor = <warning descr="'java.awt.Color' used instead of 'JBColor'">Color.BLUE</warning> takeColor(<warning descr="'java.awt.Color' used instead of 'JBColor'">Color.green</warning>) takeColor(<warning descr="'java.awt.Color' used instead of 'JBColor'">GREEN</warning>) // correct cases: @Suppress("UNUSED_VARIABLE") val myGreen: Color = JBColor(Color.white, Color.YELLOW) takeColor(JBColor(Color.BLACK, Color.WHITE)) } fun takeColor(@Suppress("UNUSED_PARAMETER") color: Color) { // do nothing } }
plugins/devkit/devkit-kotlin-tests/testData/inspections/useJBColor/UseJBColorConstant.kt
55642193
import java.math.BigInteger fun main() { for (n in testCases) { val result = getA004290(n) println("A004290($n) = $result = $n * ${result / n.toBigInteger()}") } } private val testCases: List<Int> get() { val testCases: MutableList<Int> = ArrayList() for (i in 1..10) { testCases.add(i) } for (i in 95..105) { testCases.add(i) } for (i in intArrayOf(297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878)) { testCases.add(i) } return testCases } private fun getA004290(n: Int): BigInteger { if (n == 1) { return BigInteger.ONE } val arr = Array(n) { IntArray(n) } for (i in 2 until n) { arr[0][i] = 0 } arr[0][0] = 1 arr[0][1] = 1 var m = 0 val ten = BigInteger.TEN val nBi = n.toBigInteger() while (true) { m++ if (arr[m - 1][mod(-ten.pow(m), nBi).toInt()] == 1) { break } arr[m][0] = 1 for (k in 1 until n) { arr[m][k] = arr[m - 1][k].coerceAtLeast(arr[m - 1][mod(k.toBigInteger() - ten.pow(m), nBi).toInt()]) } } var r = ten.pow(m) var k = mod(-r, nBi) for (j in m - 1 downTo 1) { if (arr[j - 1][k.toInt()] == 0) { r += ten.pow(j) k = mod(k - ten.pow(j), nBi) } } if (k.compareTo(BigInteger.ONE) == 0) { r += BigInteger.ONE } return r } private fun mod(m: BigInteger, n: BigInteger): BigInteger { var result = m.mod(n) if (result < BigInteger.ZERO) { result += n } return result }
Minimum_positive_multiple_in_base_10_using_only_0_and_1/Kotlin/src/main/kotlin/MinimumNumberOnlyZeroAndOne.kt
3302829496
package com.reactnativenavigation.viewcontrollers.fakes import android.app.Activity import androidx.coordinatorlayout.widget.CoordinatorLayout import com.reactnativenavigation.options.Options import com.reactnativenavigation.viewcontrollers.viewcontroller.Presenter import com.reactnativenavigation.utils.CompatUtils import com.reactnativenavigation.viewcontrollers.child.ChildControllersRegistry import com.reactnativenavigation.viewcontrollers.parent.ParentController import com.reactnativenavigation.viewcontrollers.viewcontroller.ViewController import org.mockito.Mockito.mock class FakeParentController @JvmOverloads constructor( activity: Activity, childRegistry: ChildControllersRegistry, private val child: ViewController<*>, id: String = "Parent" + CompatUtils.generateViewId(), presenter: Presenter = mock(Presenter::class.java), initialOptions: Options = Options.EMPTY ) : ParentController<CoordinatorLayout>(activity, childRegistry, id, presenter, initialOptions) { init { child.parentController = this } override fun getCurrentChild(): ViewController<*> = child override fun createView() = CoordinatorLayout(activity).apply { addView(child.view) } override fun getChildControllers() = listOf(child) override fun sendOnNavigationButtonPressed(buttonId: String?) = child.sendOnNavigationButtonPressed(buttonId) }
lib/android/app/src/test/java/com/reactnativenavigation/viewcontrollers/fakes/FakeParentController.kt
1498383941
// 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.intellij.plugins.markdown.ui.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.popup.JBPopupFactory import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile internal class InsertAction: DumbAwareAction() { override fun actionPerformed(event: AnActionEvent) { val dataContext = event.dataContext val popup = JBPopupFactory.getInstance().createActionGroupPopup( MarkdownBundle.message("action.Markdown.Insert.text"), insertGroup, dataContext, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false, MarkdownActionPlaces.INSERT_POPUP ) popup.showInBestPositionFor(dataContext) } override fun update(event: AnActionEvent) { val editor = MarkdownActionUtil.findMarkdownTextEditor(event) event.presentation.isEnabledAndVisible = editor != null || event.getData(PlatformDataKeys.PSI_FILE) is MarkdownFile } companion object { private val insertGroup get() = requireNotNull(ActionUtil.getActionGroup("Markdown.InsertGroup")) } }
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/actions/InsertAction.kt
2696959886
package us.nineworlds.serenity.jobs.videos import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.verify import org.apache.commons.lang3.RandomStringUtils import org.greenrobot.eventbus.EventBus import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnit import org.mockito.quality.Strictness.STRICT_STUBS import us.nineworlds.serenity.TestingModule import us.nineworlds.serenity.common.rest.SerenityClient import us.nineworlds.serenity.common.rest.SerenityUser import us.nineworlds.serenity.events.users.AuthenticatedUserEvent import us.nineworlds.serenity.jobs.AuthenticateUserJob import us.nineworlds.serenity.test.InjectingTest import us.nineworlds.serenity.testrunner.PlainAndroidRunner import javax.inject.Inject @RunWith(PlainAndroidRunner::class) class AuthenticateUserJobTest : InjectingTest() { @Rule @JvmField public val rule = MockitoJUnit.rule().strictness(STRICT_STUBS) @Mock lateinit var mockUser: SerenityUser @Inject lateinit var mockClient: SerenityClient @Mock lateinit var mockEventBus: EventBus lateinit var job: AuthenticateUserJob val expectedVideoId = RandomStringUtils.randomAlphanumeric(5) @Before override fun setUp() { super.setUp() job = AuthenticateUserJob(mockUser) job.eventBus = mockEventBus } @Test fun onRunAuthenticatesUser() { job.onRun() verify(mockClient).authenticateUser(mockUser) } @Test fun onRunPostsAuthenticationEvent() { job.onRun() verify(mockEventBus).post(any<AuthenticatedUserEvent>()) } override fun installTestModules() { scope.installTestModules(TestingModule()) } }
serenity-app/src/test/kotlin/us/nineworlds/serenity/jobs/videos/AuthenticateUserJobTest.kt
459853990
package com.github.kerubistan.kerub.planner.steps.network.ovs.sw.create import com.github.kerubistan.kerub.hostUp import com.github.kerubistan.kerub.model.config.OvsNetworkConfiguration import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.reservations.UseHostReservation import com.github.kerubistan.kerub.planner.steps.OperationalStepVerifications import com.github.kerubistan.kerub.planner.steps.network.ovs.sw.remove.RemoveOvsSwitch import com.github.kerubistan.kerub.testHost import com.github.kerubistan.kerub.testOtherHost import com.github.kerubistan.kerub.testVirtualNetwork import com.nhaarman.mockito_kotlin.mock import org.junit.jupiter.api.Test import java.util.UUID.randomUUID import kotlin.test.assertFalse import kotlin.test.assertTrue internal class CreateOvsSwitchTest : OperationalStepVerifications() { override val step = CreateOvsSwitch(host = testHost, network = testVirtualNetwork) @Test fun isInverseOf() { assertTrue("the inverse") { step.isInverseOf(RemoveOvsSwitch(host = testHost, virtualNetwork = testVirtualNetwork)) } assertFalse("some random step") { step.isInverseOf(mock()) } assertFalse("host not the same, not inverse") { step.isInverseOf(RemoveOvsSwitch(host = testOtherHost, virtualNetwork = testVirtualNetwork)) } assertFalse("host not the same, not inverse") { step.isInverseOf( RemoveOvsSwitch(host = testHost, virtualNetwork = testVirtualNetwork.copy(id = randomUUID())) ) } } @Test fun take() { val state = CreateOvsSwitch(host = testHost, network = testVirtualNetwork).take( OperationalState.fromLists( hosts = listOf(testHost), hostDyns = listOf(hostUp(testHost)), virtualNetworks = listOf(testVirtualNetwork) ) ) assertTrue { state.hosts.getValue(testHost.id).config!!.networkConfiguration.contains( OvsNetworkConfiguration(virtualNetworkId = testVirtualNetwork.id) ) } } @Test fun otherReservations() { assertTrue { step.reservations().contains(UseHostReservation(host = testHost)) } } }
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/network/ovs/sw/create/CreateOvsSwitchTest.kt
2202824341
// 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.intellij.build /** * The purpose of using Mac host is preparation and signing OS X specific artifacts.<br> * The necessary software for Mac host: * <ul> * <li>OS X 10.9</li> * <li>FTP server (it is part of OS X installation).</li> * <li>Perl 5.16 (it is part of OS X installation).</li> * <li>DSStore perl module</li> * <li>Private key and digital certificate for signing apps.</li> *</ul> * <br> *How to setup Mac host:<br> *<ol> * <li>Install OS X 10.9.</li> * <li>Import private key and signing certificate <a href=https://developer.apple.com/library/mac/documentation/Security/Conceptual/CodeSigningGuide/Procedures/Procedures.html">(CodeSigningGuide)</a></li> * <li>Enable FTP Server. Run the command in terminal:<br> * sudo -s launchctl load -w /System/Library/LaunchDaemons/ftp.plist</li> * <li>Create user which will be used for ftp connection</li> * <li>Install DSStore perl module. Run the command in terminal:<br> * sudo cpan Mac::Finder::DSStore<br> * During the cpan and the module installation process will be need to allow install the command line pkg which is part of cpan installation and required for successful result.</li> * <li>Set environment variable VERSIONER_PERL_PREFER_32_BIT to "true". <a href=http://apple.stackexchange.com/questions/83109/macosx-10-8-and-32-bit-perl-modules">More information about it.</a></li> * </ol> */ data class MacHostProperties( /** * Mac host host name. */ val host: String?, /** * userName for access to Mac host via SFTP */ val userName: String?, /** * password for access to Mac host via SFTP */ val password: String?, /** * Full name of a keychain identity (Applications > Utilities > Keychain Access). * More info in SIGNING IDENTITIES (https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/codesign.1.html) */ val codesignString: String?, val architecture: JvmArchitecture = JvmArchitecture.x64 )
platform/build-scripts/src/org/jetbrains/intellij/build/MacHostProperties.kt
1858755939
// IS_APPLICABLE: false class A { init { val x: Int = 1<caret> } }
plugins/kotlin/idea/tests/testData/intentions/convertPropertyInitializerToGetter/inapplicableIfLocalVariableInInitBlock.kt
663724996
fun kotlinRead() { println(Main.field) }
plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/fromCompanion/javaStaticField/KotlinRead.kt
3776118607
// 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.processors import com.intellij.psi.PsiElement import com.intellij.psi.ResolveState import com.intellij.psi.scope.ProcessorWithHints open class CollectElementsProcessor : ProcessorWithHints() { private val myResults = mutableListOf<PsiElement>() val results: List<PsiElement> get() = myResults final override fun execute(element: PsiElement, state: ResolveState): Boolean { myResults += element return true } }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/CollectElementsProcessor.kt
2817166540
// FIX: Convert to run { ... } // WITH_STDLIB fun test() = <caret>{ error("") }
plugins/kotlin/idea/tests/testData/inspectionsLocal/functionWithLambdaExpressionBody/wrapRun/functionReturnsNothing.kt
2313513978
// "class org.jetbrains.kotlin.idea.quickfix.InitializePropertyQuickFixFactory$AddInitializerFix" "false" // ACTION: Make internal // ACTION: Make private // ACTION: Make protected // ERROR: Property must be initialized class A { <caret>var Int.n: Int set(value: Int) {} }
plugins/kotlin/idea/tests/testData/quickfix/addInitializer/memberExtensionPropertyVarSetterOnly.kt
557694931
// 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.gradleJava.cocoapods import org.jetbrains.kotlin.idea.gradleTooling.EnablePodImportTask import org.jetbrains.plugins.gradle.model.ClassSetProjectImportModelProvider import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension class KotlinCocoaPodsModelResolver : AbstractProjectResolverExtension() { override fun getToolingExtensionsClasses(): Set<Class<out Any>> { return setOf(EnablePodImportTask::class.java) } override fun getProjectsLoadedModelProvider(): ProjectImportModelProvider { return ClassSetProjectImportModelProvider( setOf(EnablePodImportTask::class.java) ) } }
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/cocoapods/KotlinCocoaPodsModelResolver.kt
905719033