content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package org.wikipedia.analytics import org.wikipedia.Constants.InvokeSource import org.wikipedia.WikipediaApp class AppLanguageSettingsFunnel : TimedFunnel(WikipediaApp.getInstance(), SCHEMA_NAME, REV_ID, SAMPLE_LOG_ALL) { fun logLanguageSetting(source: InvokeSource, initialLanguageList: String, finalLanguageList: String, interactionsCount: Int, searched: Boolean) { log( "source", source.getName(), "initial", initialLanguageList, "final", finalLanguageList, "interactions", interactionsCount, "searched", searched ) } companion object { private const val SCHEMA_NAME = "MobileWikiAppLanguageSettings" private const val REV_ID = 18113720 } }
app/src/main/java/org/wikipedia/analytics/AppLanguageSettingsFunnel.kt
1110615780
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.ui.util import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.net.Uri import android.provider.MediaStore import androidx.core.content.ContextCompat import com.google.android.gms.maps.model.BitmapDescriptor import com.google.android.gms.maps.model.BitmapDescriptorFactory import dagger.hilt.android.qualifiers.ApplicationContext import java.io.IOException import javax.inject.Inject class BitmapUtil @Inject internal constructor(@param:ApplicationContext private val context: Context) { /** Retrieves an image for the given url as a [Bitmap]. */ @Throws(IOException::class) fun fromUri(url: Uri?): Bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, url) fun bitmapDescriptorFromVector(resId: Int): BitmapDescriptor { val vectorDrawable = ContextCompat.getDrawable(context, resId)!! // Specify a bounding rectangle for the Drawable. vectorDrawable.setBounds(0, 0, vectorDrawable.intrinsicWidth, vectorDrawable.intrinsicHeight) val bitmap = Bitmap.createBitmap( vectorDrawable.intrinsicWidth, vectorDrawable.intrinsicHeight, Bitmap.Config.ARGB_8888 ) val canvas = Canvas(bitmap) vectorDrawable.draw(canvas) return BitmapDescriptorFactory.fromBitmap(bitmap) } }
ground/src/main/java/com/google/android/ground/ui/util/BitmapUtil.kt
3629827052
/* * Copyright (c) 2015 PocketHub * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pockethub.android.ui.base import android.os.Bundle import android.os.Parcelable import android.view.View import butterknife.ButterKnife import dagger.android.support.DaggerFragment abstract class BaseFragment : DaggerFragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) ButterKnife.bind(this, view) } /** * Get parcelable extra from activity's intent */ protected fun <V : Parcelable> getParcelableExtra(name: String): V? { return activity?.intent?.getParcelableExtra(name) } /** * Get string extra from activity's intent */ protected fun getStringExtra(name: String): String? { return activity?.intent?.getStringExtra(name) } }
app/src/main/java/com/github/pockethub/android/ui/base/BaseFragment.kt
1093462857
/******************************************************************************* * 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.extensibility data class RepositoryDeclaration( val id: String?, val name: String?, val url: String?, val projectModule: ProjectModule )
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/RepositoryDeclaration.kt
2149706595
package one.two import org.jetbrains.annotations.NotNull class MyClass open class A { open fun returnString(): @NotNull MyClass = MyClass() } class B : A() { override fun returnString() = null as MyClas<caret> } // EXIST: {"lookupString":"MyClass","tailText":" (one.two)","module":"light_idea_test_case","attributes":"","allLookupStrings":"MyClass","itemText":"MyClass"} // NUMBER: 1
plugins/kotlin/completion/tests/testData/basic/java/NullableAnnotation.kt
538801622
class K: J { constructor(a: Int): super(a) { } } fun test() { J(1) }
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/JavaConstructorInDelegationCallBefore.1.kt
1191018820
package j1 fun j() { Use.acceptA(Use.returnA()) }
plugins/kotlin/idea/tests/testData/multiModuleHighlighting/multiplatform/jvmKotlinReferencesCommonKotlinThroughJava/a_jvm_dep(fulljdk)/j1/jvm.kt
4038464101
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data.provider import com.intellij.collaboration.async.CompletableFutureUtil.completionOnEdt import com.intellij.openapi.Disposable import com.intellij.openapi.progress.ProgressIndicator import com.intellij.util.messages.MessageBus import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier import org.jetbrains.plugins.github.pullrequest.data.GHPRMergeabilityState import org.jetbrains.plugins.github.pullrequest.data.service.GHPRStateService import org.jetbrains.plugins.github.util.LazyCancellableBackgroundProcessValue import java.util.concurrent.CompletableFuture class GHPRStateDataProviderImpl(private val stateService: GHPRStateService, private val pullRequestId: GHPRIdentifier, private val messageBus: MessageBus, private val detailsData: GHPRDetailsDataProvider) : GHPRStateDataProvider, Disposable { private var lastKnownBaseBranch: String? = null private var lastKnownBaseSha: String? = null private var lastKnownHeadSha: String? = null init { detailsData.addDetailsLoadedListener(this) { val details = detailsData.loadedDetails ?: return@addDetailsLoadedListener if (lastKnownBaseBranch != null && lastKnownBaseBranch != details.baseRefName) { baseBranchProtectionRulesRequestValue.drop() reloadMergeabilityState() } lastKnownBaseBranch = details.baseRefName if (lastKnownBaseSha != null && lastKnownBaseSha != details.baseRefOid && lastKnownHeadSha != null && lastKnownHeadSha != details.headRefOid) { reloadMergeabilityState() } lastKnownBaseSha = details.baseRefOid lastKnownHeadSha = details.headRefOid } } private val baseBranchProtectionRulesRequestValue = LazyCancellableBackgroundProcessValue.create { indicator -> detailsData.loadDetails().thenCompose { stateService.loadBranchProtectionRules(indicator, pullRequestId, it.baseRefName) } } private val mergeabilityStateRequestValue = LazyCancellableBackgroundProcessValue.create { indicator -> val baseBranchProtectionRulesRequest = baseBranchProtectionRulesRequestValue.value detailsData.loadDetails().thenCompose { details -> baseBranchProtectionRulesRequest.thenCompose { stateService.loadMergeabilityState(indicator, pullRequestId, details.headRefOid, details.url, it) } } } override fun loadMergeabilityState(): CompletableFuture<GHPRMergeabilityState> = mergeabilityStateRequestValue.value override fun reloadMergeabilityState() { if (baseBranchProtectionRulesRequestValue.lastLoadedValue == null) baseBranchProtectionRulesRequestValue.drop() mergeabilityStateRequestValue.drop() } override fun addMergeabilityStateListener(disposable: Disposable, listener: () -> Unit) = mergeabilityStateRequestValue.addDropEventListener(disposable, listener) override fun close(progressIndicator: ProgressIndicator): CompletableFuture<Unit> = stateService.close(progressIndicator, pullRequestId).notifyState() override fun reopen(progressIndicator: ProgressIndicator): CompletableFuture<Unit> = stateService.reopen(progressIndicator, pullRequestId).notifyState() override fun markReadyForReview(progressIndicator: ProgressIndicator): CompletableFuture<Unit> = stateService.markReadyForReview(progressIndicator, pullRequestId).notifyState().completionOnEdt { mergeabilityStateRequestValue.drop() } override fun merge(progressIndicator: ProgressIndicator, commitMessage: Pair<String, String>, currentHeadRef: String) : CompletableFuture<Unit> = stateService.merge(progressIndicator, pullRequestId, commitMessage, currentHeadRef).notifyState() override fun rebaseMerge(progressIndicator: ProgressIndicator, currentHeadRef: String): CompletableFuture<Unit> = stateService.rebaseMerge(progressIndicator, pullRequestId, currentHeadRef).notifyState() override fun squashMerge(progressIndicator: ProgressIndicator, commitMessage: Pair<String, String>, currentHeadRef: String) : CompletableFuture<Unit> = stateService.squashMerge(progressIndicator, pullRequestId, commitMessage, currentHeadRef).notifyState() private fun <T> CompletableFuture<T>.notifyState(): CompletableFuture<T> = completionOnEdt { detailsData.reloadDetails() messageBus.syncPublisher(GHPRDataOperationsListener.TOPIC).onStateChanged() } override fun dispose() { mergeabilityStateRequestValue.drop() baseBranchProtectionRulesRequestValue.drop() } }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/provider/GHPRStateDataProviderImpl.kt
519814993
class FooBar fun f(myFo<caret>) // ELEMENT_TEXT: myFooBar: FooBar
plugins/kotlin/completion/tests/testData/handlers/basic/parameterNameAndType/UserPrefix.kt
1357467855
package com.tungnui.dalatlaptop.views import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import android.widget.ImageView class ResizableImageViewHeight(context: Context, attrs: AttributeSet) : ImageView(context, attrs) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val d = drawable if (d != null) { // ceil not round - avoid thin vertical gaps along the left/right edges val height = MeasureSpec.getSize(heightMeasureSpec) val width = Math.ceil((height.toFloat() * d.intrinsicWidth.toFloat() / d.intrinsicHeight.toFloat()).toDouble()).toInt() setMeasuredDimension(width, height) } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec) } } }
app/src/main/java/com/tungnui/dalatlaptop/views/ResizableImageViewHeight.kt
3447840901
package net.techcable.sonarpet.nms import net.techcable.sonarpet.utils.NmsVersion import org.objectweb.asm.Type // Method names val NmsVersion.livingUpdateMethod: String get() = getObfuscatedMethod("LIVING_UPDATE_METHOD") val NmsVersion.entityTickMethodName get() = getObfuscatedMethod("ENTITY_TICK_METHOD") val NmsVersion.entityMoveMethodName get() = getObfuscatedMethod("ENTITY_MOVE_METHOD") val NmsVersion.onStepMethodName get() = getObfuscatedMethod("ON_STEP_METHOD") val NmsVersion.onInteractMethodName get() = getObfuscatedMethod("ON_INTERACT_METHOD") val NmsVersion.proceduralAIMethodName get() = getObfuscatedMethod("ENTITY_PROCEDURAL_AI_METHOD") val NmsVersion.rabbitSetMovementSpeed get() = getObfuscatedMethod("RABBIT_SET_MOVEMENT_SPEED") // Field names val NmsVersion.sidewaysMotionField get() = getObfuscatedField("ENTITY_SIDEWAYS_MOTION_FIELD") val NmsVersion.forwardMotionField get() = getObfuscatedField("ENTITY_FORWARD_MOTION_FIELD") val NmsVersion.upwardsMotionField: String? get() = tryGetObfuscatedField("ENTITY_UPWARDS_MOTION_FIELD") // Other /** * Before 1.12, the entity move method accepted two floats for both sideways and forwards direction. * After 1.12, it also accepts an additional float for up/down movement, giving it three paramteers in total. */ val NmsVersion.entityMoveMethodParameters: Array<Type> get() { val amount = if (this >= NmsVersion.v1_12_R1) 3 else 2 return Array(amount) { Type.FLOAT_TYPE } }
api/src/main/kotlin/net/techcable/sonarpet/nms/obfuscation.kt
4179293916
package eu.kanade.tachiyomi.ui.manga.chapter import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.content.Intent import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v7.view.ActionMode import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.view.* import com.afollestad.materialdialogs.MaterialDialog import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.download.model.Download import eu.kanade.tachiyomi.ui.base.adapter.FlexibleViewHolder import eu.kanade.tachiyomi.ui.base.fragment.BaseRxFragment import eu.kanade.tachiyomi.ui.manga.MangaActivity import eu.kanade.tachiyomi.ui.reader.ReaderActivity import eu.kanade.tachiyomi.util.getCoordinates import eu.kanade.tachiyomi.util.toast import eu.kanade.tachiyomi.widget.DeletingChaptersDialog import kotlinx.android.synthetic.main.fragment_manga_chapters.* import nucleus.factory.RequiresPresenter import timber.log.Timber @RequiresPresenter(ChaptersPresenter::class) class ChaptersFragment : BaseRxFragment<ChaptersPresenter>(), ActionMode.Callback, FlexibleViewHolder.OnListItemClickListener { companion object { /** * Creates a new instance of this fragment. * * @return a new instance of [ChaptersFragment]. */ fun newInstance(): ChaptersFragment { return ChaptersFragment() } } /** * Adapter containing a list of chapters. */ private lateinit var adapter: ChaptersAdapter /** * Action mode for multiple selection. */ private var actionMode: ActionMode? = null override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedState: Bundle?): View? { return inflater.inflate(R.layout.fragment_manga_chapters, container, false) } override fun onViewCreated(view: View, savedState: Bundle?) { // Init RecyclerView and adapter adapter = ChaptersAdapter(this) recycler.adapter = adapter recycler.layoutManager = LinearLayoutManager(activity) recycler.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) recycler.setHasFixedSize(true) swipe_refresh.setOnRefreshListener { fetchChapters() } fab.setOnClickListener { val chapter = presenter.getNextUnreadChapter() if (chapter != null) { // Create animation listener val revealAnimationListener: Animator.AnimatorListener = object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { openChapter(chapter, true) } } // Get coordinates and start animation val coordinates = fab.getCoordinates() if (!reveal_view.showRevealEffect(coordinates.x, coordinates.y, revealAnimationListener)) { openChapter(chapter) } } else { context.toast(R.string.no_next_chapter) } } } override fun onPause() { // Stop recycler's scrolling when onPause is called. If the activity is finishing // the presenter will be destroyed, and it could cause NPE // https://github.com/inorichi/tachiyomi/issues/159 recycler.stopScroll() super.onPause() } override fun onResume() { // Check if animation view is visible if (reveal_view.visibility == View.VISIBLE) { // Show the unReveal effect val coordinates = fab.getCoordinates() reveal_view.hideRevealEffect(coordinates.x, coordinates.y, 1920) } super.onResume() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.chapters, menu) } override fun onPrepareOptionsMenu(menu: Menu) { // Initialize menu items. val menuFilterRead = menu.findItem(R.id.action_filter_read) val menuFilterUnread = menu.findItem(R.id.action_filter_unread) val menuFilterDownloaded = menu.findItem(R.id.action_filter_downloaded) val menuFilterBookmarked = menu.findItem(R.id.action_filter_bookmarked) // Set correct checkbox values. menuFilterRead.isChecked = presenter.onlyRead() menuFilterUnread.isChecked = presenter.onlyUnread() menuFilterDownloaded.isChecked = presenter.onlyDownloaded() menuFilterBookmarked.isChecked = presenter.onlyBookmarked() if (presenter.onlyRead()) //Disable unread filter option if read filter is enabled. menuFilterUnread.isEnabled = false if (presenter.onlyUnread()) //Disable read filter option if unread filter is enabled. menuFilterRead.isEnabled = false } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_display_mode -> showDisplayModeDialog() R.id.manga_download -> showDownloadDialog() R.id.action_sorting_mode -> showSortingDialog() R.id.action_filter_unread -> { item.isChecked = !item.isChecked presenter.setUnreadFilter(item.isChecked) activity.supportInvalidateOptionsMenu() } R.id.action_filter_read -> { item.isChecked = !item.isChecked presenter.setReadFilter(item.isChecked) activity.supportInvalidateOptionsMenu() } R.id.action_filter_downloaded -> { item.isChecked = !item.isChecked presenter.setDownloadedFilter(item.isChecked) } R.id.action_filter_bookmarked -> { item.isChecked = !item.isChecked presenter.setBookmarkedFilter(item.isChecked) } R.id.action_filter_empty -> { presenter.removeFilters() activity.supportInvalidateOptionsMenu() } R.id.action_sort -> presenter.revertSortOrder() else -> return super.onOptionsItemSelected(item) } return true } fun onNextManga(manga: Manga) { // Set initial values activity.supportInvalidateOptionsMenu() } fun onNextChapters(chapters: List<ChapterModel>) { // If the list is empty, fetch chapters from source if the conditions are met // We use presenter chapters instead because they are always unfiltered if (presenter.chapters.isEmpty()) initialFetchChapters() destroyActionModeIfNeeded() adapter.setItems(chapters) } private fun initialFetchChapters() { // Only fetch if this view is from the catalog and it hasn't requested previously if (isCatalogueManga && !presenter.hasRequested) { fetchChapters() } } fun fetchChapters() { swipe_refresh.isRefreshing = true presenter.fetchChaptersFromSource() } fun onFetchChaptersDone() { swipe_refresh.isRefreshing = false } fun onFetchChaptersError(error: Throwable) { swipe_refresh.isRefreshing = false context.toast(error.message) } val isCatalogueManga: Boolean get() = (activity as MangaActivity).fromCatalogue fun openChapter(chapter: Chapter, hasAnimation: Boolean = false) { val intent = ReaderActivity.newIntent(activity, presenter.manga, chapter) if (hasAnimation) { intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION) } startActivity(intent) } private fun showDisplayModeDialog() { // Get available modes, ids and the selected mode val modes = intArrayOf(R.string.show_title, R.string.show_chapter_number) val ids = intArrayOf(Manga.DISPLAY_NAME, Manga.DISPLAY_NUMBER) val selectedIndex = if (presenter.manga.displayMode == Manga.DISPLAY_NAME) 0 else 1 MaterialDialog.Builder(activity) .title(R.string.action_display_mode) .items(modes.map { getString(it) }) .itemsIds(ids) .itemsCallbackSingleChoice(selectedIndex) { dialog, itemView, which, text -> // Save the new display mode presenter.setDisplayMode(itemView.id) // Refresh ui adapter.notifyItemRangeChanged(0, adapter.itemCount) true } .show() } private fun showSortingDialog() { // Get available modes, ids and the selected mode val modes = intArrayOf(R.string.sort_by_source, R.string.sort_by_number) val ids = intArrayOf(Manga.SORTING_SOURCE, Manga.SORTING_NUMBER) val selectedIndex = if (presenter.manga.sorting == Manga.SORTING_SOURCE) 0 else 1 MaterialDialog.Builder(activity) .title(R.string.sorting_mode) .items(modes.map { getString(it) }) .itemsIds(ids) .itemsCallbackSingleChoice(selectedIndex) { dialog, itemView, which, text -> // Save the new sorting mode presenter.setSorting(itemView.id) true } .show() } private fun showDownloadDialog() { // Get available modes val modes = intArrayOf(R.string.download_1, R.string.download_5, R.string.download_10, R.string.download_unread, R.string.download_all) MaterialDialog.Builder(activity) .title(R.string.manga_download) .negativeText(android.R.string.cancel) .items(modes.map { getString(it) }) .itemsCallback { dialog, view, i, charSequence -> fun getUnreadChaptersSorted() = presenter.chapters .filter { !it.read && !it.isDownloaded } .distinctBy { it.name } .sortedByDescending { it.source_order } // i = 0: Download 1 // i = 1: Download 5 // i = 2: Download 10 // i = 3: Download unread // i = 4: Download all val chaptersToDownload = when (i) { 0 -> getUnreadChaptersSorted().take(1) 1 -> getUnreadChaptersSorted().take(5) 2 -> getUnreadChaptersSorted().take(10) 3 -> presenter.chapters.filter { !it.read } 4 -> presenter.chapters else -> emptyList() } if (chaptersToDownload.isNotEmpty()) { downloadChapters(chaptersToDownload) } } .show() } fun onChapterStatusChange(download: Download) { getHolder(download.chapter)?.notifyStatus(download.status) } private fun getHolder(chapter: Chapter): ChaptersHolder? { return recycler.findViewHolderForItemId(chapter.id!!) as? ChaptersHolder } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.chapter_selection, menu) adapter.mode = FlexibleAdapter.MODE_MULTI return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { return false } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { R.id.action_select_all -> selectAll() R.id.action_mark_as_read -> markAsRead(getSelectedChapters()) R.id.action_mark_as_unread -> markAsUnread(getSelectedChapters()) R.id.action_download -> downloadChapters(getSelectedChapters()) R.id.action_delete -> { MaterialDialog.Builder(activity) .content(R.string.confirm_delete_chapters) .positiveText(android.R.string.yes) .negativeText(android.R.string.no) .onPositive { dialog, action -> deleteChapters(getSelectedChapters()) } .show() } else -> return false } return true } override fun onDestroyActionMode(mode: ActionMode) { adapter.mode = FlexibleAdapter.MODE_SINGLE adapter.clearSelection() actionMode = null } fun getSelectedChapters(): List<ChapterModel> { return adapter.selectedItems.map { adapter.getItem(it) } } fun destroyActionModeIfNeeded() { actionMode?.finish() } fun selectAll() { adapter.selectAll() setContextTitle(adapter.selectedItemCount) } fun markAsRead(chapters: List<ChapterModel>) { presenter.markChaptersRead(chapters, true) if (presenter.preferences.removeAfterMarkedAsRead()) { deleteChapters(chapters) } } fun markAsUnread(chapters: List<ChapterModel>) { presenter.markChaptersRead(chapters, false) } fun markPreviousAsRead(chapter: ChapterModel) { presenter.markPreviousChaptersAsRead(chapter) } fun downloadChapters(chapters: List<ChapterModel>) { destroyActionModeIfNeeded() presenter.downloadChapters(chapters) } fun bookmarkChapters(chapters: List<ChapterModel>, bookmarked: Boolean) { destroyActionModeIfNeeded() presenter.bookmarkChapters(chapters,bookmarked) } fun deleteChapters(chapters: List<ChapterModel>) { destroyActionModeIfNeeded() DeletingChaptersDialog().show(childFragmentManager, DeletingChaptersDialog.TAG) presenter.deleteChapters(chapters) } fun onChaptersDeleted() { dismissDeletingDialog() adapter.notifyItemRangeChanged(0, adapter.itemCount) } fun onChaptersDeletedError(error: Throwable) { dismissDeletingDialog() Timber.e(error) } fun dismissDeletingDialog() { (childFragmentManager.findFragmentByTag(DeletingChaptersDialog.TAG) as? DialogFragment)?.dismiss() } override fun onListItemClick(position: Int): Boolean { val item = adapter.getItem(position) ?: return false if (actionMode != null && adapter.mode == FlexibleAdapter.MODE_MULTI) { toggleSelection(position) return true } else { openChapter(item) return false } } override fun onListItemLongClick(position: Int) { if (actionMode == null) actionMode = activity.startSupportActionMode(this) toggleSelection(position) } private fun toggleSelection(position: Int) { adapter.toggleSelection(position, false) val count = adapter.selectedItemCount if (count == 0) { actionMode?.finish() } else { setContextTitle(count) actionMode?.invalidate() } } private fun setContextTitle(count: Int) { actionMode?.title = getString(R.string.label_selected, count) } }
app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersFragment.kt
2237093846
package io.polymorphicpanda.zerofx.template.helpers import javafx.geometry.Pos import javafx.scene.layout.StackPane class StackPaneBuilder(pane: StackPane = StackPane()): PaneBuilder<StackPane>(pane) { fun alignmentProperty() = node.alignmentProperty() var alignment: Pos get() = alignmentProperty().get() set(value) { alignmentProperty().set(value) } }
zerofx-view-helpers/src/main/kotlin/io/polymorphicpanda/zerofx/template/helpers/StackPaneBuilder.kt
4118950294
package com.edreams.android.workshops.kotlin.injection.presentation import android.arch.lifecycle.ViewModel import dagger.MapKey import kotlin.annotation.AnnotationRetention.RUNTIME import kotlin.annotation.AnnotationTarget.FUNCTION import kotlin.reflect.KClass @MustBeDocumented @Target(FUNCTION) @Retention(RUNTIME) @MapKey internal annotation class ViewModelKey(val value: KClass<out ViewModel>)
injection/src/main/java/com/edreams/android/workshops/kotlin/injection/presentation/ViewModelKey.kt
2177468324
// Return all products this customer has ordered fun Customer.getOrderedProducts(): Set<Product> = this.orders.flatMap { it.products }.toSet() // Return all products that were ordered by at least one customer fun Shop.getAllOrderedProducts(): Set<Product> = this.customers.flatMap { it.getOrderedProducts() }.toSet()
lesson3/task4/src/Task.kt
2385914790
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ /** * This entire package was shamelessly taken from the IntelliJ Kotlin plugin, so thanks to the JetBrains folks for * that. Though a built-in system would be superior... * https://github.com/JetBrains/kotlin/blob/master/idea/src/org/jetbrains/kotlin/idea/actions/ConfigurePluginUpdatesAction.kt */ package com.demonwav.mcdev.update
src/main/kotlin/com/demonwav/mcdev/update/package-info.kt
210767028
package com.paramsen.noise.sample.view /** * @author Pär Amsen 07/2017 */ interface FFTView { fun onFFT(fft: FloatArray) }
sample/src/main/java/com/paramsen/noise/sample/view/FFTView.kt
2096925450
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Method2 import org.objectweb.asm.Type.* import org.runestar.client.updater.mapper.UniqueMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Instruction2 class Node : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.instanceFields.size == 3 } .and { it.instanceFields.count { it.type == LONG_TYPE } == 1 } .and { it.superType == Any::class.type } .and { c -> c.instanceFields.count { it.type == c.type } == 2 } class key : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == LONG_TYPE } } @DependsOn(next::class) class previous : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<Node>() } .and { it != field<next>() } } @DependsOn(hasNext::class) class next : UniqueMapper.InMethod.Field(hasNext::class) { override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.GETFIELD } } @MethodParameters() class hasNext : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE } } @MethodParameters() class remove : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } } }
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Node.kt
1362226017
// 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.stubindex import com.intellij.find.ngrams.TrigramIndex import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.FilenameIndex import com.intellij.util.indexing.GlobalIndexFilter import com.intellij.util.indexing.IndexId import org.jetbrains.kotlin.idea.KotlinFileType class KotlinNonSourceRootIndexFilter: GlobalIndexFilter { private val enabled = !System.getProperty("kotlin.index.non.source.roots", "true").toBoolean() override fun isExcludedFromIndex(virtualFile: VirtualFile, indexId: IndexId<*, *>): Boolean = false override fun isExcludedFromIndex(virtualFile: VirtualFile, indexId: IndexId<*, *>, project: Project?): Boolean = project != null && affectsIndex(indexId) && virtualFile.extension == KotlinFileType.EXTENSION && ProjectRootManager.getInstance(project).fileIndex.getOrderEntriesForFile(virtualFile).isEmpty() && !ProjectFileIndex.getInstance(project).isInLibrary(virtualFile) override fun getVersion(): Int = 0 override fun affectsIndex(indexId: IndexId<*, *>): Boolean = enabled && (indexId !== TrigramIndex.INDEX_ID && indexId !== FilenameIndex.NAME) }
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinNonSourceRootIndexFilter.kt
769761753
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide.impl.jps.serialization import com.intellij.ide.impl.runUnderModalProgressIfIsEdt import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.components.PathMacroMap import com.intellij.openapi.components.impl.ModulePathMacroManager import com.intellij.openapi.components.impl.ProjectPathMacroManager import com.intellij.openapi.project.ExternalStorageConfigurationManager import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.systemIndependentPath import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.testFramework.UsefulTestCase import com.intellij.workspaceModel.ide.JpsFileEntitySource import com.intellij.workspaceModel.ide.JpsProjectConfigLocation import com.intellij.workspaceModel.ide.impl.FileInDirectorySourceNames import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.url.toVirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import junit.framework.AssertionFailedError import org.jdom.Element import org.jetbrains.jps.model.serialization.JDomSerializationUtil import org.jetbrains.jps.model.serialization.PathMacroUtil import org.jetbrains.jps.util.JpsPathUtil import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import java.io.File import java.nio.file.Path import java.util.function.Supplier internal val sampleDirBasedProjectFile = File(PathManagerEx.getCommunityHomePath(), "jps/model-serialization/testData/sampleProject") internal val sampleFileBasedProjectFile = File(PathManagerEx.getCommunityHomePath(), "jps/model-serialization/testData/sampleProject-ipr/sampleProject.ipr") internal data class LoadedProjectData( val storage: EntityStorageSnapshot, val serializers: JpsProjectSerializersImpl, val configLocation: JpsProjectConfigLocation, val originalProjectDir: File ) { val projectDirUrl: String get() = configLocation.baseDirectoryUrlString val projectDir: File get() = File(VfsUtilCore.urlToPath(configLocation.baseDirectoryUrlString)) } internal fun copyAndLoadProject(originalProjectFile: File, virtualFileManager: VirtualFileUrlManager): LoadedProjectData { val (projectDir, originalProjectDir) = copyProjectFiles(originalProjectFile) val originalBuilder = MutableEntityStorage.create() val projectFile = if (originalProjectFile.isFile) File(projectDir, originalProjectFile.name) else projectDir val configLocation = toConfigLocation(projectFile.toPath(), virtualFileManager) val serializers = loadProject(configLocation, originalBuilder, virtualFileManager) as JpsProjectSerializersImpl val loadedProjectData = LoadedProjectData(originalBuilder.toSnapshot(), serializers, configLocation, originalProjectDir) serializers.checkConsistency(loadedProjectData.configLocation, loadedProjectData.storage, virtualFileManager) return loadedProjectData } internal fun copyProjectFiles(originalProjectFile: File): Pair<File, File> { val projectDir = FileUtil.createTempDirectory("jpsProjectTest", null) val originalProjectDir = if (originalProjectFile.isFile) originalProjectFile.parentFile else originalProjectFile FileUtil.copyDir(originalProjectDir, projectDir) return projectDir to originalProjectDir } internal fun loadProject(configLocation: JpsProjectConfigLocation, originalBuilder: MutableEntityStorage, virtualFileManager: VirtualFileUrlManager, fileInDirectorySourceNames: FileInDirectorySourceNames = FileInDirectorySourceNames.empty(), externalStorageConfigurationManager: ExternalStorageConfigurationManager? = null): JpsProjectSerializers { val cacheDirUrl = configLocation.baseDirectoryUrl.append("cache") return runUnderModalProgressIfIsEdt { JpsProjectEntitiesLoader.loadProject(configLocation, originalBuilder, File(VfsUtil.urlToPath(cacheDirUrl.url)).toPath(), TestErrorReporter, virtualFileManager, fileInDirectorySourceNames, externalStorageConfigurationManager) } } internal fun JpsProjectSerializersImpl.saveAllEntities(storage: EntityStorage, configLocation: JpsProjectConfigLocation) { val writer = JpsFileContentWriterImpl(configLocation) saveAllEntities(storage, writer) writer.writeFiles() } internal fun assertDirectoryMatches(actualDir: File, expectedDir: File, filesToIgnore: Set<String>, componentsToIgnore: List<String>) { val actualFiles = actualDir.walk().filter { it.isFile }.associateBy { FileUtil.toSystemIndependentName(FileUtil.getRelativePath(actualDir, it)!!) } val expectedFiles = expectedDir.walk() .filter { it.isFile } .associateBy { FileUtil.toSystemIndependentName(FileUtil.getRelativePath(expectedDir, it)!!) } .filterKeys { it !in filesToIgnore } for (actualPath in actualFiles.keys) { val actualFile = actualFiles.getValue(actualPath) if (actualPath in expectedFiles) { val expectedFile = expectedFiles.getValue(actualPath) if (actualFile.extension in setOf("xml", "iml", "ipr")) { val expectedTag = JDOMUtil.load(expectedFile) componentsToIgnore.forEach { val toIgnore = JDomSerializationUtil.findComponent(expectedTag, it) if (toIgnore != null) { expectedTag.removeContent(toIgnore) } } val actualTag = JDOMUtil.load(actualFile) assertEquals("Different content in $actualPath", JDOMUtil.write(expectedTag), JDOMUtil.write(actualTag)) } else { assertEquals("Different content in $actualPath", expectedFile.readText(), actualFile.readText()) } } } UsefulTestCase.assertEmpty(actualFiles.keys - expectedFiles.keys) UsefulTestCase.assertEmpty(expectedFiles.keys - actualFiles.keys) } internal fun createProjectSerializers(projectDir: File, virtualFileManager: VirtualFileUrlManager): Pair<JpsProjectSerializersImpl, JpsProjectConfigLocation> { val configLocation = toConfigLocation(projectDir.toPath(), virtualFileManager) val reader = CachingJpsFileContentReader(configLocation) val externalStoragePath = projectDir.toPath().resolve("cache") val serializer = JpsProjectEntitiesLoader.createProjectSerializers(configLocation, reader, externalStoragePath, virtualFileManager) as JpsProjectSerializersImpl return serializer to configLocation } fun JpsProjectSerializersImpl.checkConsistency(configLocation: JpsProjectConfigLocation, storage: EntityStorage, virtualFileManager: VirtualFileUrlManager) { fun getNonNullActualFileUrl(source: EntitySource): String { return getActualFileUrl(source) ?: throw AssertionFailedError("file name is not registered for $source") } directorySerializerFactoriesByUrl.forEach { (url, directorySerializer) -> assertEquals(url, directorySerializer.directoryUrl) val fileSerializers = serializerToDirectoryFactory.getKeysByValue(directorySerializer) ?: emptyList() val directoryFileUrls = JpsPathUtil.urlToFile(url).listFiles { file: File -> file.isFile }?.map { JpsPathUtil.pathToUrl(it.systemIndependentPath) } ?: emptyList() assertEquals(directoryFileUrls.sorted(), fileSerializers.map { getNonNullActualFileUrl(it.internalEntitySource) }.sorted()) } moduleListSerializersByUrl.forEach { (url, fileSerializer) -> assertEquals(url, fileSerializer.fileUrl) val fileSerializers = moduleSerializers.getKeysByValue(fileSerializer) ?: emptyList() val urlsFromFactory = fileSerializer.loadFileList(CachingJpsFileContentReader(configLocation), virtualFileManager) assertEquals(urlsFromFactory.map { it.first.url }.sorted(), fileSerializers.map { getNonNullActualFileUrl(it.internalEntitySource) }.sorted()) } fileSerializersByUrl.keys.associateWith { fileSerializersByUrl.getValues(it) }.forEach { (url, serializers) -> serializers.forEach { assertEquals(url, getNonNullActualFileUrl(it.internalEntitySource)) } } moduleSerializers.keys.forEach { assertTrue(it in fileSerializersByUrl.getValues(getNonNullActualFileUrl(it.internalEntitySource))) } serializerToDirectoryFactory.keys.forEach { assertTrue(it in fileSerializersByUrl.getValues(getNonNullActualFileUrl(it.internalEntitySource))) } fun <E : WorkspaceEntity> isSerializerWithoutEntities(serializer: JpsFileEntitiesSerializer<E>) = serializer is JpsFileEntityTypeSerializer<E> && storage.entities(serializer.mainEntityClass).none { serializer.entityFilter(it) } val allSources = storage.entitiesBySource { true } val urlsFromSources = allSources.keys.filterIsInstance<JpsFileEntitySource>().mapTo(HashSet()) { getNonNullActualFileUrl(it) } assertEquals(urlsFromSources.sorted(), fileSerializersByUrl.keys.associateWith { fileSerializersByUrl.getValues(it) } .filterNot { entry -> entry.value.all { isSerializerWithoutEntities(it)} }.map { it.key }.sorted()) val fileIdFromEntities = allSources.keys.filterIsInstance(JpsFileEntitySource.FileInDirectory::class.java).mapTo(HashSet()) { it.fileNameId } val unregisteredIds = fileIdFromEntities - fileIdToFileName.keys.toSet() assertTrue("Some fileNameId aren't registered: ${unregisteredIds}", unregisteredIds.isEmpty()) val staleIds = fileIdToFileName.keys.toSet() - fileIdFromEntities assertTrue("There are stale mapping for some fileNameId: ${staleIds.joinToString { "$it -> ${fileIdToFileName.get(it)}" }}", staleIds.isEmpty()) } internal fun File.asConfigLocation(virtualFileManager: VirtualFileUrlManager): JpsProjectConfigLocation = toConfigLocation(toPath(), virtualFileManager) internal fun toConfigLocation(file: Path, virtualFileManager: VirtualFileUrlManager): JpsProjectConfigLocation { if (FileUtil.extensionEquals(file.fileName.toString(), "ipr")) { val iprFile = file.toVirtualFileUrl(virtualFileManager) return JpsProjectConfigLocation.FileBased(iprFile, virtualFileManager.getParentVirtualUrl(iprFile)!!) } else { val projectDir = file.toVirtualFileUrl(virtualFileManager) return JpsProjectConfigLocation.DirectoryBased(projectDir, projectDir.append(PathMacroUtil.DIRECTORY_STORE_NAME)) } } internal class JpsFileContentWriterImpl(private val configLocation: JpsProjectConfigLocation) : JpsFileContentWriter { val urlToComponents = LinkedHashMap<String, LinkedHashMap<String, Element?>>() override fun saveComponent(fileUrl: String, componentName: String, componentTag: Element?) { urlToComponents.computeIfAbsent(fileUrl) { LinkedHashMap() }[componentName] = componentTag } override fun getReplacePathMacroMap(fileUrl: String): PathMacroMap { return if (isModuleFile(JpsPathUtil.urlToFile(fileUrl))) ModulePathMacroManager.createInstance(configLocation::projectFilePath, Supplier { JpsPathUtil.urlToOsPath(fileUrl) }).replacePathMap else ProjectPathMacroManager.createInstance(configLocation::projectFilePath, { JpsPathUtil.urlToPath(configLocation.baseDirectoryUrlString) }, null).replacePathMap } internal fun writeFiles() { urlToComponents.forEach { (url, newComponents) -> val components = HashMap(newComponents) val file = JpsPathUtil.urlToFile(url) val replaceMacroMap = getReplacePathMacroMap(url) val newRootElement = when { isModuleFile(file) -> Element("module") FileUtil.filesEqual(File(JpsPathUtil.urlToPath(configLocation.baseDirectoryUrlString), ".idea"), file.parentFile.parentFile) -> null else -> Element("project") } fun isEmptyComponentTag(componentTag: Element) = componentTag.contentSize == 0 && componentTag.attributes.all { it.name == "name" } val rootElement: Element? if (newRootElement != null) { if (file.exists()) { val oldElement = JDOMUtil.load(file) oldElement.getChildren("component") .filterNot { it.getAttributeValue("name") in components } .map { it.clone() } .associateByTo(components) { it.getAttributeValue("name") } } components.entries.sortedBy { it.key }.forEach { (name, element) -> if (element != null && !isEmptyComponentTag(element)) { if (name == DEPRECATED_MODULE_MANAGER_COMPONENT_NAME) { element.getChildren("option").forEach { newRootElement.setAttribute(it.getAttributeValue("key")!!, it.getAttributeValue("value")!!) } } else { newRootElement.addContent(element) } } } if (!JDOMUtil.isEmpty(newRootElement)) { newRootElement.setAttribute("version", "4") rootElement = newRootElement } else { rootElement = null } } else { val singleComponent = components.values.single() rootElement = if (singleComponent != null && !isEmptyComponentTag(singleComponent)) singleComponent else null } if (rootElement != null) { replaceMacroMap.substitute(rootElement, true, true) FileUtil.createParentDirs(file) JDOMUtil.write(rootElement, file) } else { FileUtil.delete(file) } } } private fun isModuleFile(file: File) = (FileUtil.extensionEquals(file.absolutePath, "iml") || file.parentFile.name == "modules" && file.parentFile.parentFile.name != ".idea") } internal object TestErrorReporter : ErrorReporter { override fun reportError(message: String, file: VirtualFileUrl) { throw AssertionFailedError("Failed to load ${file.url}: $message") } }
platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/impl/jps/serialization/jpsTestUtils.kt
1265835966
// 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.ui.popup.list import com.intellij.openapi.util.NlsActions.ActionText import com.intellij.ui.ExperimentalUI import com.intellij.ui.popup.ActionPopupStep import java.awt.Point import java.awt.event.InputEvent import javax.swing.JComponent import javax.swing.JList private val Empty = object : PopupInlineActionsSupport { override fun calcExtraButtonsCount(element: Any?): Int = 0 override fun calcButtonIndex(element: Any?, point: Point): Int? = null override fun getInlineAction(element: Any?, index: Int, event: InputEvent?) = InlineActionDescriptor({}, false) override fun getExtraButtons(list: JList<*>, value: Any?, isSelected: Boolean): List<JComponent> = emptyList() override fun getActiveButtonIndex(list: JList<*>): Int? = null override fun getActiveExtraButtonToolTipText(list: JList<*>, value: Any?): String? = null } internal interface PopupInlineActionsSupport { fun hasExtraButtons(element: Any?): Boolean = calcExtraButtonsCount(element) > 0 fun calcExtraButtonsCount(element: Any?): Int fun calcButtonIndex(element: Any?, point: Point): Int? fun getInlineAction(element: Any?, index: Int, event: InputEvent? = null) : InlineActionDescriptor fun getExtraButtons(list: JList<*>, value: Any?, isSelected: Boolean): List<JComponent> @ActionText fun getActiveExtraButtonToolTipText(list: JList<*>, value: Any?): String? fun getActiveButtonIndex(list: JList<*>): Int? companion object { fun create(popup: ListPopupImpl): PopupInlineActionsSupport { if (!ExperimentalUI.isNewUI()) return Empty if (popup.listStep is ActionPopupStep) return PopupInlineActionsSupportImpl(popup) return NonActionsPopupInlineSupport(popup) } } }
platform/platform-impl/src/com/intellij/ui/popup/list/PopupInlineActionsSupport.kt
663992406
package com.simplemobiletools.gallery.pro.helpers import android.graphics.* import com.squareup.picasso.Transformation // taken from https://stackoverflow.com/a/35241525/1967672 class PicassoRoundedCornersTransformation(private val radius: Float) : Transformation { override fun transform(source: Bitmap): Bitmap { val size = Math.min(source.width, source.height) val x = (source.width - size) / 2 val y = (source.height - size) / 2 val squaredBitmap = Bitmap.createBitmap(source, x, y, size, size) if (squaredBitmap != source) { source.recycle() } val bitmap = Bitmap.createBitmap(size, size, source.config) val canvas = Canvas(bitmap) val paint = Paint() val shader = BitmapShader(squaredBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) paint.shader = shader paint.isAntiAlias = true val rect = RectF(0f, 0f, source.width.toFloat(), source.height.toFloat()) canvas.drawRoundRect(rect, radius, radius, paint) squaredBitmap.recycle() return bitmap } override fun key() = "rounded_corners" }
app/src/main/kotlin/com/simplemobiletools/gallery/pro/helpers/PicassoRoundedCornersTransformation.kt
1262056519
// 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 com.intellij.codeInsight.daemon.impl import com.intellij.codeInsight.codeVision.CodeVisionRelativeOrdering import com.intellij.codeInsight.hints.codeVision.ReferencesCodeVisionProvider import com.intellij.java.JavaBundle import com.intellij.lang.java.JavaLanguage import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiMember import com.intellij.psi.PsiTypeParameter class JavaReferencesCodeVisionProvider : ReferencesCodeVisionProvider() { companion object{ const val ID = "java.references" } override fun acceptsFile(file: PsiFile): Boolean = file.language == JavaLanguage.INSTANCE override fun acceptsElement(element: PsiElement): Boolean = element is PsiMember && element !is PsiTypeParameter override fun getHint(element: PsiElement, file: PsiFile): String? = JavaTelescope.usagesHint(element as PsiMember, file) override fun logClickToFUS(element: PsiElement, hint: String) { JavaCodeVisionUsageCollector.USAGES_CLICKED_EVENT_ID.log(element.project) } override val name: String get() = JavaBundle.message("settings.inlay.java.usages") override val relativeOrderings: List<CodeVisionRelativeOrdering> get() = listOf(CodeVisionRelativeOrdering.CodeVisionRelativeOrderingBefore("java.inheritors")) override val id: String get() = ID }
java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaReferencesCodeVisionProvider.kt
3829202519
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsRoot import com.intellij.vcsUtil.VcsUtil internal class DirtBuilder { private val scopesByVcs: MutableMap<AbstractVcs, VcsDirtyScopeImpl> = mutableMapOf() var isEverythingDirty: Boolean = false private set fun markEverythingDirty() { isEverythingDirty = true scopesByVcs.clear() } fun addDirtyFiles(vcsRoot: VcsRoot, files: Collection<FilePath>, dirs: Collection<FilePath>): Boolean { if (isEverythingDirty) return true val vcs = vcsRoot.vcs val root = vcsRoot.path if (vcs != null) { val scope = scopesByVcs.computeIfAbsent(vcs) { VcsDirtyScopeImpl(it, isEverythingDirty) } for (filePath in files) { scope.addDirtyPathFast(root, filePath, false) } for (filePath in dirs) { scope.addDirtyPathFast(root, filePath, true) } } return scopesByVcs.isNotEmpty() } fun buildScopes(project: Project): List<VcsDirtyScopeImpl> { val scopes: Collection<VcsDirtyScopeImpl> if (isEverythingDirty) { val allScopes = mutableMapOf<AbstractVcs, VcsDirtyScopeImpl>() for (root in ProjectLevelVcsManager.getInstance(project).allVcsRoots) { val vcs = root.vcs val path = root.path if (vcs != null) { val scope = allScopes.computeIfAbsent(vcs) { VcsDirtyScopeImpl(it, isEverythingDirty) } scope.addDirtyPathFast(path, VcsUtil.getFilePath(path), true) } } scopes = allScopes.values } else { scopes = scopesByVcs.values } return scopes.map { it.pack() } } fun isFileDirty(filePath: FilePath): Boolean = isEverythingDirty || scopesByVcs.values.any { it.belongsTo(filePath) } }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/DirtBuilder.kt
1374633064
package ch.difty.scipamato.core.persistence import ch.difty.scipamato.core.entity.CoreEntity import io.mockk.every import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeNull import org.jooq.Record import org.jooq.RecordMapper import org.junit.jupiter.api.Test import org.junit.jupiter.api.fail import java.sql.Timestamp abstract class RecordMapperTest<R : Record, E : CoreEntity> { protected abstract val mapper: RecordMapper<R, E> @Test internal fun mapping_mapsRecordToEntity() { val record = makeRecord() setAuditFieldsIn(record) val entity = mapper.map(record) ?: fail("Unable to get entity") assertEntity(entity) assertAuditFieldsOf(entity) } /** * Create the record and set its field (except for the audit fields, which are * set separately). */ protected abstract fun makeRecord(): R /** * `<pre> * record.setCreated(CREATED); * record.setCreatedBy(CREATED_BY); * record.setLastModified(LAST_MOD); * record.setLastModifiedBy(LAST_MOD_BY); * record.setVersion(VERSION); </pre>` * * * @param record * for which the audit fields are set into */ protected abstract fun setAuditFieldsIn(record: R) /** * Assert non-audit fields of entity (audit fields are asserted separately) * * @param entity * the entity to assert the non-audit fields for */ protected abstract fun assertEntity(entity: E) private fun assertAuditFieldsOf(e: E) { e.version shouldBeEqualTo VERSION e.created shouldBeEqualTo CREATED.toLocalDateTime() e.createdBy shouldBeEqualTo CREATED_BY e.lastModified shouldBeEqualTo LAST_MOD.toLocalDateTime() e.lastModifiedBy shouldBeEqualTo LAST_MOD_BY // not enriched by service e.createdByName.shouldBeNull() e.createdByFullName.shouldBeNull() e.lastModifiedByName.shouldBeNull() } companion object { const val VERSION = 1 val CREATED = Timestamp(1469999999999L) const val CREATED_BY = 1 val LAST_MOD = Timestamp(1479999999999L) const val LAST_MOD_BY = 2 /** * Test fixture for the entity mock audit fields. * * @param entityMock * the mocked entity */ fun auditFixtureFor(entityMock: CoreEntity) { every { entityMock.createdBy } returns CREATED_BY every { entityMock.lastModifiedBy } returns LAST_MOD_BY } /** * Test fixture for the entity mock audit fields. * * @param entityMock * the mocked entity */ fun auditExtendedFixtureFor(entityMock: CoreEntity) { every { entityMock.created } returns CREATED.toLocalDateTime() every { entityMock.lastModified } returns LAST_MOD.toLocalDateTime() every { entityMock.version } returns VERSION } } }
core/core-persistence-jooq/src/test/kotlin/ch/difty/scipamato/core/persistence/RecordMapperTest.kt
2600615117
// 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.remote import com.google.common.net.HostAndPort import com.intellij.openapi.diagnostic.logger import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.isPending import java.io.InputStream import java.io.OutputStream import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import kotlin.math.max import kotlin.system.measureNanoTime /** * Asynchronous adapter for synchronous process callers. Intended for usage in cases when blocking calls like [ProcessBuilder.start] * are called in EDT and it's uneasy to refactor. Anyway, better to not call blocking methods in EDT rather than use this class. */ class DeferredRemoteProcess(private val promise: Promise<RemoteProcess>) : RemoteProcess() { override fun getOutputStream(): OutputStream = DeferredOutputStream() override fun getInputStream(): InputStream = DeferredInputStream { it.inputStream } override fun getErrorStream(): InputStream = DeferredInputStream { it.errorStream } override fun waitFor(): Int = get().waitFor() override fun waitFor(timeout: Long, unit: TimeUnit): Boolean { val process: RemoteProcess? val nanosSpent = measureNanoTime { process = promise.blockingGet(timeout.toInt(), unit) } val restTimeoutNanos = max(0, TimeUnit.NANOSECONDS.convert(timeout, unit) - nanosSpent) return process?.waitFor(restTimeoutNanos, TimeUnit.NANOSECONDS) ?: false } override fun exitValue(): Int = tryGet()?.exitValue() ?: throw IllegalStateException("Process is not terminated") override fun destroy() { runNowOrSchedule { it.destroy() } } override fun killProcessTree(): Boolean = runNowOrSchedule { it.killProcessTree() } ?: false override fun isDisconnected(): Boolean = tryGet()?.isDisconnected ?: false override fun getLocalTunnel(remotePort: Int): HostAndPort? = get().getLocalTunnel(remotePort) override fun destroyForcibly(): Process = runNowOrSchedule { it.destroyForcibly() } ?: this override fun supportsNormalTermination(): Boolean = true override fun isAlive(): Boolean = tryGet()?.isAlive ?: true override fun onExit(): CompletableFuture<Process> = CompletableFuture<Process>().also { promise.then(it::complete) } private fun get(): RemoteProcess = promise.blockingGet(Int.MAX_VALUE)!! private fun tryGet(): RemoteProcess? = promise.takeUnless { it.isPending }?.blockingGet(0) private fun <T> runNowOrSchedule(handler: (RemoteProcess) -> T): T? { val process = tryGet() return if (process != null) { handler(process) } else { val cause = Throwable("Initially called from this context.") promise.then { try { it?.let(handler) } catch (err: Throwable) { err.addSuppressed(cause) LOG.info("$this: Got an error that nothing could catch: ${err.message}", err) } } null } } private inner class DeferredOutputStream : OutputStream() { override fun close() { runNowOrSchedule { it.outputStream.close() } } override fun flush() { tryGet()?.outputStream?.flush() } override fun write(b: Int) { get().outputStream.write(b) } override fun write(b: ByteArray) { get().outputStream.write(b) } override fun write(b: ByteArray, off: Int, len: Int) { get().outputStream.write(b, off, len) } } private inner class DeferredInputStream(private val streamGetter: (RemoteProcess) -> InputStream) : InputStream() { override fun close() { runNowOrSchedule { streamGetter(it).close() } } override fun read(): Int = streamGetter(get()).read() override fun read(b: ByteArray): Int = streamGetter(get()).read(b) override fun read(b: ByteArray, off: Int, len: Int): Int = streamGetter(get()).read(b, off, len) override fun readAllBytes(): ByteArray = streamGetter(get()).readAllBytes() override fun readNBytes(len: Int): ByteArray = streamGetter(get()).readNBytes(len) override fun readNBytes(b: ByteArray, off: Int, len: Int): Int = streamGetter(get()).readNBytes(b, off, len) override fun skip(n: Long): Long = streamGetter(get()).skip(n) override fun available(): Int = tryGet()?.let(streamGetter)?.available() ?: 0 override fun markSupported(): Boolean = false } private companion object { private val LOG = logger<DeferredRemoteProcess>() } }
platform/platform-impl/src/com/intellij/remote/DeferredRemoteProcess.kt
684916178
package graphics.scenery.volumes import graphics.scenery.textures.Texture import graphics.scenery.textures.Texture.BorderColor import graphics.scenery.textures.UpdatableTexture.TextureExtents import graphics.scenery.textures.Texture.RepeatMode import graphics.scenery.textures.UpdatableTexture.TextureUpdate import graphics.scenery.backends.ShaderType import graphics.scenery.textures.UpdatableTexture import graphics.scenery.utils.LazyLogger import net.imglib2.type.numeric.NumericType import net.imglib2.type.numeric.integer.UnsignedByteType import net.imglib2.type.numeric.integer.UnsignedShortType import net.imglib2.type.numeric.real.FloatType import org.joml.* import org.lwjgl.system.MemoryUtil import tpietzsch.backend.* import tpietzsch.cache.TextureCache import tpietzsch.example2.LookupTextureARGB import tpietzsch.shadergen.Shader import java.nio.Buffer import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.FloatBuffer import java.util.concurrent.ConcurrentHashMap import kotlin.time.ExperimentalTime import tpietzsch.backend.Texture as BVVTexture /** * Context class for interaction with BigDataViewer-generated shaders. * * @author Ulrik Günther <[email protected]> * @author Tobias Pietzsch <[email protected]> */ open class SceneryContext(val node: VolumeManager, val useCompute: Boolean = false) : GpuContext { private val logger by LazyLogger() data class BindingState(var binding: Int, var uniformName: String?, var reallocate: Boolean = false) private val pboBackingStore = HashMap<StagingBuffer, ByteBuffer>() /** Factory for the autogenerated shaders. */ val factory = VolumeShaderFactory(useCompute) /** Reference to the currently bound texture cache. */ protected var currentlyBoundCache: Texture? = null /** Hashmap for references to the currently bound LUTs/texture atlases. */ protected var currentlyBoundTextures = ConcurrentHashMap<String, Texture>() /** Hashmap for storing associations between [Texture] objects, texture slots and uniform names. */ protected var bindings = ConcurrentHashMap<BVVTexture, BindingState>() /** Storage for deferred bindings, where the association between uniform and texture unit is not known upfront. */ protected var deferredBindings = ConcurrentHashMap<BVVTexture, (String) -> Unit>() protected var samplerKeys = listOf("volumeCache", "lutSampler", "volume_", "transferFunction_", "colorMap_") val uniformSetter = SceneryUniformSetter() /** * Uniform setter class */ inner class SceneryUniformSetter: SetUniforms { var modified: Boolean = false override fun shouldSet(modified: Boolean): Boolean = modified /** * Sets the uniform with [name] to the Integer [v0]. */ override fun setUniform1i(name: String, v0: Int) { logger.debug("Setting uniform $name to $v0") if(samplerKeys.any { name.startsWith(it) }) { val binding = bindings.entries.find { it.value.binding == v0 } if(binding != null) { bindings[binding.key] = BindingState(v0, name, binding.value.reallocate) } else { logger.warn("Binding for $name slot $v0 not found.") } } else { node.shaderProperties[name] = v0 } modified = true } /** * Sets the uniform with [name] to the Integer 2-vector [v0] and [v1]. */ override fun setUniform2i(name: String, v0: Int, v1: Int) { node.shaderProperties[name] = Vector2i(v0, v1) modified = true } /** * Sets the uniform with [name] to the Integer 3-vector [v0],[v1],[v2]. */ override fun setUniform3i(name: String, v0: Int, v1: Int, v2: Int) { node.shaderProperties[name] = Vector3i(v0, v1, v2) modified = true } /** * Sets the uniform with [name] to the Integer 4-vector [v0],[v1],[v2],[v3]. */ override fun setUniform4i(name: String, v0: Int, v1: Int, v2: Int, v3: Int) { node.shaderProperties[name] = Vector4i(v0, v1, v2, v3) modified = true } /** * Sets the uniform with [name] to the int array given by [value], containing [count] single values. */ override fun setUniform1iv(name: String, count: Int, value: IntArray) { node.shaderProperties[name] = value modified = true } /** * Sets the uniform with [name] to the int array given by [value], containing [count] 2-vectors. */ override fun setUniform2iv(name: String, count: Int, value: IntArray) { node.shaderProperties[name] = value modified = true } /** * Sets the uniform with [name] to the int array given by [value], containing [count] 3-vectors. * To conform with OpenGL/Vulkan UBO alignment rules, the array given will be padded to a 4-vector by zeroes. */ override fun setUniform3iv(name: String, count: Int, value: IntArray) { // in UBOs, arrays of vectors need to be padded, such that they start on // word boundaries, e.g. a 3-vector needs to start on byte 16. val padded = IntArray(4*count) var j = 0 for(i in 0 until count) { padded[j] = value[3*i] padded[j+1] = value[3*i+1] padded[j+2] = value[3*i+2] padded[j+3] = 0 j += 4 } node.shaderProperties[name] = padded modified = true } /** * Sets the uniform with [name] to the int array given by [value], containing [count] 4-vectors. */ override fun setUniform4iv(name: String, count: Int, value: IntArray) { node.shaderProperties[name] = value modified = true } /** * Sets the uniform with [name] to the Float [v0]. */ override fun setUniform1f(name: String, v0: Float) { node.shaderProperties[name] = v0 modified = true } /** * Sets the uniform with [name] to the Float 2-vector [v0],[v1]. */ override fun setUniform2f(name: String, v0: Float, v1: Float) { node.shaderProperties[name] = Vector2f(v0, v1) modified = true } /** * Sets the uniform with [name] to the Float 3-vector [v0],[v1],[v2]. */ override fun setUniform3f(name: String, v0: Float, v1: Float, v2: Float) { node.shaderProperties[name] = Vector3f(v0, v1, v2) modified = true } /** * Sets the uniform with [name] to the Float 4-vector [v0],[v1],[v2],[v3]. */ override fun setUniform4f(name: String, v0: Float, v1: Float, v2: Float, v3: Float) { node.shaderProperties[name] = Vector4f(v0, v1, v2, v3) modified = true } /** * Sets the uniform with [name] to the Float array given by [value], containing [count] single values. */ override fun setUniform1fv(name: String, count: Int, value: FloatArray) { node.shaderProperties[name] = value modified = true } /** * Sets the uniform with [name] to the Float array given by [value], containing [count] 2-vectors. */ override fun setUniform2fv(name: String, count: Int, value: FloatArray) { node.shaderProperties[name] = value modified = true } /** * Sets the uniform with [name] to the Float array given by [value], containing [count] 3-vectors. * To conform with OpenGL/Vulkan UBO alignment rules, the array given will be padded to a 4-vector by zeroes. */ override fun setUniform3fv(name: String, count: Int, value: FloatArray) { // in UBOs, arrays of vectors need to be padded, such that they start on // word boundaries, e.g. a 3-vector needs to start on byte 16. val padded = FloatArray(4*count) var j = 0 for(i in 0 until count) { padded[j] = value[3*i] padded[j+1] = value[3*i+1] padded[j+2] = value[3*i+2] padded[j+3] = 0.0f j += 4 } // value.asSequence().windowed(3, 3).forEach { // padded.addAll(it) // padded.add(0.0f) // } node.shaderProperties[name] = padded modified = true } /** * Sets the uniform with [name] to the Float array given by [value], containing [count] 4-vectors. */ override fun setUniform4fv(name: String, count: Int, value: FloatArray) { node.shaderProperties[name] = value modified = true } /** * Sets the uniform with [name] to the Float 3x3 matrix given in [value]. Set [transpose] if the matrix should * be transposed prior to setting. */ override fun setUniformMatrix3f(name: String, transpose: Boolean, value: FloatBuffer) { val matrix = value.duplicate() if(matrix.position() == matrix.capacity()) { matrix.flip() } val m = Matrix4f(matrix) if(transpose) { m.transpose() } node.shaderProperties[name] = m modified = true } /** * Sets the uniform with [name] to the Float 4x4 matrix given in [value]. Set [transpose] if the matrix should * be transposed prior to setting. */ override fun setUniformMatrix4f(name: String, transpose: Boolean, value: FloatBuffer) { val matrix = value.duplicate() if(matrix.position() == matrix.capacity()) { matrix.flip() } val m = Matrix4f(matrix) if(transpose) { m.transpose() } node.shaderProperties[name] = m modified = true } } var currentShader: Shader? = null /** * Update the shader set with the new [shader] given. */ override fun use(shader: Shader) { if(currentShader == null || currentShader != shader) { if(!useCompute) { factory.updateShaders( hashMapOf( ShaderType.VertexShader to shader, ShaderType.FragmentShader to shader)) } else { factory.updateShaders( hashMapOf(ShaderType.ComputeShader to shader), ) } currentShader = shader } } /** * Returns the uniform setter for [shader]. */ override fun getUniformSetter(shader: Shader): SetUniforms { return uniformSetter } /** * @param pbo StagingBuffer to bind * @return id of previously bound pbo */ override fun bindStagingBuffer(pbo: StagingBuffer): Int { logger.debug("Binding PBO $pbo") return 0 } /** * @param id pbo id to bind * @return id of previously bound pbo */ override fun bindStagingBufferId(id: Int): Int { logger.debug("Binding PBO $id") return id } private fun dimensionsMatch(texture: BVVTexture, current: Texture?): Boolean { if(current == null) { return false } if(texture.texWidth() == current.dimensions.x && texture.texHeight() == current.dimensions.y && texture.texDepth() == current.dimensions.z) { return true } return false } /** * @param texture texture to bind * @return id of previously bound texture */ override fun bindTexture(texture: BVVTexture): Int { logger.debug("Binding $texture and updating GT") val (channels, type: NumericType<*>, normalized) = when(texture.texInternalFormat()) { BVVTexture.InternalFormat.R8 -> Triple(1, UnsignedByteType(), true) BVVTexture.InternalFormat.R16 -> Triple(1, UnsignedShortType(), true) BVVTexture.InternalFormat.RGBA8 -> Triple(4, UnsignedByteType(), true) BVVTexture.InternalFormat.RGBA8UI -> Triple(4, UnsignedByteType(), false) BVVTexture.InternalFormat.R32F -> Triple(1, FloatType(), false) BVVTexture.InternalFormat.UNKNOWN -> TODO() else -> throw UnsupportedOperationException("Unknown internal format ${texture.texInternalFormat()}") } val repeat = when(texture.texWrap()) { BVVTexture.Wrap.CLAMP_TO_BORDER_ZERO -> RepeatMode.ClampToBorder BVVTexture.Wrap.CLAMP_TO_EDGE -> RepeatMode.ClampToEdge BVVTexture.Wrap.REPEAT -> RepeatMode.Repeat else -> throw UnsupportedOperationException("Unknown wrapping mode: ${texture.texWrap()}") } val material = node.material() if (texture is TextureCache) { if(currentlyBoundCache != null && material.textures["volumeCache"] == currentlyBoundCache && dimensionsMatch(texture, material.textures["volumeCache"])) { return 0 } // logger.warn("Binding and updating cache $texture") val gt = UpdatableTexture( Vector3i(texture.texWidth(), texture.texHeight(), texture.texDepth()), channels, type, null, repeat.all(), BorderColor.TransparentBlack, normalized, false, minFilter = Texture.FilteringMode.Linear, maxFilter = Texture.FilteringMode.Linear) material.textures["volumeCache"] = gt currentlyBoundCache = gt } else { val textureName = bindings[texture]?.uniformName logger.debug("lutName is $textureName for $texture") val db = { name: String -> /* if (!(node.material.textures[lut] != null && currentlyBoundLuts[lut] != null && node.material.textures[lut] == currentlyBoundLuts[lut])) { */ if (!(material.textures[name] != null && currentlyBoundTextures[name] != null && material.textures[name] == currentlyBoundTextures[name])) { val contents = when(texture) { is LookupTextureARGB -> null is VolumeManager.SimpleTexture2D -> texture.data else -> null } val filterLinear = when(texture) { is LookupTextureARGB -> Texture.FilteringMode.NearestNeighbour else -> Texture.FilteringMode.Linear } val gt = UpdatableTexture( Vector3i(texture.texWidth(), texture.texHeight(), texture.texDepth()), channels, type, contents, repeat.all(), BorderColor.TransparentBlack, normalized, false, minFilter = filterLinear, maxFilter = filterLinear) material.textures[name] = gt currentlyBoundTextures[name] = gt } } logger.debug("Adding deferred binding for $texture/$textureName") if(textureName == null) { deferredBindings[texture] = db return -1 } else { db.invoke(textureName) } } return 0 } /** * Runs all bindings that have been deferred to a later point. Necessary for some textures * to be compatible with the OpenGL binding model. */ fun runDeferredBindings() { val removals = ArrayList<BVVTexture>(deferredBindings.size) logger.debug("Running deferred bindings, got ${deferredBindings.size}") deferredBindings.forEach { (texture, func) -> val binding = bindings[texture] val samplerName = binding?.uniformName if(binding != null && samplerName != null) { func.invoke(samplerName) removals.add(texture) } else { if(node.readyToRender()) { logger.error("Binding for $texture not found, despite trying deferred binding. (binding=$binding/sampler=$samplerName)") } } } removals.forEach { deferredBindings.remove(it) } // val currentBindings = bindings.values.mapNotNull { it.uniformName } // logger.info("Current bindings are: ${currentBindings.joinToString(",")}") // val missingKeys = node.material.textures.filterKeys { it !in currentBindings } // missingKeys.forEach { (k, _) -> if(k.contains("_x_")) node.material.textures.remove(k) } } @Suppress("unused") fun clearCacheBindings() { val caches = bindings.filter { it is TextureCache } caches.map { bindings.remove(it.key) } currentlyBoundCache = null } fun clearBindings() { currentlyBoundTextures.clear() deferredBindings.clear() bindings.clear() cachedUpdates.clear() } /** * @param texture texture to bind * @param unit texture unit to bind to */ override fun bindTexture(texture: BVVTexture?, unit: Int) { logger.debug("Binding $texture to unit $unit") if(texture != null) { val binding = bindings[texture] if(binding != null) { bindings[texture] = BindingState(unit, binding.uniformName, binding.reallocate) } else { val prev = bindings.filter { it.value.binding == unit }.entries.firstOrNull()?.value val previousName = prev?.uniformName val previousReallocate = prev?.reallocate bindings[texture] = BindingState(unit, previousName) if(previousReallocate != null) { bindings[texture]?.reallocate = previousReallocate } } } } /** * @param id texture id to bind * @param numTexDimensions texture target: 1, 2, or 3 * @return id of previously bound texture */ override fun bindTextureId(id: Int, numTexDimensions: Int): Int { return 0 } /** * Maps a given [pbo] to a native memory-backed [ByteBuffer] and returns it. * The allocated buffers will be cached. */ override fun map(pbo: StagingBuffer): Buffer { logger.debug("Mapping $pbo... (${pboBackingStore.size} total)") return pboBackingStore.computeIfAbsent(pbo) { MemoryUtil.memAlloc(pbo.sizeInBytes) } } /** * Unmaps a buffer given by [pbo]. This function currently has no effect. */ override fun unmap(pbo: StagingBuffer) { logger.debug("Unmapping $pbo...") } /** * Marks a given [texture] for reallocation. */ override fun delete(texture: BVVTexture) { bindings[texture]?.reallocate = true } private data class SubImageUpdate(val xoffset: Int, val yoffset: Int, val zoffset: Int, val width: Int, val height: Int, val depth: Int, val contents: ByteBuffer, val reallocate: Boolean = false, val deallocate: Boolean = false) private var cachedUpdates = ConcurrentHashMap<BVVTexture, MutableList<SubImageUpdate>>() private data class UpdateParameters(val xoffset: Int, val yoffset: Int, val zoffset: Int, val width: Int, val height: Int, val depth: Int, val hash: Long) private val lastUpdates = ConcurrentHashMap<Texture3D, UpdateParameters>() /** * Runs all cached texture updates gathered from [texSubImage3D]. */ fun runTextureUpdates() { cachedUpdates.forEach { (t, updates) -> val texture = bindings[t] val name = texture?.uniformName if(texture != null && name != null) { val material = node.material() val gt = material.textures[name] as? UpdatableTexture ?: throw IllegalStateException("Texture for $name is null or not updateable") logger.debug("Running ${updates.size} texture updates for $texture") updates.forEach { update -> if (texture.reallocate) { val newDimensions = Vector3i(update.width, update.height, update.depth) val dimensionsChanged = Vector3i(newDimensions).sub(gt.dimensions).length() > 0.0001f if(dimensionsChanged) { logger.debug("Reallocating for size change ${gt.dimensions} -> $newDimensions") gt.clearUpdates() gt.dimensions = newDimensions gt.contents = null if (t is LookupTextureARGB) { gt.normalized = false } material.textures[name] = gt } val textureUpdate = TextureUpdate( TextureExtents(update.xoffset, update.yoffset, update.zoffset, update.width, update.height, update.depth), update.contents, deallocate = update.deallocate) gt.addUpdate(textureUpdate) texture.reallocate = false } else { val textureUpdate = TextureUpdate( TextureExtents(update.xoffset, update.yoffset, update.zoffset, update.width, update.height, update.depth), update.contents, deallocate = update.deallocate) gt.addUpdate(textureUpdate) } } updates.clear() } else { if(t is TextureCache) { logger.debug("Don't know how to update $t/$texture/$name") } else { if(node.readyToRender()) { logger.error("Don't know how to update $t/$texture/$name") } else { logger.debug("Don't know how to update $t/$texture/$name") } } } } } /** * Updates the memory allocated to [texture] with the contents of the staging buffer [pbo]. * This function updates only the part of the texture at the offsets [xoffset], [yoffset], [zoffset], with the given * [width], [height], and [depth]. In case the texture data does not start at offset 0, [pixels_buffer_offset] can be * set in addition. */ override fun texSubImage3D(pbo: StagingBuffer, texture: Texture3D, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, pixels_buffer_offset: Long) { logger.debug("Updating 3D texture via PBO from {}: dx={} dy={} dz={} w={} h={} d={} offset={}", texture, xoffset, yoffset, zoffset, width, height, depth, pixels_buffer_offset ) val tmpStorage = (map(pbo) as ByteBuffer).duplicate().order(ByteOrder.LITTLE_ENDIAN) tmpStorage.position(pixels_buffer_offset.toInt()) val tmp = MemoryUtil.memAlloc(width*height*depth*texture.texInternalFormat().bytesPerElement) tmpStorage.limit(tmpStorage.position() + width*height*depth*texture.texInternalFormat().bytesPerElement) tmp.put(tmpStorage) tmp.flip() val update = SubImageUpdate(xoffset, yoffset, zoffset, width, height, depth, tmp, deallocate = true) cachedUpdates.getOrPut(texture, { ArrayList(10) }).add(update) } /** * Updates the memory allocated to [texture] with the contents of [pixels]. * This function updates only the part of the texture at the offsets [xoffset], [yoffset], [zoffset], with the given * [width], [height], and [depth]. */ @OptIn(ExperimentalTime::class) override fun texSubImage3D(texture: Texture3D, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, pixels: Buffer) { if(pixels !is ByteBuffer) { return } // val (params, duration) = measureTimedValue { // UpdateParameters(xoffset, yoffset, zoffset, width, height, depth, XXHash.XXH3_64bits(pixels)) // } // if (lastUpdates[texture] == params) { // logger.debug("Updates already seen, skipping") // return // } logger.debug("Updating 3D texture via Texture3D, hash took from {}: dx={} dy={} dz={} w={} h={} d={}", texture, xoffset, yoffset, zoffset, width, height, depth ) val p = pixels.duplicate().order(ByteOrder.LITTLE_ENDIAN) // val allocationSize = width * height * depth * texture.texInternalFormat().bytesPerElement // val tmp = //MemoryUtil.memAlloc(allocationSize) // p.limit(p.position() + allocationSize) // MemoryUtil.memCopy(p, tmp) // lastUpdates[texture] = params val update = SubImageUpdate(xoffset, yoffset, zoffset, width, height, depth, p) cachedUpdates.getOrPut(texture, { ArrayList(10) }).add(update) } fun clearLUTs() { val luts = currentlyBoundTextures.filterKeys { it.startsWith("colorMap_") }.keys luts.forEach { currentlyBoundTextures.remove(it) } } }
src/main/kotlin/graphics/scenery/volumes/SceneryContext.kt
1101895130
package de.theunknownxy.mcdocs.gui.widget import de.theunknownxy.mcdocs.gui.base.Point import de.theunknownxy.mcdocs.gui.event.MouseButton public abstract class ScrollChild { public var mouse_pos: Point = Point(0f, 0f) public var width: Float = 0f set(v: Float) { $width = v onWidthChanged() } /** * Ask the child how tall it is. */ abstract fun getHeight(): Float /** * Draw the child. */ abstract fun draw() /** * Called when a mouse button is pressed. */ open fun onMouseClick(pos: Point, button: MouseButton) { } /** * Called when the width was changed. */ open fun onWidthChanged() { } }
src/main/kotlin/de/theunknownxy/mcdocs/gui/widget/ScrollChild.kt
4065645013
// 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.configurationStore import com.intellij.configurationStore.schemeManager.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.StateStorageOperation import com.intellij.openapi.diagnostic.DefaultLogger import com.intellij.openapi.options.ExternalizableScheme import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.testFramework.* import com.intellij.testFramework.rules.InMemoryFsRule import com.intellij.util.PathUtil import com.intellij.util.io.* import com.intellij.util.toByteArray import com.intellij.util.xmlb.annotations.Tag import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.jdom.Element import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.io.InputStream import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.util.function.Function /** * Functionality without stream provider covered, ICS has own test suite */ internal class SchemeManagerTest { companion object { internal const val FILE_SPEC = "REMOTE" @JvmField @ClassRule val projectRule = ProjectRule() } @Rule @JvmField val tempDirManager = TemporaryDirectory() @Rule @JvmField val fsRule = InMemoryFsRule() @Rule @JvmField val disposableRule = DisposableRule() private var localBaseDir: Path? = null private var remoteBaseDir: Path? = null private fun getTestDataPath(): Path = Paths.get(PlatformTestUtil.getCommunityPath(), "platform/platform-tests/testData/options") @Test fun loadSchemes() { doLoadSaveTest("options1", "1->first;2->second") } @Test fun loadSimpleSchemes() { doLoadSaveTest("options", "1->1") } @Test fun deleteScheme() { val manager = createAndLoad("options1") manager.removeScheme("first") manager.save() checkSchemes("2->second") } @Test fun renameScheme() { val manager = createAndLoad("options1") val scheme = manager.findSchemeByName("first") assertThat(scheme).isNotNull @Suppress("SpellCheckingInspection") scheme!!.name = "Grünwald" manager.save() @Suppress("SpellCheckingInspection") checkSchemes("2->second;Grünwald->Grünwald") } @Test fun testRenameScheme2() { val manager = createAndLoad("options1") val first = manager.findSchemeByName("first") assertThat(first).isNotNull assert(first != null) first!!.name = "2" val second = manager.findSchemeByName("second") assertThat(second).isNotNull assert(second != null) second!!.name = "1" manager.save() checkSchemes("1->1;2->2") } @Test fun testDeleteRenamedScheme() { val manager = createAndLoad("options1") val firstScheme = manager.findSchemeByName("first") assertThat(firstScheme).isNotNull assert(firstScheme != null) firstScheme!!.name = "first_renamed" manager.save() checkSchemes(remoteBaseDir!!.resolve("REMOTE"), "first_renamed->first_renamed;2->second", true) checkSchemes(localBaseDir!!, "", false) firstScheme.name = "first_renamed2" manager.removeScheme(firstScheme) manager.save() checkSchemes(remoteBaseDir!!.resolve("REMOTE"), "2->second", true) checkSchemes(localBaseDir!!, "", false) } @Test fun testDeleteAndCreateSchemeWithTheSameName() { val manager = createAndLoad("options1") val firstScheme = manager.findSchemeByName("first") assertThat(firstScheme).isNotNull manager.removeScheme(firstScheme!!) manager.addScheme(TestScheme("first")) manager.save() checkSchemes("2->second;first->first") } @Test fun testGenerateUniqueSchemeName() { val manager = createAndLoad("options1") val scheme = TestScheme("first") manager.addScheme(scheme, false) assertThat("first2").isEqualTo(scheme.name) } fun TestScheme.save(file: Path) { file.write(serialize(this)!!.toByteArray()) } @Test fun `different extensions - old, new`() { doDifferentExtensionTest(listOf("1.xml", "1.icls")) } @Test fun `different extensions - new, old`() { doDifferentExtensionTest(listOf("1.icls", "1.xml")) } private fun doDifferentExtensionTest(fileNames: List<String>) { val dir = tempDirManager.newPath() val scheme = TestScheme("local", "true") scheme.save(dir.resolve("1.icls")) TestScheme("local", "false").save(dir.resolve("1.xml")) class ATestSchemeProcessor : TestSchemeProcessor(), SchemeExtensionProvider { override val schemeExtension = ".icls" } // use provider to specify exact order of files (it is critical to test both variants - old, new or new, old) val schemeManager = SchemeManagerImpl(FILE_SPEC, ATestSchemeProcessor(), object : StreamProvider { override val isExclusive = true override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { getFile(fileSpec).write(content, 0, size) } override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean { getFile(fileSpec).inputStream().use(consumer) return true } override fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean): Boolean { for (name in fileNames) { dir.resolve(name).inputStream().use { processor(name, it, false) } } return true } override fun delete(fileSpec: String, roamingType: RoamingType): Boolean { getFile(fileSpec).delete() return true } private fun getFile(fileSpec: String) = dir.resolve(fileSpec.substring(FILE_SPEC.length + 1)) }, dir) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).containsOnly(scheme) assertThat(dir.resolve("1.icls")).isRegularFile() assertThat(dir.resolve("1.xml")).isRegularFile() scheme.data = "newTrue" schemeManager.save() assertThat(dir.resolve("1.icls")).isRegularFile() assertThat(dir.resolve("1.xml")).doesNotExist() } @Test fun setSchemes() { val dir = fsRule.fs.getPath("/test") val schemeManager = SchemeManagerImpl(FILE_SPEC, TestSchemeProcessor(), null, dir, schemeNameToFileName = MODERN_NAME_CONVERTER) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).isEmpty() @Suppress("SpellCheckingInspection") val schemeName = "Grünwald и русский" val scheme = TestScheme(schemeName) schemeManager.setSchemes(listOf(scheme)) val schemes = schemeManager.allSchemes assertThat(schemes).containsOnly(scheme) assertThat(dir.resolve("$schemeName.xml")).doesNotExist() scheme.data = "newTrue" schemeManager.save() assertThat(dir.resolve("$schemeName.xml")).isRegularFile() schemeManager.setSchemes(emptyList()) schemeManager.save() assertThat(dir).doesNotExist() } @Test fun `reload schemes`() { val dir = fsRule.fs.getPath("/test").createDirectories() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).isEmpty() val scheme = TestScheme("s1", "oldData") schemeManager.setSchemes(listOf(scheme)) assertThat(schemeManager.allSchemes).containsOnly(scheme) schemeManager.save() dir.resolve("s1.xml").write("""<scheme name="s1" data="newData" />""") schemeManager.reload() assertThat(schemeManager.allSchemes).containsOnly(TestScheme("s1", "newData")) } @Test fun `ignore dir named as file`() { val dir = fsRule.fs.getPath("/test").createDirectories() dir.resolve("foo.xml").createDirectories() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).isEmpty() } @Test fun `reload several schemes`() { doReloadTest(UpdateScheme::class.java) } @Test fun `reload - remove and add`() { doReloadTest(RemoveScheme::class.java) } private fun doReloadTest(kind: Class<out SchemeChangeEvent>) { val dir = fsRule.fs.getPath("/test").createDirectories() fun writeScheme(index: Int, value: String): TestScheme { val name = "s$index" val data = "data $value for scheme $index" dir.resolve("$name.xml").write("""<scheme name="$name" data="$data" />""") return TestScheme(name, data) } var s1 = writeScheme(1, "foo") var s2 = writeScheme(2, "foo") fun createVirtualFile(scheme: TestScheme): VirtualFile { val fileName = "${scheme.name}.xml" val file = dir.resolve(fileName) return LightVirtualFile(fileName, null, file.readText(), Charsets.UTF_8, Files.getLastModifiedTime(file).toMillis()) } val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).containsExactly(s1, s2) s1 = writeScheme(1, "bar") s2 = writeScheme(2, "bar") @Suppress("UNCHECKED_CAST") val schemeChangeApplicator = SchemeChangeApplicator(schemeManager as SchemeManagerImpl<Any, Any>) if (kind == UpdateScheme::class.java) { schemeChangeApplicator.reload(listOf(UpdateScheme(createVirtualFile(s1)), UpdateScheme(createVirtualFile(s2)))) } else { val sF2 = createVirtualFile(s2) val updateEventS1 = UpdateScheme(createVirtualFile(s1)) val updateEventS2 = UpdateScheme(sF2) val events = listOf(updateEventS1, RemoveScheme(sF2.name), updateEventS2) assertThat(sortSchemeChangeEvents(events)).containsExactly(updateEventS1, updateEventS2) val removeAllSchemes = RemoveAllSchemes() assertThat(sortSchemeChangeEvents(listOf(updateEventS1, RemoveScheme("foo"), updateEventS2, removeAllSchemes))).containsExactly(removeAllSchemes) assertThat(sortSchemeChangeEvents(listOf(updateEventS1, RemoveScheme("foo"), removeAllSchemes, updateEventS2))).containsExactly(removeAllSchemes, updateEventS2) assertThat(sortSchemeChangeEvents(listOf(removeAllSchemes, updateEventS2, RemoveScheme(sF2.name)))).containsExactly(removeAllSchemes, RemoveScheme(sF2.name)) schemeChangeApplicator.reload(events) } schemeManager.save() assertThat(schemeManager.allSchemes).containsExactly(s1, s2) } /** * This test shows how the interaction between [SchemeManagerImpl] and a []StreamProvider] with different * naming styles (e.g. a custom naming logic exposed by [SchemeManagerIprProvider.load]) can put [SchemeManagerImpl] * into a bad state where it deletes a scheme right after it tries to save it. * * This errors shows up as inconsistent outputs from the stream provider used by the scheme manager. An in-production * example of this is [com.intellij.execution.impl.RunManagerImpl], where two identical consecutive calls to * [RunManagerImpl.getState] can return different results. * * The steps to reproduce the error is inlined with the code below. */ @Test fun `scheme manager with dependencies using different scheme naming styles`() { /** * A simple schemes processor that names it's scheme keys with a custom suffix. */ val dir = tempDirManager.newPath() /** * 1. Create a [StreamProvider] that will later be used to load scheme elements with custom scheme names. * An instance of [SchemeManagerIprProvider] satisfies this criteria. */ val streamProvider = SchemeManagerIprProvider("scheme") /** * 2. Create a [SchemeProcessor] with custom naming scheme. See SchemesProcessorWithUniqueNaming in the test * as an example. */ class SchemeProcessorWithUniqueNaming : TestSchemeProcessor() { override fun getSchemeKey(scheme: TestScheme) = scheme.name + "someSuffix" } val schemeProcessor = SchemeProcessorWithUniqueNaming() /** * 3. Create a [SchemeManagerImpl] with the [StreamProvider] from #1 and [SchemeProcessor] from #2. We now have * a SchemeManager that can be manipulated to exhibit the error. */ val schemeManager = SchemeManagerImpl(FILE_SPEC, schemeProcessor, streamProvider, dir) /** * 4. Add a scheme and save it. The scheme manager will now have a scheme named in the style of our * [SchemeProcessorWithUniqueNaming] from #2. */ schemeManager.addScheme(TestScheme("first")) schemeManager.save() /** * 5. Obtain the scheme by writing its contents into an element, and then load the element with a different naming scheme. * This creates the scenario where schemeManager and streamProvider refers to the same scheme with different names. */ val element = Element("state") streamProvider.writeState(element) streamProvider.load(element) { elementToLoad -> elementToLoad.name + "someOtherSuffix" } /** * 6. [SchemeManagerImpl.reload] reloads it's schemes by deleting it's current set of schemes and reloading it. * Note that the file to delete here and what scheme manager thinks the scheme belongs to have different names. These * different names come from the different naming styles we defined earlier in the test. */ schemeManager.reload() /** * 7. By calling [SchemeManagerImpl.save], we delete the file our currently existing scheme uses. * Now [SchemeManagerImpl.save] should remove that deleted file from it's list of staged files to delete. * However, because the file names don't match, the file isn't removed. This means the file is STILL staged * for deletion. The saving process also corrects the scheme's file name if it's different from what [SchemeManager] * sees; this restores our scheme to use the same name given by our scheme processor from #2. */ schemeManager.save() val firstElement = Element("state") streamProvider.writeState(firstElement) /** * We have now successfully put our SchemeManagerImpl in the BAD STATE: * - [SchemeManagerImpl] has a file staged for deletion. * - [SchemeManagerImpl] ALSO has an existing scheme that is backed by the same file. * * This means [SchemeManagerImpl] will delete the file backing a scheme that's still in use. The deletion happens * on the next call to [SchemeManagerImpl.save]. */ /** * 8. Calling save will delete the file backing our scheme that's still in use. [streamProvider.writeState] will now * write an empty element, because the backing file was deleted. */ schemeManager.save() val secondElement = Element("state") streamProvider.writeState(secondElement) assertThat(firstElement.children.size).isEqualTo(secondElement.children.size) } @Test fun `save only if scheme differs from bundled`() { val dir = tempDirManager.newPath() var schemeManager = createSchemeManager(dir) val bundledPath = "/com/intellij/configurationStore/bundledSchemes/default.xml" schemeManager.loadBundledScheme(bundledPath, this, null) val customScheme = TestScheme("default") assertThat(schemeManager.allSchemes).containsOnly(customScheme) schemeManager.save() assertThat(dir).doesNotExist() schemeManager.save() schemeManager.setSchemes(listOf(customScheme)) assertThat(dir).doesNotExist() assertThat(schemeManager.allSchemes).containsOnly(customScheme) customScheme.data = "foo" schemeManager.save() assertThat(dir.resolve("default.xml")).isRegularFile() schemeManager = createSchemeManager(dir) schemeManager.loadBundledScheme(bundledPath, this, null) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).containsOnly(customScheme) } @Test fun `don't remove dir if no schemes but at least one non-hidden file exists`() { val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) val scheme = TestScheme("s1") schemeManager.setSchemes(listOf(scheme)) schemeManager.save() val schemeFile = dir.resolve("s1.xml") assertThat(schemeFile).isRegularFile() schemeManager.setSchemes(emptyList()) dir.resolve("empty").write(byteArrayOf()) schemeManager.save() assertThat(schemeFile).doesNotExist() assertThat(dir).isDirectory() } @Test fun `remove empty directory only if some file was deleted`() { val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() dir.createDirectories() schemeManager.save() assertThat(dir).isDirectory() schemeManager.addScheme(TestScheme("test")) schemeManager.save() assertThat(dir).isDirectory() schemeManager.setSchemes(emptyList()) schemeManager.save() assertThat(dir).doesNotExist() } @Test fun rename() { val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).isEmpty() val scheme = TestScheme("s1") schemeManager.setSchemes(listOf(scheme)) val schemes = schemeManager.allSchemes assertThat(schemes).containsOnly(scheme) assertThat(dir.resolve("s1.xml")).doesNotExist() scheme.data = "newTrue" schemeManager.save() assertThat(dir.resolve("s1.xml")).isRegularFile() scheme.name = "s2" schemeManager.save() assertThat(dir.resolve("s1.xml")).doesNotExist() assertThat(dir.resolve("s2.xml")).isRegularFile() } @Test fun `rename A to B and B to A`() { val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) val a = TestScheme("a", "a") val b = TestScheme("b", "b") schemeManager.setSchemes(listOf(a, b)) schemeManager.save() assertThat(dir.resolve("a.xml")).isRegularFile() assertThat(dir.resolve("b.xml")).isRegularFile() a.name = "b" b.name = "a" schemeManager.save() assertThat(dir.resolve("a.xml").readText()).isEqualTo("""<scheme name="a" data="b" />""") assertThat(dir.resolve("b.xml").readText()).isEqualTo("""<scheme name="b" data="a" />""") } @Test fun `VFS - rename A to B and B to A`() { val dir = tempDirManager.newPath(refreshVfs = true) val busDisposable = Disposer.newDisposable() try { val schemeManager = SchemeManagerImpl(FILE_SPEC, TestSchemeProcessor(), null, dir, fileChangeSubscriber = { schemeManager -> @Suppress("UNCHECKED_CAST") val schemeFileTracker = SchemeFileTracker(schemeManager as SchemeManagerImpl<Any, Any>, projectRule.project) ApplicationManager.getApplication().messageBus.connect(busDisposable).subscribe(VirtualFileManager.VFS_CHANGES, schemeFileTracker) }) val a = TestScheme("a", "a") val b = TestScheme("b", "b") schemeManager.setSchemes(listOf(a, b)) runInEdtAndWait { schemeManager.save() } assertThat(dir.resolve("a.xml")).isRegularFile() assertThat(dir.resolve("b.xml")).isRegularFile() a.name = "b" b.name = "a" runInEdtAndWait { schemeManager.save() } assertThat(dir.resolve("a.xml").readText()).isEqualTo("""<scheme name="a" data="b" />""") assertThat(dir.resolve("b.xml").readText()).isEqualTo("""<scheme name="b" data="a" />""") } finally { Disposer.dispose(busDisposable) } } @Test fun `VFS - vf resolver`() { val dir = tempDirManager.newPath() val requestedPaths = linkedSetOf<String>() val schemeManager = SchemeManagerImpl(FILE_SPEC, TestSchemeProcessor(), null, dir, fileChangeSubscriber = null, virtualFileResolver = object: VirtualFileResolver { override fun resolveVirtualFile(path: String, reasonOperation: StateStorageOperation): VirtualFile? { requestedPaths.add(PathUtil.getFileName(path)) return super.resolveVirtualFile(path, reasonOperation) } }) val a = TestScheme("a", "a") val b = TestScheme("b", "b") schemeManager.setSchemes(listOf(a, b)) runInEdtAndWait { schemeManager.save() } schemeManager.reload() assertThat(requestedPaths).containsExactly(dir.fileName.toString()) } @Test fun `path must not contains ROOT_CONFIG macro`() { assertThatThrownBy { SchemeManagerFactory.getInstance().create("\$ROOT_CONFIG$/foo", TestSchemeProcessor()) }.hasMessage("Path must not contains ROOT_CONFIG macro, corrected: foo") } @Test fun `path must be system-independent`() { DefaultLogger.disableStderrDumping(disposableRule.disposable); assertThatThrownBy { SchemeManagerFactory.getInstance().create("foo\\bar", TestSchemeProcessor())}.hasMessage("Path must be system-independent, use forward slash instead of backslash") } private fun createSchemeManager(dir: Path) = SchemeManagerImpl(FILE_SPEC, TestSchemeProcessor(), null, dir) private fun createAndLoad(testData: String): SchemeManagerImpl<TestScheme, TestScheme> { createTempFiles(testData) return createAndLoad() } private fun doLoadSaveTest(testData: String, expected: String, localExpected: String = "") { val schemesManager = createAndLoad(testData) schemesManager.save() checkSchemes(remoteBaseDir!!.resolve("REMOTE"), expected, true) checkSchemes(localBaseDir!!, localExpected, false) } private fun checkSchemes(expected: String) { checkSchemes(remoteBaseDir!!.resolve("REMOTE"), expected, true) checkSchemes(localBaseDir!!, "", false) } private fun createAndLoad(): SchemeManagerImpl<TestScheme, TestScheme> { val schemesManager = SchemeManagerImpl(FILE_SPEC, TestSchemeProcessor(), MockStreamProvider(remoteBaseDir!!), localBaseDir!!) schemesManager.loadSchemes() return schemesManager } private fun createTempFiles(testData: String) { val temp = tempDirManager.newPath() localBaseDir = temp.resolve("__local") remoteBaseDir = temp FileUtil.copyDir(getTestDataPath().resolve(testData).toFile(), temp.resolve("REMOTE").toFile()) } } private fun checkSchemes(baseDir: Path, expected: String, ignoreDeleted: Boolean) { val filesToScheme = StringUtil.split(expected, ";") val fileToSchemeMap = HashMap<String, String>() for (fileToScheme in filesToScheme) { val index = fileToScheme.indexOf("->") fileToSchemeMap.put(fileToScheme.substring(0, index), fileToScheme.substring(index + 2)) } baseDir.directoryStreamIfExists { for (file in it) { val fileName = FileUtil.getNameWithoutExtension(file.fileName.toString()) if ("--deleted" == fileName && ignoreDeleted) { assertThat(fileToSchemeMap).containsKey(fileName) } } } for (file in fileToSchemeMap.keys) { assertThat(baseDir.resolve("$file.xml")).isRegularFile() } baseDir.directoryStreamIfExists { for (file in it) { val scheme = JDOMUtil.load(file).deserialize(TestScheme::class.java) assertThat(fileToSchemeMap.get(FileUtil.getNameWithoutExtension(file.fileName.toString()))).isEqualTo(scheme.name) } } } @Tag("scheme") data class TestScheme(@field:com.intellij.util.xmlb.annotations.Attribute @field:kotlin.jvm.JvmField var name: String = "", @field:com.intellij.util.xmlb.annotations.Attribute var data: String? = null) : ExternalizableScheme, SerializableScheme { override fun getName() = name override fun setName(value: String) { name = value } override fun writeScheme() = serialize(this)!! } open class TestSchemeProcessor : LazySchemeProcessor<TestScheme, TestScheme>() { override fun createScheme(dataHolder: SchemeDataHolder<TestScheme>, name: String, attributeProvider: Function<in String, String?>, isBundled: Boolean): TestScheme { val scheme = dataHolder.read().deserialize(TestScheme::class.java) dataHolder.updateDigest(scheme) return scheme } }
platform/configuration-store-impl/testSrc/SchemeManagerTest.kt
3369117347
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.model.search.impl import com.intellij.lang.Language import com.intellij.lang.LanguageMatcher import com.intellij.model.search.LeafOccurrenceMapper import com.intellij.model.search.SearchContext import com.intellij.model.search.SearchWordQueryBuilder import com.intellij.model.search.TextOccurrence import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiSearchScopeUtil.restrictScopeTo import com.intellij.psi.search.PsiSearchScopeUtil.restrictScopeToFileLanguage import com.intellij.psi.search.SearchScope import com.intellij.util.Query import com.intellij.util.containers.toArray import java.util.* internal data class SearchWordQueryBuilderImpl( private val myProject: Project, private val myWord: String, private val myContainerName: String? = null, private val myCaseSensitive: Boolean = true, private val mySearchContexts: Set<SearchContext> = emptySet(), private val mySearchScope: SearchScope = GlobalSearchScope.EMPTY_SCOPE, private val myFileTypes: Collection<FileType>? = null, private val myFileLanguage: LanguageInfo = LanguageInfo.NoLanguage, private val myInjection: InjectionInfo = InjectionInfo.NoInjection ) : SearchWordQueryBuilder { override fun withContainerName(containerName: String?): SearchWordQueryBuilder = copy(myContainerName = containerName) override fun caseSensitive(caseSensitive: Boolean): SearchWordQueryBuilder = copy(myCaseSensitive = caseSensitive) override fun inScope(searchScope: SearchScope): SearchWordQueryBuilder = copy(mySearchScope = searchScope) override fun restrictFileTypes(fileType: FileType, vararg fileTypes: FileType): SearchWordQueryBuilder = copy( myFileTypes = listOf(fileType, *fileTypes) ) override fun inFilesWithLanguage(language: Language): SearchWordQueryBuilder = copy( myFileLanguage = LanguageInfo.InLanguage(LanguageMatcher.match(language)) ) override fun inFilesWithLanguageOfKind(language: Language): SearchWordQueryBuilder = copy( myFileLanguage = LanguageInfo.InLanguage(LanguageMatcher.matchWithDialects(language)) ) override fun inContexts(context: SearchContext, vararg otherContexts: SearchContext): SearchWordQueryBuilder = copy( mySearchContexts = EnumSet.of(context, *otherContexts) ) override fun inContexts(contexts: Set<SearchContext>): SearchWordQueryBuilder { require(contexts.isNotEmpty()) return copy(mySearchContexts = contexts) } override fun includeInjections(): SearchWordQueryBuilder = copy(myInjection = InjectionInfo.IncludeInjections) override fun inInjections(): SearchWordQueryBuilder = copy(myInjection = InjectionInfo.InInjection(LanguageInfo.NoLanguage)) override fun inInjections(language: Language): SearchWordQueryBuilder = copy( myInjection = InjectionInfo.InInjection(LanguageInfo.InLanguage(LanguageMatcher.match(language))) ) override fun inInjectionsOfKind(language: Language): SearchWordQueryBuilder = copy( myInjection = InjectionInfo.InInjection(LanguageInfo.InLanguage(LanguageMatcher.matchWithDialects(language))) ) private fun buildSearchScope(): SearchScope { var scope = mySearchScope if (myFileTypes != null) { scope = restrictScopeTo(scope, *myFileTypes.toArray(FileType.EMPTY_ARRAY)) } if (myFileLanguage is LanguageInfo.InLanguage) { scope = restrictScopeToFileLanguage(myProject, scope, myFileLanguage.matcher) } return scope } override fun <T> buildQuery(mapper: LeafOccurrenceMapper<T>): Query<out T> = SearchWordQuery( Parameters( myProject, myWord, myContainerName, myCaseSensitive, mySearchContexts, buildSearchScope(), myInjection ), mapper ) override fun buildOccurrenceQuery(): Query<out TextOccurrence> = buildQuery(TextOccurrenceWalker) override fun buildLeafOccurrenceQuery(): Query<out TextOccurrence> = buildQuery(IdLeafOccurenceMapper) internal data class Parameters( val project: Project, val word: String, val containerName: String?, val caseSensitive: Boolean, val searchContexts: Set<SearchContext>, val searchScope: SearchScope, val injection: InjectionInfo ) }
platform/indexing-impl/src/com/intellij/model/search/impl/SearchWordQueryBuilderImpl.kt
1471257901
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.index.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.project.Project import com.intellij.util.containers.asJBIterable import git4idea.conflicts.GitMergeHandler import git4idea.conflicts.acceptConflictSide import git4idea.conflicts.getConflictOperationLock import git4idea.conflicts.showMergeWindow import git4idea.i18n.GitBundle import git4idea.index.ui.* import git4idea.repo.GitConflict import org.jetbrains.annotations.Nls import java.util.function.Supplier class GitAcceptTheirsAction : GitAcceptConflictSideAction(true) class GitAcceptYoursAction : GitAcceptConflictSideAction(false) abstract class GitConflictAction(text: Supplier<@Nls String>) : GitFileStatusNodeAction(text, Presentation.NULL_STRING, null) { override fun update(e: AnActionEvent) { val project = e.project val nodes = e.getData(GitStageDataKeys.GIT_FILE_STATUS_NODES).asJBIterable() if (project == null || nodes.filter(this::matches).isEmpty) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true e.presentation.isEnabled = isEnabled(project, nodes.filterMap(GitFileStatusNode::createConflict).asSequence() as Sequence<GitConflict>) } override fun matches(statusNode: GitFileStatusNode): Boolean = statusNode.kind == NodeKind.CONFLICTED override fun perform(project: Project, nodes: List<GitFileStatusNode>) { perform(project, createMergeHandler(project), nodes.mapNotNull { it.createConflict() }) } protected open fun isEnabled(project: Project, conflicts: Sequence<GitConflict>): Boolean { return conflicts.any { conflict -> !getConflictOperationLock(project, conflict).isLocked } } protected abstract fun perform(project: Project, handler: GitMergeHandler, conflicts: List<GitConflict>) } abstract class GitAcceptConflictSideAction(private val takeTheirs: Boolean) : GitConflictAction(getActionText(takeTheirs)) { override fun perform(project: Project, handler: GitMergeHandler, conflicts: List<GitConflict>) { acceptConflictSide(project, createMergeHandler(project), conflicts, takeTheirs, project::isReversedRoot) } } private fun getActionText(takeTheirs: Boolean): Supplier<@Nls String> { return if (takeTheirs) GitBundle.messagePointer("conflicts.accept.theirs.action.text") else GitBundle.messagePointer("conflicts.accept.yours.action.text") } class GitMergeConflictAction : GitConflictAction(GitBundle.messagePointer("action.Git.Merge.text")) { override fun isEnabled(project: Project, conflicts: Sequence<GitConflict>): Boolean { val handler = createMergeHandler(project) return conflicts.any { conflict -> !getConflictOperationLock(project, conflict).isLocked && handler.canResolveConflict(conflict) } } override fun perform(project: Project, handler: GitMergeHandler, conflicts: List<GitConflict>) { showMergeWindow(project, handler, conflicts, project::isReversedRoot) } }
plugins/git4idea/src/git4idea/index/actions/GitConflictActions.kt
2840614414
// 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.grazie import com.intellij.grazie.grammar.GrammarChecker import com.intellij.grazie.grammar.Typo import com.intellij.grazie.grammar.check import com.intellij.grazie.ide.inspection.grammar.GrazieInspection import com.intellij.grazie.ide.language.LanguageGrammarChecking import com.intellij.grazie.jlanguage.Lang import com.intellij.grazie.utils.filterFor import com.intellij.psi.PsiElement import com.intellij.psi.PsiPlainText import com.intellij.spellchecker.inspections.SpellCheckingInspection import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.fixtures.BasePlatformTestCase abstract class GrazieTestBase : BasePlatformTestCase() { companion object { val inspectionTools by lazy { arrayOf(GrazieInspection(), SpellCheckingInspection()) } val enabledLanguages = setOf(Lang.AMERICAN_ENGLISH, Lang.GERMANY_GERMAN, Lang.RUSSIAN) val enabledRules = setOf("COMMA_WHICH") } override fun getBasePath() = "community/plugins/grazie/src/test/testData" override fun setUp() { super.setUp() myFixture.enableInspections(*inspectionTools) if (GrazieConfig.get().enabledLanguages != enabledLanguages) { GrazieConfig.update { state -> val checkingContext = state.checkingContext.copy( isCheckInStringLiteralsEnabled = true, isCheckInCommentsEnabled = true, isCheckInDocumentationEnabled = true ) state.copy( enabledLanguages = enabledLanguages, userEnabledRules = enabledRules, checkingContext = checkingContext ) } PlatformTestUtil.dispatchAllEventsInIdeEventQueue() } } protected open fun runHighlightTestForFile(file: String) { myFixture.configureByFile(file) myFixture.checkHighlighting(true, false, false) } fun plain(vararg texts: String) = plain(texts.toList()) fun plain(texts: List<String>): Collection<PsiElement> { return texts.flatMap { myFixture.configureByText("${it.hashCode()}.txt", it).filterFor<PsiPlainText>() } } fun check(tokens: Collection<PsiElement>): Set<Typo> { if (tokens.isEmpty()) return emptySet() val strategy = LanguageGrammarChecking.allForLanguage(tokens.first().language).first() return GrammarChecker.check(tokens, strategy) } }
plugins/grazie/src/test/kotlin/com/intellij/grazie/GrazieTestBase.kt
1179778461
package com.polidea.androidthings.driver.steppermotor.awaiter class DefaultAwaiter(val busyAwaitThresholdMillis: Long = 2, val busyAwaitThresholdNanos: Int = 0) : Awaiter { override fun await(millis: Long, nanos: Int) { if (millis == 0L && nanos == 0) { return } val exceedsThreshold = millis < busyAwaitThresholdMillis || millis >= busyAwaitThresholdMillis && nanos < busyAwaitThresholdNanos if (exceedsThreshold) { busyAwait(millis, nanos) } else { sleep(millis, nanos) } } private fun sleep(millis: Long, nanos: Int) = Thread.sleep(millis, nanos) private fun busyAwait(millis: Long, nanos: Int) { val awaitFinishNanos = System.nanoTime() + getNanos(millis, nanos) while (System.nanoTime() < awaitFinishNanos) { } } private fun getNanos(millis: Long, nanos: Int): Long = millis * NANOS_IN_MILLISECOND + nanos.toLong() companion object { private val NANOS_IN_MILLISECOND = 1000000L } }
steppermotor/src/main/java/com/polidea/androidthings/driver/steppermotor/awaiter/DefaultAwaiter.kt
918877152
/* * Copyright (C) 2019 Veli Tasalı * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.monora.uprotocol.client.android.util import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.content.SharedPreferences import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.preference.PreferenceManager import org.monora.uprotocol.client.android.R /** * Created by: veli * Date: 4/28/17 2:00 AM */ class NotificationBackend(val context: Context) { val manager = NotificationManagerCompat.from(context) val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) val notificationSettings: Int get() { val makeSound = if (preferences.getBoolean("notification_sound", true)) NotificationCompat.DEFAULT_SOUND else 0 val vibrate = if (preferences.getBoolean("notification_vibrate", true)) NotificationCompat.DEFAULT_VIBRATE else 0 val light = if (preferences.getBoolean("notification_light", false)) NotificationCompat.DEFAULT_LIGHTS else 0 return makeSound or vibrate or light } fun buildDynamicNotification(notificationId: Int, channelId: String): DynamicNotification { return DynamicNotification(context, manager, channelId, notificationId) } fun cancel(notificationId: Int) { manager.cancel(notificationId) } companion object { private const val TAG = "NotificationBackend" const val NOTIFICATION_CHANNEL_HIGH = "tsHighPriority" const val NOTIFICATION_CHANNEL_LOW = "tsLowPriority" const val CHANNEL_INSTRUCTIVE = "instructiveNotifications" const val EXTRA_NOTIFICATION_ID = "notificationId" } init { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channelHigh = NotificationChannel( NOTIFICATION_CHANNEL_HIGH, context.getString(R.string.high_priority_notifications), NotificationManager.IMPORTANCE_HIGH ) channelHigh.enableLights(preferences.getBoolean("notification_light", false)) channelHigh.enableVibration(preferences.getBoolean("notification_vibrate", false)) manager.createNotificationChannel(channelHigh) val channelLow = NotificationChannel( NOTIFICATION_CHANNEL_LOW, context.getString(R.string.low_priority_notifications), NotificationManager.IMPORTANCE_LOW ) manager.createNotificationChannel(channelLow) val channelInstructive = NotificationChannel( CHANNEL_INSTRUCTIVE, context.getString(R.string.notifications_instructive), NotificationManager.IMPORTANCE_MAX ) manager.createNotificationChannel(channelInstructive) } } }
app/src/main/java/org/monora/uprotocol/client/android/util/NotificationBackend.kt
2020927628
package szewek.fl.util import net.minecraft.nbt.NBTBase import net.minecraft.util.EnumFacing import net.minecraftforge.common.capabilities.Capability import net.minecraftforge.common.util.INBTSerializable @Suppress("UNCHECKED_CAST") object CapStorage { private val EMPTY = object : Capability.IStorage<Any> { override fun writeNBT(cap: Capability<Any>, t: Any, side: EnumFacing): NBTBase? { return null } override fun readNBT(cap: Capability<Any>, t: Any, side: EnumFacing, nbt: NBTBase) {} } private val NBT_STORAGE = object : Capability.IStorage<INBTSerializable<NBTBase>> { override fun writeNBT(cap: Capability<INBTSerializable<NBTBase>>, instance: INBTSerializable<NBTBase>, side: EnumFacing): NBTBase? { return instance.serializeNBT() } override fun readNBT(cap: Capability<INBTSerializable<NBTBase>>, instance: INBTSerializable<NBTBase>, side: EnumFacing, nbt: NBTBase) { instance.deserializeNBT(nbt) } } private val CUSTOM = object : Capability.IStorage<Any> { override fun writeNBT(capability: Capability<Any>, t: Any, side: EnumFacing): NBTBase? { return (t as? INBTSerializable<*>)?.serializeNBT() } override fun readNBT(capability: Capability<Any>, t: Any, side: EnumFacing, nbt: NBTBase) { if (t is INBTSerializable<*>) (t as INBTSerializable<NBTBase>).deserializeNBT(nbt) } } @JvmStatic fun <T> getEmpty(): Capability.IStorage<T> { return EMPTY as Capability.IStorage<T> } @JvmStatic fun <T : INBTSerializable<NBTBase>> getNBTStorage(): Capability.IStorage<T> { return NBT_STORAGE as Capability.IStorage<T> } @JvmStatic fun <T> getCustom(): Capability.IStorage<T> { return CUSTOM as Capability.IStorage<T> } }
src/main/java/szewek/fl/util/CapStorage.kt
4084043105
/* Copyright (c) 2021 DeflatedPickle under the MIT license */ package com.deflatedpickle.quiver.packexport.event import com.deflatedpickle.haruhi.api.event.AbstractEvent import java.io.File /** * An event that is run when a file has been exported */ object EventExportFile : AbstractEvent<File>()
packexport/src/main/kotlin/com/deflatedpickle/quiver/packexport/event/EventExportFile.kt
1635378197
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:JvmMultifileClass @file:JvmName("JobKt") @file:Suppress("DEPRECATION_ERROR", "RedundantUnitReturnType") package kotlinx.coroutines import kotlinx.coroutines.selects.* import kotlin.coroutines.* import kotlin.jvm.* // --------------- core job interfaces --------------- /** * A background job. Conceptually, a job is a cancellable thing with a life-cycle that * culminates in its completion. * * Jobs can be arranged into parent-child hierarchies where cancellation * of a parent leads to immediate cancellation of all its [children] recursively. * Failure of a child with an exception other than [CancellationException] immediately cancels its parent and, * consequently, all its other children. This behavior can be customized using [SupervisorJob]. * * The most basic instances of `Job` interface are created like this: * * * **Coroutine job** is created with [launch][CoroutineScope.launch] coroutine builder. * It runs a specified block of code and completes on completion of this block. * * **[CompletableJob]** is created with a `Job()` factory function. * It is completed by calling [CompletableJob.complete]. * * Conceptually, an execution of a job does not produce a result value. Jobs are launched solely for their * side-effects. See [Deferred] interface for a job that produces a result. * * ### Job states * * A job has the following states: * * | **State** | [isActive] | [isCompleted] | [isCancelled] | * | -------------------------------- | ---------- | ------------- | ------------- | * | _New_ (optional initial state) | `false` | `false` | `false` | * | _Active_ (default initial state) | `true` | `false` | `false` | * | _Completing_ (transient state) | `true` | `false` | `false` | * | _Cancelling_ (transient state) | `false` | `false` | `true` | * | _Cancelled_ (final state) | `false` | `true` | `true` | * | _Completed_ (final state) | `false` | `true` | `false` | * * Usually, a job is created in the _active_ state (it is created and started). However, coroutine builders * that provide an optional `start` parameter create a coroutine in the _new_ state when this parameter is set to * [CoroutineStart.LAZY]. Such a job can be made _active_ by invoking [start] or [join]. * * A job is _active_ while the coroutine is working or until [CompletableJob] is completed, * or until it fails or cancelled. * * Failure of an _active_ job with an exception makes it _cancelling_. * A job can be cancelled at any time with [cancel] function that forces it to transition to * the _cancelling_ state immediately. The job becomes _cancelled_ when it finishes executing its work and * all its children complete. * * Completion of an _active_ coroutine's body or a call to [CompletableJob.complete] transitions the job to * the _completing_ state. It waits in the _completing_ state for all its children to complete before * transitioning to the _completed_ state. * Note that _completing_ state is purely internal to the job. For an outside observer a _completing_ job is still * active, while internally it is waiting for its children. * * ``` * wait children * +-----+ start +--------+ complete +-------------+ finish +-----------+ * | New | -----> | Active | ---------> | Completing | -------> | Completed | * +-----+ +--------+ +-------------+ +-----------+ * | cancel / fail | * | +----------------+ * | | * V V * +------------+ finish +-----------+ * | Cancelling | --------------------------------> | Cancelled | * +------------+ +-----------+ * ``` * * A `Job` instance in the * [coroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/coroutine-context.html) * represents the coroutine itself. * * ### Cancellation cause * * A coroutine job is said to _complete exceptionally_ when its body throws an exception; * a [CompletableJob] is completed exceptionally by calling [CompletableJob.completeExceptionally]. * An exceptionally completed job is cancelled and the corresponding exception becomes the _cancellation cause_ of the job. * * Normal cancellation of a job is distinguished from its failure by the type of this exception that caused its cancellation. * A coroutine that threw [CancellationException] is considered to be _cancelled normally_. * If a cancellation cause is a different exception type, then the job is considered to have _failed_. * When a job has _failed_, then its parent gets cancelled with the exception of the same type, * thus ensuring transparency in delegating parts of the job to its children. * * Note, that [cancel] function on a job only accepts [CancellationException] as a cancellation cause, thus * calling [cancel] always results in a normal cancellation of a job, which does not lead to cancellation * of its parent. This way, a parent can [cancel] its own children (cancelling all their children recursively, too) * without cancelling itself. * * ### Concurrency and synchronization * * All functions on this interface and on all interfaces derived from it are **thread-safe** and can * be safely invoked from concurrent coroutines without external synchronization. * * ### Not stable for inheritance * * **`Job` interface and all its derived interfaces are not stable for inheritance in 3rd party libraries**, * as new methods might be added to this interface in the future, but is stable for use. */ public interface Job : CoroutineContext.Element { /** * Key for [Job] instance in the coroutine context. */ public companion object Key : CoroutineContext.Key<Job> // ------------ state query ------------ /** * Returns `true` when this job is active -- it was already started and has not completed nor was cancelled yet. * The job that is waiting for its [children] to complete is still considered to be active if it * was not cancelled nor failed. * * See [Job] documentation for more details on job states. */ public val isActive: Boolean /** * Returns `true` when this job has completed for any reason. A job that was cancelled or failed * and has finished its execution is also considered complete. Job becomes complete only after * all its [children] complete. * * See [Job] documentation for more details on job states. */ public val isCompleted: Boolean /** * Returns `true` if this job was cancelled for any reason, either by explicit invocation of [cancel] or * because it had failed or its child or parent was cancelled. * In the general case, it does not imply that the * job has already [completed][isCompleted], because it may still be finishing whatever it was doing and * waiting for its [children] to complete. * * See [Job] documentation for more details on cancellation and failures. */ public val isCancelled: Boolean /** * Returns [CancellationException] that signals the completion of this job. This function is * used by [cancellable][suspendCancellableCoroutine] suspending functions. They throw exception * returned by this function when they suspend in the context of this job and this job becomes _complete_. * * This function returns the original [cancel] cause of this job if that `cause` was an instance of * [CancellationException]. Otherwise (if this job was cancelled with a cause of a different type, or * was cancelled without a cause, or had completed normally), an instance of [CancellationException] is * returned. The [CancellationException.cause] of the resulting [CancellationException] references * the original cancellation cause that was passed to [cancel] function. * * This function throws [IllegalStateException] when invoked on a job that is still active. * * @suppress **This an internal API and should not be used from general code.** */ @InternalCoroutinesApi public fun getCancellationException(): CancellationException // ------------ state update ------------ /** * Starts coroutine related to this job (if any) if it was not started yet. * The result is `true` if this invocation actually started coroutine or `false` * if it was already started or completed. */ public fun start(): Boolean /** * Cancels this job with an optional cancellation [cause]. * A cause can be used to specify an error message or to provide other details on * the cancellation reason for debugging purposes. * See [Job] documentation for full explanation of cancellation machinery. */ public fun cancel(cause: CancellationException? = null) /** * @suppress This method implements old version of JVM ABI. Use [cancel]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun cancel(): Unit = cancel(null) /** * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [cancel]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun cancel(cause: Throwable? = null): Boolean // ------------ parent-child ------------ /** * Returns a sequence of this job's children. * * A job becomes a child of this job when it is constructed with this job in its * [CoroutineContext] or using an explicit `parent` parameter. * * A parent-child relation has the following effect: * * * Cancellation of parent with [cancel] or its exceptional completion (failure) * immediately cancels all its children. * * Parent cannot complete until all its children are complete. Parent waits for all its children to * complete in _completing_ or _cancelling_ state. * * Uncaught exception in a child, by default, cancels parent. This applies even to * children created with [async][CoroutineScope.async] and other future-like * coroutine builders, even though their exceptions are caught and are encapsulated in their result. * This default behavior can be overridden with [SupervisorJob]. */ public val children: Sequence<Job> /** * Attaches child job so that this job becomes its parent and * returns a handle that should be used to detach it. * * A parent-child relation has the following effect: * * Cancellation of parent with [cancel] or its exceptional completion (failure) * immediately cancels all its children. * * Parent cannot complete until all its children are complete. Parent waits for all its children to * complete in _completing_ or _cancelling_ states. * * **A child must store the resulting [ChildHandle] and [dispose][DisposableHandle.dispose] the attachment * to its parent on its own completion.** * * Coroutine builders and job factory functions that accept `parent` [CoroutineContext] parameter * lookup a [Job] instance in the parent context and use this function to attach themselves as a child. * They also store a reference to the resulting [ChildHandle] and dispose a handle when they complete. * * @suppress This is an internal API. This method is too error prone for public API. */ // ChildJob and ChildHandle are made internal on purpose to further deter 3rd-party impl of Job @InternalCoroutinesApi public fun attachChild(child: ChildJob): ChildHandle // ------------ state waiting ------------ /** * Suspends the coroutine until this job is complete. This invocation resumes normally (without exception) * when the job is complete for any reason and the [Job] of the invoking coroutine is still [active][isActive]. * This function also [starts][Job.start] the corresponding coroutine if the [Job] was still in _new_ state. * * Note that the job becomes complete only when all its children are complete. * * This suspending function is cancellable and **always** checks for a cancellation of the invoking coroutine's Job. * If the [Job] of the invoking coroutine is cancelled or completed when this * suspending function is invoked or while it is suspended, this function * throws [CancellationException]. * * In particular, it means that a parent coroutine invoking `join` on a child coroutine throws * [CancellationException] if the child had failed, since a failure of a child coroutine cancels parent by default, * unless the child was launched from within [supervisorScope]. * * This function can be used in [select] invocation with [onJoin] clause. * Use [isCompleted] to check for a completion of this job without waiting. * * There is [cancelAndJoin] function that combines an invocation of [cancel] and `join`. */ public suspend fun join() /** * Clause for [select] expression of [join] suspending function that selects when the job is complete. * This clause never fails, even if the job completes exceptionally. */ public val onJoin: SelectClause0 // ------------ low-level state-notification ------------ /** * Registers handler that is **synchronously** invoked once on completion of this job. * When the job is already complete, then the handler is immediately invoked * with the job's exception or cancellation cause or `null`. Otherwise, the handler will be invoked once when this * job is complete. * * The meaning of `cause` that is passed to the handler: * * Cause is `null` when the job has completed normally. * * Cause is an instance of [CancellationException] when the job was cancelled _normally_. * **It should not be treated as an error**. In particular, it should not be reported to error logs. * * Otherwise, the job had _failed_. * * The resulting [DisposableHandle] can be used to [dispose][DisposableHandle.dispose] the * registration of this handler and release its memory if its invocation is no longer needed. * There is no need to dispose the handler after completion of this job. The references to * all the handlers are released when this job completes. * * Installed [handler] should not throw any exceptions. If it does, they will get caught, * wrapped into [CompletionHandlerException], and rethrown, potentially causing crash of unrelated code. * * **Note**: Implementation of `CompletionHandler` must be fast, non-blocking, and thread-safe. * This handler can be invoked concurrently with the surrounding code. * There is no guarantee on the execution context in which the [handler] is invoked. */ public fun invokeOnCompletion(handler: CompletionHandler): DisposableHandle /** * Registers handler that is **synchronously** invoked once on cancellation or completion of this job. * when the job was already cancelled and is completed its execution, then the handler is immediately invoked * with the job's cancellation cause or `null` unless [invokeImmediately] is set to false. * Otherwise, handler will be invoked once when this job is cancelled or is complete. * * The meaning of `cause` that is passed to the handler: * * Cause is `null` when the job has completed normally. * * Cause is an instance of [CancellationException] when the job was cancelled _normally_. * **It should not be treated as an error**. In particular, it should not be reported to error logs. * * Otherwise, the job had _failed_. * * Invocation of this handler on a transition to a _cancelling_ state * is controlled by [onCancelling] boolean parameter. * The handler is invoked when the job becomes _cancelling_ if [onCancelling] parameter is set to `true`. * * The resulting [DisposableHandle] can be used to [dispose][DisposableHandle.dispose] the * registration of this handler and release its memory if its invocation is no longer needed. * There is no need to dispose the handler after completion of this job. The references to * all the handlers are released when this job completes. * * Installed [handler] should not throw any exceptions. If it does, they will get caught, * wrapped into [CompletionHandlerException], and rethrown, potentially causing crash of unrelated code. * * **Note**: This function is a part of internal machinery that supports parent-child hierarchies * and allows for implementation of suspending functions that wait on the Job's state. * This function should not be used in general application code. * Implementation of `CompletionHandler` must be fast, non-blocking, and thread-safe. * This handler can be invoked concurrently with the surrounding code. * There is no guarantee on the execution context in which the [handler] is invoked. * * @param onCancelling when `true`, then the [handler] is invoked as soon as this job transitions to _cancelling_ state; * when `false` then the [handler] is invoked only when it transitions to _completed_ state. * @param invokeImmediately when `true` and this job is already in the desired state (depending on [onCancelling]), * then the [handler] is immediately and synchronously invoked and no-op [DisposableHandle] is returned; * when `false` then no-op [DisposableHandle] is returned, but the [handler] is not invoked. * @param handler the handler. * * @suppress **This an internal API and should not be used from general code.** */ @InternalCoroutinesApi public fun invokeOnCompletion( onCancelling: Boolean = false, invokeImmediately: Boolean = true, handler: CompletionHandler): DisposableHandle // ------------ unstable internal API ------------ /** * @suppress **Error**: Operator '+' on two Job objects is meaningless. * Job is a coroutine context element and `+` is a set-sum operator for coroutine contexts. * The job to the right of `+` just replaces the job the left of `+`. */ @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated(message = "Operator '+' on two Job objects is meaningless. " + "Job is a coroutine context element and `+` is a set-sum operator for coroutine contexts. " + "The job to the right of `+` just replaces the job the left of `+`.", level = DeprecationLevel.ERROR) public operator fun plus(other: Job): Job = other } /** * Creates a job object in an active state. * A failure of any child of this job immediately causes this job to fail, too, and cancels the rest of its children. * * To handle children failure independently of each other use [SupervisorJob]. * * If [parent] job is specified, then this job becomes a child job of its parent and * is cancelled when its parent fails or is cancelled. All this job's children are cancelled in this case, too. * The invocation of [cancel][Job.cancel] with exception (other than [CancellationException]) on this job also cancels parent. * * Conceptually, the resulting job works in the same way as the job created by the `launch { body }` invocation * (see [launch]), but without any code in the body. It is active until cancelled or completed. Invocation of * [CompletableJob.complete] or [CompletableJob.completeExceptionally] corresponds to the successful or * failed completion of the body of the coroutine. * * @param parent an optional parent job. */ @Suppress("FunctionName") public fun Job(parent: Job? = null): CompletableJob = JobImpl(parent) /** @suppress Binary compatibility only */ @Suppress("FunctionName") @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") @JvmName("Job") public fun Job0(parent: Job? = null): Job = Job(parent) /** * A handle to an allocated object that can be disposed to make it eligible for garbage collection. */ public fun interface DisposableHandle { /** * Disposes the corresponding object, making it eligible for garbage collection. * Repeated invocation of this function has no effect. */ public fun dispose() } // -------------------- Parent-child communication -------------------- /** * A reference that parent receives from its child so that it can report its cancellation. * * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi @Deprecated(level = DeprecationLevel.ERROR, message = "This is internal API and may be removed in the future releases") public interface ChildJob : Job { /** * Parent is cancelling its child by invoking this method. * Child finds the cancellation cause using [ParentJob.getChildJobCancellationCause]. * This method does nothing is the child is already being cancelled. * * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi public fun parentCancelled(parentJob: ParentJob) } /** * A reference that child receives from its parent when it is being cancelled by the parent. * * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi @Deprecated(level = DeprecationLevel.ERROR, message = "This is internal API and may be removed in the future releases") public interface ParentJob : Job { /** * Child job is using this method to learn its cancellation cause when the parent cancels it with [ChildJob.parentCancelled]. * This method is invoked only if the child was not already being cancelled. * * Note that [CancellationException] is the method's return type: if child is cancelled by its parent, * then the original exception is **already** handled by either the parent or the original source of failure. * * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi public fun getChildJobCancellationCause(): CancellationException } /** * A handle that child keep onto its parent so that it is able to report its cancellation. * * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi @Deprecated(level = DeprecationLevel.ERROR, message = "This is internal API and may be removed in the future releases") public interface ChildHandle : DisposableHandle { /** * Returns the parent of the current parent-child relationship. * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi public val parent: Job? /** * Child is cancelling its parent by invoking this method. * This method is invoked by the child twice. The first time child report its root cause as soon as possible, * so that all its siblings and the parent can start cancelling their work asap. The second time * child invokes this method when it had aggregated and determined its final cancellation cause. * * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi public fun childCancelled(cause: Throwable): Boolean } // -------------------- Job extensions -------------------- /** * Disposes a specified [handle] when this job is complete. * * This is a shortcut for the following code with slightly more efficient implementation (one fewer object created). * ``` * invokeOnCompletion { handle.dispose() } * ``` */ internal fun Job.disposeOnCompletion(handle: DisposableHandle): DisposableHandle = invokeOnCompletion(handler = DisposeOnCompletion(handle).asHandler) /** * Cancels the job and suspends the invoking coroutine until the cancelled job is complete. * * This suspending function is cancellable and **always** checks for a cancellation of the invoking coroutine's Job. * If the [Job] of the invoking coroutine is cancelled or completed when this * suspending function is invoked or while it is suspended, this function * throws [CancellationException]. * * In particular, it means that a parent coroutine invoking `cancelAndJoin` on a child coroutine throws * [CancellationException] if the child had failed, since a failure of a child coroutine cancels parent by default, * unless the child was launched from within [supervisorScope]. * * This is a shortcut for the invocation of [cancel][Job.cancel] followed by [join][Job.join]. */ public suspend fun Job.cancelAndJoin() { cancel() return join() } /** * Cancels all [children][Job.children] jobs of this coroutine using [Job.cancel] for all of them * with an optional cancellation [cause]. * Unlike [Job.cancel] on this job as a whole, the state of this job itself is not affected. */ public fun Job.cancelChildren(cause: CancellationException? = null) { children.forEach { it.cancel(cause) } } /** * @suppress This method implements old version of JVM ABI. Use [cancel]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun Job.cancelChildren(): Unit = cancelChildren(null) /** * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [Job.cancelChildren]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun Job.cancelChildren(cause: Throwable? = null) { children.forEach { (it as? JobSupport)?.cancelInternal(cause.orCancellation(this)) } } // -------------------- CoroutineContext extensions -------------------- /** * Returns `true` when the [Job] of the coroutine in this context is still active * (has not completed and was not cancelled yet). * * Check this property in long-running computation loops to support cancellation * when [CoroutineScope.isActive] is not available: * * ``` * while (coroutineContext.isActive) { * // do some computation * } * ``` * * The `coroutineContext.isActive` expression is a shortcut for `coroutineContext[Job]?.isActive == true`. * See [Job.isActive]. */ public val CoroutineContext.isActive: Boolean get() = this[Job]?.isActive == true /** * Cancels [Job] of this context with an optional cancellation cause. * See [Job.cancel] for details. */ public fun CoroutineContext.cancel(cause: CancellationException? = null) { this[Job]?.cancel(cause) } /** * @suppress This method implements old version of JVM ABI. Use [CoroutineContext.cancel]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun CoroutineContext.cancel(): Unit = cancel(null) /** * Ensures that current job is [active][Job.isActive]. * If the job is no longer active, throws [CancellationException]. * If the job was cancelled, thrown exception contains the original cancellation cause. * * This method is a drop-in replacement for the following code, but with more precise exception: * ``` * if (!job.isActive) { * throw CancellationException() * } * ``` */ public fun Job.ensureActive(): Unit { if (!isActive) throw getCancellationException() } /** * Ensures that job in the current context is [active][Job.isActive]. * * If the job is no longer active, throws [CancellationException]. * If the job was cancelled, thrown exception contains the original cancellation cause. * This function does not do anything if there is no [Job] in the context, since such a coroutine cannot be cancelled. * * This method is a drop-in replacement for the following code, but with more precise exception: * ``` * if (!isActive) { * throw CancellationException() * } * ``` */ public fun CoroutineContext.ensureActive() { get(Job)?.ensureActive() } /** * Cancels current job, including all its children with a specified diagnostic error [message]. * A [cause] can be specified to provide additional details on a cancellation reason for debugging purposes. */ public fun Job.cancel(message: String, cause: Throwable? = null): Unit = cancel(CancellationException(message, cause)) /** * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [CoroutineContext.cancel]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun CoroutineContext.cancel(cause: Throwable? = null): Boolean { val job = this[Job] as? JobSupport ?: return false job.cancelInternal(cause.orCancellation(job)) return true } /** * Cancels all children of the [Job] in this context, without touching the state of this job itself * with an optional cancellation cause. See [Job.cancel]. * It does not do anything if there is no job in the context or it has no children. */ public fun CoroutineContext.cancelChildren(cause: CancellationException? = null) { this[Job]?.children?.forEach { it.cancel(cause) } } /** * @suppress This method implements old version of JVM ABI. Use [CoroutineContext.cancelChildren]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun CoroutineContext.cancelChildren(): Unit = cancelChildren(null) /** * Retrieves the current [Job] instance from the given [CoroutineContext] or * throws [IllegalStateException] if no job is present in the context. * * This method is a short-cut for `coroutineContext[Job]!!` and should be used only when it is known in advance that * the context does have instance of the job in it. */ public val CoroutineContext.job: Job get() = get(Job) ?: error("Current context doesn't contain Job in it: $this") /** * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [CoroutineContext.cancelChildren]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun CoroutineContext.cancelChildren(cause: Throwable? = null) { val job = this[Job] ?: return job.children.forEach { (it as? JobSupport)?.cancelInternal(cause.orCancellation(job)) } } private fun Throwable?.orCancellation(job: Job): Throwable = this ?: JobCancellationException("Job was cancelled", null, job) /** * No-op implementation of [DisposableHandle]. * @suppress **This an internal API and should not be used from general code.** */ @InternalCoroutinesApi public object NonDisposableHandle : DisposableHandle, ChildHandle { override val parent: Job? get() = null /** * Does not do anything. * @suppress */ override fun dispose() {} /** * Returns `false`. * @suppress */ override fun childCancelled(cause: Throwable): Boolean = false /** * Returns "NonDisposableHandle" string. * @suppress */ override fun toString(): String = "NonDisposableHandle" }
kotlinx-coroutines-core/common/src/Job.kt
2447212605
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.internal @Suppress("ACTUAL_WITHOUT_EXPECT") internal actual typealias LocalAtomicInt = java.util.concurrent.atomic.AtomicInteger
kotlinx-coroutines-core/jvm/src/internal/LocalAtomics.kt
1976547748
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui import com.intellij.openapi.project.Project import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.Action class GHLoadingErrorHandlerImpl(private val project: Project, private val account: GithubAccount, private val resetRunnable: () -> Unit) : GHLoadingErrorHandler { override fun getActionForError(error: Throwable): Action? { if (error is GithubAuthenticationException) { return ReLoginAction() } else { return RetryAction() } } private inner class ReLoginAction : AbstractAction("Re-Login") { override fun actionPerformed(e: ActionEvent?) { if (GithubAuthenticationManager.getInstance().requestReLogin(account, project)) resetRunnable() } } private inner class RetryAction : AbstractAction("Retry") { override fun actionPerformed(e: ActionEvent?) { resetRunnable() } } }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHLoadingErrorHandlerImpl.kt
2283828899
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.intellij.codeInsight.hints import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager import com.intellij.codeInsight.hints.HintInfo.MethodInfo import com.intellij.codeInsight.hints.settings.InlayHintsConfigurable import com.intellij.codeInsight.hints.settings.Diff import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.injected.editor.EditorWindow import com.intellij.lang.Language import com.intellij.notification.Notification import com.intellij.notification.NotificationListener import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.util.PsiTreeUtil class ShowSettingsWithAddedPattern : AnAction() { init { templatePresentation.description = CodeInsightBundle.message("inlay.hints.show.settings.description") templatePresentation.text = CodeInsightBundle.message("inlay.hints.show.settings", "_") } override fun update(e: AnActionEvent) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val offset = editor.caretModel.offset val info = getHintInfoFromProvider(offset, file, editor) if (info is MethodInfo) { e.presentation.setText(CodeInsightBundle.message("inlay.hints.show.settings", info.getMethodName()), false) } else { e.presentation.isVisible = false } } override fun actionPerformed(e: AnActionEvent) { showParameterHintsDialog(e) { when (it) { is HintInfo.OptionInfo -> null is MethodInfo -> it.toPattern() }} } } class ShowParameterHintsSettings : AnAction() { override fun actionPerformed(e: AnActionEvent) { showParameterHintsDialog(e) {null} } } fun showParameterHintsDialog(e: AnActionEvent, getPattern: (HintInfo) -> String?) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val fileLanguage = file.language InlayParameterHintsExtension.forLanguage(fileLanguage) ?: return val offset = editor.caretModel.offset val info = getHintInfoFromProvider(offset, file, editor) ?: return val selectedLanguage = (info as? MethodInfo)?.language ?: fileLanguage when (val pattern = getPattern(info)) { null -> InlayHintsConfigurable.showSettingsDialogForLanguage(file.project, fileLanguage) else -> BlackListDialog(selectedLanguage, pattern).show() } } class BlacklistCurrentMethodIntention : IntentionAction, LowPriorityAction { companion object { private val presentableText = CodeInsightBundle.message("inlay.hints.blacklist.method") private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name") } override fun getText(): String = presentableText override fun getFamilyName(): String = presentableFamilyName override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { val language = file.language val hintsProvider = InlayParameterHintsExtension.forLanguage(language) ?: return false return hintsProvider.isBlackListSupported && hasEditorParameterHintAtOffset(editor, file) && isMethodHintAtOffset(editor, file) } private fun isMethodHintAtOffset(editor: Editor, file: PsiFile): Boolean { val offset = editor.caretModel.offset return getHintInfoFromProvider(offset, file, editor) is MethodInfo } override fun invoke(project: Project, editor: Editor, file: PsiFile) { val offset = editor.caretModel.offset val info = getHintInfoFromProvider(offset, file, editor) as? MethodInfo ?: return val language = info.language ?: file.language ParameterNameHintsSettings.getInstance().addIgnorePattern(getLanguageForSettingKey(language), info.toPattern()) refreshAllOpenEditors() showHint(project, language, info) } private fun showHint(project: Project, language: Language, info: MethodInfo) { val methodName = info.getMethodName() val listener = NotificationListener { notification, event -> when (event.description) { "settings" -> showSettings(language) "undo" -> undo(language, info) } notification.expire() } val notification = Notification("Parameter Name Hints", "Method \"$methodName\" added to blacklist", "<html><a href='settings'>Show Parameter Hints Settings</a> or <a href='undo'>Undo</a></html>", NotificationType.INFORMATION, listener) notification.notify(project) } private fun showSettings(language: Language) { BlackListDialog(language).show() } private fun undo(language: Language, info: MethodInfo) { val settings = ParameterNameHintsSettings.getInstance() val languageForSettings = getLanguageForSettingKey(language) val diff = settings.getBlackListDiff(languageForSettings) val updated = diff.added.toMutableSet().apply { remove(info.toPattern()) } settings.setBlackListDiff(languageForSettings, Diff(updated, diff.removed)) refreshAllOpenEditors() } override fun startInWriteAction(): Boolean = false } class DisableCustomHintsOption: IntentionAction, LowPriorityAction { companion object { private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name") } private var lastOptionName = "" override fun getText(): String = getIntentionText() private fun getIntentionText(): String { if (lastOptionName.startsWith("show", ignoreCase = true)) { return "Do not ${lastOptionName.toLowerCase()}" } return CodeInsightBundle.message("inlay.hints.disable.custom.option", lastOptionName) } override fun getFamilyName(): String = presentableFamilyName override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { InlayParameterHintsExtension.forLanguage(file.language) ?: return false if (!hasEditorParameterHintAtOffset(editor, file)) return false val option = getOptionHintAtOffset(editor, file) ?: return false lastOptionName = option.optionName return true } private fun getOptionHintAtOffset(editor: Editor, file: PsiFile): HintInfo.OptionInfo? { val offset = editor.caretModel.offset return getHintInfoFromProvider(offset, file, editor) as? HintInfo.OptionInfo } override fun invoke(project: Project, editor: Editor, file: PsiFile) { val option = getOptionHintAtOffset(editor, file) ?: return option.disable() refreshAllOpenEditors() } override fun startInWriteAction(): Boolean = false } class EnableCustomHintsOption: IntentionAction, HighPriorityAction { companion object { private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name") } private var lastOptionName = "" override fun getText(): String { if (lastOptionName.startsWith("show", ignoreCase = true)) { return lastOptionName.capitalizeFirstLetter() } return CodeInsightBundle.message("inlay.hints.enable.custom.option", lastOptionName) } override fun getFamilyName(): String = presentableFamilyName override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { val language = file.language if(!isParameterHintsEnabledForLanguage(language)) return false if (editor !is EditorImpl) return false InlayParameterHintsExtension.forLanguage(file.language) ?: return false val option = getDisabledOptionInfoAtCaretOffset(editor, file) ?: return false lastOptionName = option.optionName return true } private fun getDisabledOptionInfoAtCaretOffset(editor: Editor, file: PsiFile): HintInfo.OptionInfo? { val offset = editor.caretModel.offset val element = file.findElementAt(offset) ?: return null val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null val target = PsiTreeUtil.findFirstParent(element) { it is PsiFile || provider.hasDisabledOptionHintInfo(it) } if (target == null || target is PsiFile) return null return provider.getHintInfo(target) as? HintInfo.OptionInfo } override fun invoke(project: Project, editor: Editor, file: PsiFile) { val option = getDisabledOptionInfoAtCaretOffset(editor, file) ?: return option.enable() refreshAllOpenEditors() } override fun startInWriteAction(): Boolean = false } private fun InlayParameterHintsProvider.hasDisabledOptionHintInfo(element: PsiElement): Boolean { val info = getHintInfo(element) return info is HintInfo.OptionInfo && !info.isOptionEnabled() } class ToggleInlineHintsAction : AnAction() { companion object { private val disableText = CodeInsightBundle.message("inlay.hints.disable.action.text").capitalize() private val enableText = CodeInsightBundle.message("inlay.hints.enable.action.text").capitalize() } override fun update(e: AnActionEvent) { if (!InlayParameterHintsExtension.hasAnyExtensions()) { e.presentation.isEnabledAndVisible = false return } val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val isHintsShownNow = isParameterHintsEnabledForLanguage(file.language) e.presentation.text = if (isHintsShownNow) disableText else enableText e.presentation.isEnabledAndVisible = true } override fun actionPerformed(e: AnActionEvent) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val language = file.language val before = isParameterHintsEnabledForLanguage(language) setShowParameterHintsForLanguage(!before, language) refreshAllOpenEditors() } } private fun hasEditorParameterHintAtOffset(editor: Editor, file: PsiFile): Boolean { if (editor is EditorWindow) return false val offset = editor.caretModel.offset val element = file.findElementAt(offset) val startOffset = element?.textRange?.startOffset ?: offset val endOffset = element?.textRange?.endOffset ?: offset return ParameterHintsPresentationManager.getInstance().getParameterHintsInRange(editor, startOffset, endOffset).isNotEmpty() } private fun refreshAllOpenEditors() { ParameterHintsPassFactory.forceHintsUpdateOnNextPass() ProjectManager.getInstance().openProjects.forEach { project -> val psiManager = PsiManager.getInstance(project) val daemonCodeAnalyzer = DaemonCodeAnalyzer.getInstance(project) val fileEditorManager = FileEditorManager.getInstance(project) fileEditorManager.selectedFiles.forEach { file -> psiManager.findFile(file)?.let { daemonCodeAnalyzer.restart(it) } } } } private fun getHintInfoFromProvider(offset: Int, file: PsiFile, editor: Editor): HintInfo? { val element = file.findElementAt(offset) ?: return null val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null val method = PsiTreeUtil.findFirstParent(element) { it is PsiFile // hint owned by element || (provider.getHintInfo(it)?.isOwnedByPsiElement(it, editor) ?: false)} if (method == null || method is PsiFile) return null return provider.getHintInfo(method) } fun MethodInfo.toPattern(): String = this.fullyQualifiedName + '(' + this.paramNames.joinToString(",") + ')' private fun String.capitalize() = StringUtil.capitalizeWords(this, true) private fun String.capitalizeFirstLetter() = StringUtil.capitalize(this)
platform/lang-impl/src/com/intellij/codeInsight/hints/PopupActions.kt
159384083
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotlin.text.regex /** * Represents a node for a '$' sign. * Note: In Kotlin we use only the "anchoring bounds" mode when "$" matches the end of a match region. * See: http://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#useAnchoringBounds-boolean- */ internal class EOLSet(val consCounter: Int, val lt: AbstractLineTerminator, val multiline: Boolean = false) : SimpleSet() { override fun matches(startIndex: Int, testString: CharSequence, matchResult: MatchResultImpl): Int { val rightBound = testString.length val remainingChars = rightBound - startIndex when { startIndex >= rightBound || remainingChars == 1 && lt.isLineTerminator(testString[startIndex]) || remainingChars == 2 && lt.isLineTerminatorPair(testString[startIndex], testString[startIndex+1]) || multiline && lt.isLineTerminator(testString[startIndex]) -> { matchResult.setConsumed(consCounter, 0) return next.matches(startIndex, testString, matchResult) } } return -1 } override fun hasConsumed(matchResult: MatchResultImpl): Boolean { val result = matchResult.getConsumed(consCounter) != 0 matchResult.setConsumed(consCounter, -1) return result } override val name: String get()= "<EOL>" }
runtime/src/main/kotlin/kotlin/text/regex/sets/EOLSet.kt
1234017353
// FILE: 1.kt package test import kotlin.reflect.KProperty class Delegate { operator fun getValue(t: Any?, p: KProperty<*>): String = "O" } inline fun test(crossinline s: () -> String): String { val delegate = Delegate() val o = object { fun run(): String { val prop: String by delegate return prop + s() } } return o.run() } // FILE: 2.kt import test.* fun box(): String { return test { "K" } }
backend.native/tests/external/codegen/boxInline/delegatedProperty/localInAnonymousObject.kt
3558809854
/* * Copyright (c) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.chromeos.videocompositionsample.domain.interactor.settings import dev.chromeos.videocompositionsample.domain.entity.Settings import dev.chromeos.videocompositionsample.domain.exception.NullParamsUseCaseException import dev.chromeos.videocompositionsample.domain.interactor.base.CompletableUseCase import dev.chromeos.videocompositionsample.domain.repository.ISettingsRepo import dev.chromeos.videocompositionsample.domain.schedulers.ISchedulerProvider import io.reactivex.Completable import javax.inject.Inject class PutSettingsUseCase @Inject constructor(schedulerProvider: ISchedulerProvider, private val settingRepo: ISettingsRepo ) : CompletableUseCase<PutSettingsUseCase.RequestValues>(schedulerProvider) { override fun buildUseCase(requestValues: RequestValues?): Completable { return if (requestValues != null) { Completable.fromCallable { settingRepo.put(requestValues.settings) Completable.complete() } } else { Completable.error(NullParamsUseCaseException()) } } data class RequestValues(val settings: Settings) : CompletableUseCase.RequestValues }
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/domain/interactor/settings/PutSettingsUseCase.kt
2558183018
package com.octo.mob.planningpoker.list.model import android.support.annotation.DrawableRes import com.octo.mob.planningpoker.R enum class CardDeck(val resourceList: List<Card>) { FIBONACCI(listOf( Card.ONE, Card.TWO, Card.THREE, Card.FIVE, Card.HEIGHT, Card.THIRTEEN, Card.TWENTY_ONE, Card.COFFEE )) , TSHIRT(listOf( Card.XS, Card.S, Card.M, Card.L, Card.XL, Card.COFFEE )) } enum class Card(@DrawableRes val resource: Int) { ONE(R.drawable.fibonacci_1), TWO(R.drawable.fibonacci_2), THREE(R.drawable.fibonacci_3), FIVE(R.drawable.fibonacci_5), HEIGHT(R.drawable.fibonacci_8), THIRTEEN(R.drawable.fibonacci_13), TWENTY_ONE(R.drawable.fibonacci_21), XS(R.drawable.tshirt_xs), S(R.drawable.tshirt_s), M(R.drawable.tshirt_m), L(R.drawable.tshirt_l), XL(R.drawable.tshirt_xl), COFFEE(R.drawable.coffee) }
app/src/main/kotlin/com/octo/mob/planningpoker/list/model/CardDeck.kt
2631454961
package com.vimeo.networking2.params import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Container for [AddVideoToAlbum]. * * @param video The video that should be added. */ @JsonClass(generateAdapter = true) data class AddVideoToAlbumContainer( @Json(name = "video") val video: AddVideoToAlbum ) { /** * A secondary constructor that eliminates the redundancy of the wrapping. * * @param uri The URI of the video. * @param position The position of the video. */ constructor(uri: String, position: Int?) : this(AddVideoToAlbum(uri, position)) }
models/src/main/java/com/vimeo/networking2/params/AddVideoToAlbumContainer.kt
102420663
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.migration.bundle import androidx.annotation.RestrictTo import androidx.room.migration.bundle.SchemaEqualityUtil.checkSchemaEquality import com.google.gson.annotations.SerializedName /** * Data class that holds the schema information for a * [androidx.room.Database]. * * @constructor Creates a new database * @property version Version * @property identityHash Identity hash * @property entities List of entities * @property views List of views * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) public open class DatabaseBundle( @field:SerializedName("version") public open val version: Int, @field:SerializedName("identityHash") public open val identityHash: String, @field:SerializedName("entities") public open val entities: List<EntityBundle>, @field:SerializedName("views") public open val views: List<DatabaseViewBundle>, @field:SerializedName("setupQueries") private val setupQueries: List<String>, ) : SchemaEquality<DatabaseBundle> { // Used by GSON @Deprecated("Marked deprecated to avoid usage in the codebase") @SuppressWarnings("unused") public constructor() : this(0, "", emptyList(), emptyList(), emptyList()) @delegate:Transient public open val entitiesByTableName: Map<String, EntityBundle> by lazy { entities.associateBy { it.tableName } } @delegate:Transient public val viewsByName: Map<String, DatabaseViewBundle> by lazy { views.associateBy { it.viewName } } /** * @return List of SQL queries to build this database from scratch. */ public open fun buildCreateQueries(): List<String> { return buildList { entities.sortedWith(FtsEntityCreateComparator()).forEach { entityBundle -> addAll(entityBundle.buildCreateQueries()) } views.forEach { viewBundle -> add(viewBundle.createView()) } addAll(setupQueries) } } @Override override fun isSchemaEqual(other: DatabaseBundle): Boolean { return checkSchemaEquality(entitiesByTableName, other.entitiesByTableName) && checkSchemaEquality(viewsByName, other.viewsByName) } // Comparator to sort FTS entities after their declared external content entity so that the // content entity table gets created first. public class FtsEntityCreateComparator : Comparator<EntityBundle> { override fun compare(firstEntity: EntityBundle, secondEntity: EntityBundle): Int { if (firstEntity is FtsEntityBundle) { val contentTable = firstEntity.ftsOptions.contentTable if (contentTable == secondEntity.tableName) { return 1 } } else if (secondEntity is FtsEntityBundle) { val contentTable = secondEntity.ftsOptions.contentTable if (contentTable == firstEntity.tableName) { return -1 } } return 0 } } }
room/room-migration/src/main/java/androidx/room/migration/bundle/DatabaseBundle.kt
4011299339
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build.resources import androidx.build.checkapi.ApiLocation import org.gradle.api.DefaultTask import org.gradle.api.provider.ListProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.Internal import org.gradle.api.tasks.OutputFiles import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import java.io.File /** * Task for updating the public Android resource surface, e.g. `public.xml`. */ @CacheableTask abstract class UpdateResourceApiTask : DefaultTask() { /** Generated resource API file (in build output). */ @get:Internal abstract val apiLocation: Property<ApiLocation> @get:Input abstract val forceUpdate: Property<Boolean> @InputFile @PathSensitive(PathSensitivity.RELATIVE) fun getTaskInput(): File { return apiLocation.get().resourceFile } /** Resource API files to which APIs should be written (in source control). */ @get:Internal // outputs are declared in getTaskOutputs() abstract val outputApiLocations: ListProperty<ApiLocation> @OutputFiles fun getTaskOutputs(): List<File> { return outputApiLocations.get().flatMap { outputApiLocation -> listOf( outputApiLocation.resourceFile ) } } @TaskAction fun updateResourceApi() { var permitOverwriting = true for (outputApi in outputApiLocations.get()) { val version = outputApi.version() if (version != null && version.isFinalApi() && outputApi.publicApiFile.exists() && !forceUpdate.get() ) { permitOverwriting = false } } val inputApi = apiLocation.get().resourceFile for (outputApi in outputApiLocations.get()) { androidx.build.metalava.copy( inputApi, outputApi.resourceFile, permitOverwriting, logger ) } } }
buildSrc/private/src/main/kotlin/androidx/build/resources/UpdateResourceApiTask.kt
3964555177
/* * 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.build.paparazzi import java.util.zip.ZipInputStream import org.gradle.api.artifacts.transform.CacheableTransform import org.gradle.api.artifacts.transform.InputArtifact import org.gradle.api.artifacts.transform.TransformAction import org.gradle.api.artifacts.transform.TransformOutputs import org.gradle.api.artifacts.transform.TransformParameters.None import org.gradle.api.file.FileSystemLocation import org.gradle.api.provider.Provider import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity /** * Unzips one of Paparazzi's platform-specific layoutlib JAR artifacts so that Paparazzi can read * its contents at run time. These contain a native dynamic library and supporting resources * including ICU and fonts. */ @CacheableTransform abstract class UnzipPaparazziNativeTransform : TransformAction<None> { @get:PathSensitive(PathSensitivity.NAME_ONLY) @get:InputArtifact abstract val primaryInput: Provider<FileSystemLocation> override fun transform(outputs: TransformOutputs) { val inputFile = primaryInput.get().asFile val outputDir = outputs.dir(inputFile.nameWithoutExtension).also { it.mkdirs() } ZipInputStream(inputFile.inputStream().buffered()).use { zipInputStream -> while (true) { val entry = zipInputStream.nextEntry ?: break val outputFile = outputDir.resolve(entry.name) if (entry.isDirectory) { outputFile.mkdir() } else { // This works because ZipInputStream resizes itself to the contents of the // last-returned entry outputFile.outputStream().buffered().use { zipInputStream.copyTo(it) } } } } } }
buildSrc/private/src/main/kotlin/androidx/build/paparazzi/UnzipPaparazziNativeTransform.kt
996782052
// SET_TRUE: SMART_TABS // SET_TRUE: USE_TAB_CHARACTER // SET_TRUE: ALIGN_MULTILINE_PARAMETERS // WITHOUT_CUSTOM_LINE_INDENT_PROVIDER class A( a: Int, <caret> )
plugins/kotlin/idea/tests/testData/editor/enterHandler/SmartEnterWithTabsOnConstructorParametersWithInvertedAlignWhenMultiline.after.kt
1790160437
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.transformations.impl.namedVariant import com.intellij.openapi.util.NlsSafe import com.intellij.psi.CommonClassNames.JAVA_UTIL_MAP import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiManager import com.intellij.psi.PsiModifier import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil.getAnnotation import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightModifierList import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightParameter import org.jetbrains.plugins.groovy.lang.resolve.ast.extractVisibility import org.jetbrains.plugins.groovy.lang.resolve.ast.getVisibility import org.jetbrains.plugins.groovy.transformations.AstTransformationSupport import org.jetbrains.plugins.groovy.transformations.TransformationContext class NamedVariantTransformationSupport : AstTransformationSupport { override fun applyTransformation(context: TransformationContext) { context.codeClass.codeMethods.forEach { if (!it.hasAnnotation(GROOVY_TRANSFORM_NAMED_VARIANT)) return@forEach val method = constructNamedMethod(it, context) ?: return@forEach context.addMethod(method) } } private fun constructNamedMethod(method: GrMethod, context: TransformationContext): GrLightMethodBuilder? { val parameters = mutableListOf<GrParameter>() val namedVariantAnnotation = method.getAnnotation(GROOVY_TRANSFORM_NAMED_VARIANT) ?: return null val mapType = TypesUtil.createType(JAVA_UTIL_MAP, method) val mapParameter = GrLightParameter(NAMED_ARGS_PARAMETER_NAME, mapType, method) val modifierList = GrLightModifierList(mapParameter) mapParameter.modifierList = modifierList parameters.add(mapParameter) val namedParams = collectNamedParamsFromNamedVariantMethod(method) namedParams.forEach { namedParam -> addNamedParamAnnotation(modifierList, namedParam) } val requiredParameters = method.parameterList.parameters .filter { getAnnotation(it, GROOVY_TRANSFORM_NAMED_PARAM) == null && getAnnotation(it, GROOVY_TRANSFORM_NAMED_DELEGATE) == null } if (requiredParameters.size != method.parameters.size) { parameters.addAll(requiredParameters) } return buildMethod(parameters, method, namedVariantAnnotation, context) } internal class NamedVariantGeneratedMethod(manager: PsiManager?, name: @NlsSafe String?) : GrLightMethodBuilder(manager, name) private fun buildMethod(parameters: List<GrParameter>, method: GrMethod, namedVariantAnnotation: PsiAnnotation, context: TransformationContext): GrLightMethodBuilder? { val builder = NamedVariantGeneratedMethod(method.manager, method.name + "") val psiClass = method.containingClass ?: return null builder.containingClass = psiClass builder.returnType = method.returnType builder.navigationElement = method val defaultVisibility = extractVisibility(method) val requiredVisibility = getVisibility(namedVariantAnnotation, builder, defaultVisibility) builder.modifierList.addModifier(requiredVisibility.toString()) if (context.hasModifierProperty(method.modifierList, PsiModifier.STATIC)) { builder.modifierList.addModifier(PsiModifier.STATIC) } builder.isConstructor = method.isConstructor parameters.forEach { builder.addParameter(it) } method.throwsList.referencedTypes.forEach { builder.addException(it) } builder.originInfo = NAMED_VARIANT_ORIGIN_INFO return builder } }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/impl/namedVariant/NamedVariantTransformationSupport.kt
2439060497
// 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.idea.maven.plugins.groovy.wizard import com.intellij.ide.util.EditorHelper import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.openapi.application.ModalityState import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.openapi.roots.ui.configuration.ModulesProvider import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import org.jetbrains.idea.maven.model.MavenConstants import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.utils.MavenUtil import org.jetbrains.idea.maven.wizards.AbstractMavenModuleBuilder import org.jetbrains.idea.maven.wizards.MavenStructureWizardStep import org.jetbrains.idea.maven.wizards.MavenWizardBundle import org.jetbrains.idea.maven.wizards.SelectPropertiesStep import org.jetbrains.plugins.groovy.config.GroovyConfigUtils import org.jetbrains.plugins.groovy.config.wizard.createSampleGroovyCodeFile import java.util.* import kotlin.io.path.Path import kotlin.io.path.createDirectories /** * Currently used only for new project wizard, thus the functionality is rather limited */ class MavenGroovyNewProjectBuilder(private val groovySdkVersion : String) : AbstractMavenModuleBuilder() { var createSampleCode = false override fun createWizardSteps(wizardContext: WizardContext, modulesProvider: ModulesProvider): Array<ModuleWizardStep> = arrayOf( MavenStructureWizardStep(this, wizardContext), SelectPropertiesStep(wizardContext.project, this), ) override fun setupRootModel(rootModel: ModifiableRootModel) { val project = rootModel.project val contentPath = contentEntryPath ?: return val path = FileUtil.toSystemIndependentName(contentPath).also { Path(it).createDirectories() } val root = LocalFileSystem.getInstance().refreshAndFindFileByPath(path) ?: return rootModel.addContentEntry(root) if (myJdk != null) { rootModel.sdk = myJdk } else { rootModel.inheritSdk() } MavenUtil.runWhenInitialized(project) { setupMavenStructure(project, root) } } private fun setupMavenStructure(project: Project, root: VirtualFile) { val pom = WriteCommandAction.writeCommandAction(project) .withName(MavenWizardBundle.message("maven.new.project.wizard.groovy.creating.groovy.project")) .compute<VirtualFile, RuntimeException> { root.findChild(MavenConstants.POM_XML)?.delete(this) val file = root.createChildData(this, MavenConstants.POM_XML) val properties = Properties() val conditions = Properties() properties.setProperty("GROOVY_VERSION", groovySdkVersion) properties.setProperty("GROOVY_REPOSITORY", GroovyConfigUtils.getMavenSdkRepository(groovySdkVersion)) conditions.setProperty("NEED_POM", (GroovyConfigUtils.compareSdkVersions(groovySdkVersion, GroovyConfigUtils.GROOVY2_5) >= 0).toString()) conditions.setProperty("CREATE_SAMPLE_CODE", "true") MavenUtil.runOrApplyMavenProjectFileTemplate(project, file, projectId, null, null, properties, conditions, MAVEN_GROOVY_XML_TEMPLATE, false) file } val sourceDirectory = VfsUtil.createDirectories(root.path + "/src/main/groovy") VfsUtil.createDirectories(root.path + "/src/main/resources") VfsUtil.createDirectories(root.path + "/src/test/groovy") if (createSampleCode) { createSampleGroovyCodeFile(project, sourceDirectory) } MavenProjectsManager.getInstance(project).forceUpdateAllProjectsOrFindAllAvailablePomFiles() MavenUtil.invokeLater(project, ModalityState.NON_MODAL) { PsiManager.getInstance(project).findFile(pom)?.let(EditorHelper::openInEditor) } } } private const val MAVEN_GROOVY_XML_TEMPLATE = "Maven Groovy.xml"
plugins/maven/src/main/java/org/jetbrains/idea/maven/plugins/groovy/wizard/MavenGroovyNewProjectBuilder.kt
3802046725
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.wizard import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.Key import com.intellij.ui.dsl.builder.Panel import org.jetbrains.annotations.ApiStatus import javax.swing.JComponent @ApiStatus.Internal internal class NewProjectWizardPanelBuilder(private val context: WizardContext) { private val panels = LinkedHashMap<DialogPanel, Boolean>() private val straightPanels get() = panels.filter { it.value }.keys fun getPreferredFocusedComponent(): JComponent? = straightPanels.firstNotNullOfOrNull { it.preferredFocusedComponent } fun panel(init: Panel.() -> Unit) = com.intellij.ui.dsl.builder.panel(init) .also { panels[it] = true } .apply { registerValidators(context.disposable) } fun setVisible(panel: DialogPanel, isVisible: Boolean) { panels[panel] = isVisible panel.isVisible = isVisible } fun validate() = straightPanels.asSequence() .flatMap { it.validateCallbacks } .mapNotNull { it() } .map { it.also(::logValidationInfoInHeadlessMode) } .all { it.okEnabled } private fun logValidationInfoInHeadlessMode(info: ValidationInfo) { if (ApplicationManager.getApplication().isHeadlessEnvironment) { logger<NewProjectWizardPanelBuilder>().warn(info.message) } } fun isModified() = straightPanels.any { it.isModified() } fun apply() = straightPanels.forEach(DialogPanel::apply) fun reset() = panels.keys.forEach(DialogPanel::reset) init { KEY.set(context, this) } companion object { private val KEY = Key.create<NewProjectWizardPanelBuilder>(NewProjectWizardPanelBuilder::class.java.name) fun getInstance(context: WizardContext): NewProjectWizardPanelBuilder = KEY.get(context) } }
platform/platform-impl/src/com/intellij/ide/wizard/NewProjectWizardPanelBuilder.kt
2217840017
fun t() { while (true) { t<caret> } } // ELEMENT: try
plugins/kotlin/completion/tests/testData/handlers/keywords/Try.kt
3386237809
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api.data.pullrequest class GHPullRequestReviewRequest(val requestedReviewer: GHPullRequestRequestedReviewer?)
plugins/github/src/org/jetbrains/plugins/github/api/data/pullrequest/GHPullRequestReviewRequest.kt
1514339266
package flank.log import org.junit.Assert.assertEquals import org.junit.Test private const val STATIC = "static" private const val VALUE = "value" private const val CLASS = "class" private const val STRING = "string" /** * Complete logger API test. */ class LoggingTest { private object Singleton : Event.Type<Unit> private object Value : Event.Type<String> private data class Class(val value: String) : Event.Data /** * Test logging API. * * * Build [Formatter] with different types of formatting functions. * * Create output with events wrapper. * * Pass various objects to logger output. */ @Test fun test() { // Given val expected = listOf(STATIC, VALUE, CLASS, STRING) val actual = mutableListOf<String>() // Specify formatter for converting registered types into string values val formatter = buildFormatter<String> { Singleton { STATIC } Value { this } Class::class { value } match { it as? String } to { this } } // Prepare log output from string formatter val out: Output = formatter .output { formatted -> actual += formatted } .normalize { next -> Unit event next } // When Singleton.out() Value(VALUE).out() Class(CLASS).out() STRING.out() // Then assertEquals(expected, actual) } }
tool/log/format/src/test/kotlin/flank/log/LoggingTest.kt
3639862616
package com.cn29.aac.ui.main import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProvider import com.cn29.aac.R import com.cn29.aac.databinding.ActivityAppArchNavigationDrawerBinding import com.cn29.aac.ui.main.vm.AppArchNavViewModel import com.cn29.aac.ui.main.vm.AppArchNavViewModelFactory import dagger.Module import dagger.Provides /** * Created by Charles Ng on 13/10/2017. */ @Module class AppArchNavigationDrawerModule { @Provides fun provideVm(drawer: AppArchNavigationDrawer, factory: AppArchNavViewModelFactory): AppArchNavViewModel { return ViewModelProvider(drawer, factory).get( AppArchNavViewModel::class.java) } @Provides fun provideBinding(drawer: AppArchNavigationDrawer?): ActivityAppArchNavigationDrawerBinding { return DataBindingUtil.setContentView(drawer!!, R.layout.activity_app_arch_navigation_drawer) } }
app/src/main/java/com/cn29/aac/ui/main/AppArchNavigationDrawerModule.kt
1270339390
package info.nightscout.androidaps.danar.di import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.danaRKorean.comm.* import info.nightscout.androidaps.danaRv2.comm.* import info.nightscout.androidaps.danar.comm.* @Module @Suppress("unused") abstract class DanaRCommModule { @ContributesAndroidInjector abstract fun contributesMessageBase(): MessageBase @ContributesAndroidInjector abstract fun contributesMsgSetTime(): MsgSetTime @ContributesAndroidInjector abstract fun contributesMsgBolusProgress(): MsgBolusProgress @ContributesAndroidInjector abstract fun contributesMsgBolusStart(): MsgBolusStart @ContributesAndroidInjector abstract fun contributesMsgBolusStartWithSpeed(): MsgBolusStartWithSpeed @ContributesAndroidInjector abstract fun contributesMsgBolusStop(): MsgBolusStop @ContributesAndroidInjector abstract fun contributesMsgCheckValue(): MsgCheckValue @ContributesAndroidInjector abstract fun contributesMsgError(): MsgError @ContributesAndroidInjector abstract fun contributesMsgHistoryAll(): MsgHistoryAll @ContributesAndroidInjector abstract fun contributesMsgHistoryAllDone(): MsgHistoryAllDone @ContributesAndroidInjector abstract fun contributesMsgHistoryDone(): MsgHistoryDone @ContributesAndroidInjector abstract fun contributesMsgHistoryNewDone(): MsgHistoryNewDone @ContributesAndroidInjector abstract fun contributesMsgInitConnStatusBasic(): MsgInitConnStatusBasic @ContributesAndroidInjector abstract fun contributesMsgInitConnStatusBolus(): MsgInitConnStatusBolus @ContributesAndroidInjector abstract fun contributesMsgInitConnStatusOption(): MsgInitConnStatusOption @ContributesAndroidInjector abstract fun contributesMsgInitConnStatusTime(): MsgInitConnStatusTime @ContributesAndroidInjector abstract fun contributesMsgPCCommStart(): MsgPCCommStart @ContributesAndroidInjector abstract fun contributesMsgPCCommStop(): MsgPCCommStop @ContributesAndroidInjector abstract fun contributesMsgSetActivateBasalProfile(): MsgSetActivateBasalProfile @ContributesAndroidInjector abstract fun contributesMsgSetBasalProfile(): MsgSetBasalProfile @ContributesAndroidInjector abstract fun contributesMsgSetCarbsEntry(): MsgSetCarbsEntry @ContributesAndroidInjector abstract fun contributesMsgSetExtendedBolusStart(): MsgSetExtendedBolusStart @ContributesAndroidInjector abstract fun contributesMsgSetExtendedBolusStop(): MsgSetExtendedBolusStop @ContributesAndroidInjector abstract fun contributesMsgSetSingleBasalProfile(): MsgSetSingleBasalProfile @ContributesAndroidInjector abstract fun contributesMsgSetTempBasalStart(): MsgSetTempBasalStart @ContributesAndroidInjector abstract fun contributesMsgSetTempBasalStop(): MsgSetTempBasalStop @ContributesAndroidInjector abstract fun contributesMsgSetUserOptions(): MsgSetUserOptions @ContributesAndroidInjector abstract fun contributesMsgSettingActiveProfile(): MsgSettingActiveProfile @ContributesAndroidInjector abstract fun contributesMsgSettingBasal(): MsgSettingBasal @ContributesAndroidInjector abstract fun contributesMsgSettingBasalProfileAll(): MsgSettingBasalProfileAll @ContributesAndroidInjector abstract fun contributesMsgSettingGlucose(): MsgSettingGlucose @ContributesAndroidInjector abstract fun contributesMsgSettingMaxValues(): MsgSettingMaxValues @ContributesAndroidInjector abstract fun contributesMsgSettingMeal(): MsgSettingMeal @ContributesAndroidInjector abstract fun contributesMsgSettingProfileRatios(): MsgSettingProfileRatios @ContributesAndroidInjector abstract fun contributesMsgSettingProfileRatiosAll(): MsgSettingProfileRatiosAll @ContributesAndroidInjector abstract fun contributesMsgSettingPumpTime(): MsgSettingPumpTime @ContributesAndroidInjector abstract fun contributesMsgSettingShippingInfo(): MsgSettingShippingInfo @ContributesAndroidInjector abstract fun contributesMsgSettingUserOptions(): MsgSettingUserOptions @ContributesAndroidInjector abstract fun contributesMsgStatus(): MsgStatus @ContributesAndroidInjector abstract fun contributesMsgStatusBasic(): MsgStatusBasic @ContributesAndroidInjector abstract fun contributesMsgStatusBolusExtended(): MsgStatusBolusExtended @ContributesAndroidInjector abstract fun contributesMsgStatusProfile(): MsgStatusProfile @ContributesAndroidInjector abstract fun contributesMsgStatusTempBasal(): MsgStatusTempBasal @ContributesAndroidInjector abstract fun contributesMsgHistoryBolus(): MsgHistoryBolus @ContributesAndroidInjector abstract fun contributesMsgHistoryDailyInsulin(): MsgHistoryDailyInsulin @ContributesAndroidInjector abstract fun contributesMsgHistoryGlucose(): MsgHistoryGlucose @ContributesAndroidInjector abstract fun contributesMsgHistoryAlarm(): MsgHistoryAlarm @ContributesAndroidInjector abstract fun contributesMsgHistoryError(): MsgHistoryError @ContributesAndroidInjector abstract fun contributesMsgHistoryCarbo(): MsgHistoryCarbo @ContributesAndroidInjector abstract fun contributesMsgHistoryRefill(): MsgHistoryRefill @ContributesAndroidInjector abstract fun contributesMsgHistorySuspend(): MsgHistorySuspend @ContributesAndroidInjector abstract fun contributesMsgHistoryBasalHour(): MsgHistoryBasalHour @ContributesAndroidInjector abstract fun contributesMsgHistoryNew(): MsgHistoryNew @ContributesAndroidInjector abstract fun contributesMsgCheckValue_v2(): MsgCheckValue_v2 @ContributesAndroidInjector abstract fun contributesMsgHistoryEvents_v2(): MsgHistoryEvents_v2 @ContributesAndroidInjector abstract fun contributesMsgSetAPSTempBasalStart_v2(): MsgSetAPSTempBasalStart_v2 @ContributesAndroidInjector abstract fun contributesMsgSetHistoryEntry_v2(): MsgSetHistoryEntry_v2 @ContributesAndroidInjector abstract fun contributesMsgStatusAPS_v2(): MsgStatusAPS_v2 @ContributesAndroidInjector abstract fun contributesMsgStatusBolusExtended_v2(): MsgStatusBolusExtended_v2 @ContributesAndroidInjector abstract fun contributesMsgStatusTempBasal_v2(): MsgStatusTempBasal_v2 @ContributesAndroidInjector abstract fun contributesMsgCheckValue_k(): MsgCheckValue_k @ContributesAndroidInjector abstract fun contributesMsgInitConnStatusBasic_k(): MsgInitConnStatusBasic_k @ContributesAndroidInjector abstract fun contributesMsgInitConnStatusBolus_k(): MsgInitConnStatusBolus_k @ContributesAndroidInjector abstract fun contributesMsgInitConnStatusTime_k(): MsgInitConnStatusTime_k @ContributesAndroidInjector abstract fun contributesMsgSettingBasalProfileAll_k(): MsgSettingBasalProfileAll_k @ContributesAndroidInjector abstract fun contributesMsgSettingBasal_k(): MsgSettingBasal_k @ContributesAndroidInjector abstract fun contributesMsgStatusBasic_k(): MsgStatusBasic_k @ContributesAndroidInjector abstract fun contributesMsgStatus_k(): MsgStatus_k }
danar/src/main/java/info/nightscout/androidaps/danar/di/DanaRCommModule.kt
3596950006
package info.nightscout.androidaps.plugins.treatments.fragments import android.graphics.Paint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import dagger.android.support.DaggerFragment import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.dialogs.ProfileViewerDialog import info.nightscout.androidaps.events.EventProfileNeedsUpdate import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfileSwitchFragment.RecyclerProfileViewAdapter.ProfileSwitchViewHolder import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.treatments_profileswitch_fragment.* import javax.inject.Inject class TreatmentsProfileSwitchFragment : DaggerFragment() { private val disposable = CompositeDisposable() @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var sp: SP @Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var nsUpload: NSUpload @Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var dateUtil: DateUtil @Inject lateinit var buildHelper: BuildHelper override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.treatments_profileswitch_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) profileswitch_recyclerview.setHasFixedSize(true) profileswitch_recyclerview.layoutManager = LinearLayoutManager(view.context) profileswitch_recyclerview.adapter = RecyclerProfileViewAdapter(MainApp.getDbHelper().getProfileSwitchData(DateUtil.now() - T.days(30).msecs(), false)) profileswitch_refreshfromnightscout.setOnClickListener { activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.refresheventsfromnightscout) + "?") { MainApp.getDbHelper().resetProfileSwitch() rxBus.send(EventNSClientRestart()) } } } if (sp.getBoolean(R.string.key_ns_upload_only, true) || !buildHelper.isEngineeringMode()) profileswitch_refreshfromnightscout.visibility = View.GONE } @Synchronized override fun onResume() { super.onResume() disposable.add(rxBus .toObservable(EventProfileNeedsUpdate::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateGUI() }) { fabricPrivacy.logException(it) } ) updateGUI() } @Synchronized override fun onPause() { super.onPause() disposable.clear() } fun updateGUI() = profileswitch_recyclerview?.swapAdapter(RecyclerProfileViewAdapter(MainApp.getDbHelper().getProfileSwitchData(DateUtil.now() - T.days(30).msecs(), false)), false) inner class RecyclerProfileViewAdapter(private var profileSwitchList: List<ProfileSwitch>) : RecyclerView.Adapter<ProfileSwitchViewHolder>() { override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ProfileSwitchViewHolder { return ProfileSwitchViewHolder(LayoutInflater.from(viewGroup.context).inflate(R.layout.treatments_profileswitch_item, viewGroup, false)) } override fun onBindViewHolder(holder: ProfileSwitchViewHolder, position: Int) { val profileSwitch = profileSwitchList[position] holder.ph.visibility = (profileSwitch.source == Source.PUMP).toVisibility() holder.ns.visibility = NSUpload.isIdValid(profileSwitch._id).toVisibility() holder.date.text = dateUtil.dateAndTimeString(profileSwitch.date) if (!profileSwitch.isEndingEvent) { holder.duration.text = resourceHelper.gs(R.string.format_mins, profileSwitch.durationInMinutes) } else { holder.duration.text = "" } holder.name.text = profileSwitch.customizedName if (profileSwitch.isInProgress) holder.date.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.date.setTextColor(holder.duration.currentTextColor) holder.remove.tag = profileSwitch holder.clone.tag = profileSwitch holder.name.tag = profileSwitch holder.date.tag = profileSwitch holder.invalid.visibility = if (profileSwitch.isValid()) View.GONE else View.VISIBLE } override fun getItemCount(): Int { return profileSwitchList.size } inner class ProfileSwitchViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener { var date: TextView = itemView.findViewById<View>(R.id.profileswitch_date) as TextView var duration: TextView = itemView.findViewById<View>(R.id.profileswitch_duration) as TextView var name: TextView = itemView.findViewById<View>(R.id.profileswitch_name) as TextView var remove: TextView = itemView.findViewById<View>(R.id.profileswitch_remove) as TextView var clone: TextView = itemView.findViewById<View>(R.id.profileswitch_clone) as TextView var ph: TextView = itemView.findViewById<View>(R.id.pump_sign) as TextView var ns: TextView = itemView.findViewById<View>(R.id.ns_sign) as TextView var invalid: TextView = itemView.findViewById<View>(R.id.invalid_sign) as TextView override fun onClick(v: View) { val profileSwitch = v.tag as ProfileSwitch when (v.id) { R.id.profileswitch_remove -> activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), resourceHelper.gs(R.string.careportal_profileswitch) + ": " + profileSwitch.profileName + "\n" + resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(profileSwitch.date), Runnable { val id = profileSwitch._id if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) else uploadQueue.removeID("dbAdd", id) MainApp.getDbHelper().delete(profileSwitch) }) } R.id.profileswitch_clone -> activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), resourceHelper.gs(R.string.copytolocalprofile) + "\n" + profileSwitch.customizedName + "\n" + dateUtil.dateAndTimeString(profileSwitch.date), Runnable { profileSwitch.profileObject?.let { val nonCustomized = it.convertToNonCustomizedProfile() if (nonCustomized.isValid(resourceHelper.gs(R.string.careportal_profileswitch, false))) { localProfilePlugin.addProfile(localProfilePlugin.copyFrom(nonCustomized, profileSwitch.customizedName + " " + dateUtil.dateAndTimeString(profileSwitch.date).replace(".", "_"))) rxBus.send(EventLocalProfileChanged()) } else { OKDialog.show(activity, resourceHelper.gs(R.string.careportal_profileswitch), resourceHelper.gs(R.string.copytolocalprofile_invalid)) } } }) } R.id.profileswitch_date, R.id.profileswitch_name -> { val args = Bundle() args.putLong("time", (v.tag as ProfileSwitch).date) args.putInt("mode", ProfileViewerDialog.Mode.DB_PROFILE.ordinal) val pvd = ProfileViewerDialog() pvd.arguments = args pvd.show(childFragmentManager, "ProfileViewDialog") } } } init { remove.setOnClickListener(this) clone.setOnClickListener(this) remove.paintFlags = remove.paintFlags or Paint.UNDERLINE_TEXT_FLAG clone.paintFlags = clone.paintFlags or Paint.UNDERLINE_TEXT_FLAG name.setOnClickListener(this) date.setOnClickListener(this) } } } }
app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt
1121929470
package de.fabmax.kool.modules.ksl import de.fabmax.kool.math.Mat3f import de.fabmax.kool.math.Vec2f import de.fabmax.kool.math.Vec4f import de.fabmax.kool.modules.ksl.blocks.* import de.fabmax.kool.modules.ksl.lang.* import de.fabmax.kool.pipeline.Attribute import de.fabmax.kool.pipeline.BlendMode import de.fabmax.kool.pipeline.Texture2d import de.fabmax.kool.pipeline.TextureCube import de.fabmax.kool.pipeline.shading.AlphaMode import de.fabmax.kool.util.Color abstract class KslLitShader(cfg: LitShaderConfig, model: KslProgram) : KslShader(model, cfg.pipelineCfg) { var color: Vec4f by uniform4f(cfg.colorCfg.primaryUniform?.uniformName, cfg.colorCfg.primaryUniform?.defaultColor) var colorMap: Texture2d? by texture2d(cfg.colorCfg.primaryTexture?.textureName, cfg.colorCfg.primaryTexture?.defaultTexture) var normalMap: Texture2d? by texture2d(cfg.normalMapCfg.normalMapName, cfg.normalMapCfg.defaultNormalMap) var normalMapStrength: Float by uniform1f("uNormalMapStrength", cfg.normalMapCfg.defaultStrength) var ssaoMap: Texture2d? by texture2d("tSsaoMap", cfg.defaultSsaoMap) var ambientFactor: Vec4f by uniform4f("uAmbientColor") var ambientTextureOrientation: Mat3f by uniformMat3f("uAmbientTextureOri", Mat3f().setIdentity()) // if ambient color is image based var ambientTexture: TextureCube? by textureCube("tAmbientTexture") // if ambient color is dual image based val ambientTextures: Array<TextureCube?> by textureCubeArray("tAmbientTextures", 2) var ambientTextureWeights by uniform2f("tAmbientWeights", Vec2f.X_AXIS) init { when (val ambient = cfg.ambientColor) { is AmbientColor.Uniform -> ambientFactor = ambient.color is AmbientColor.ImageBased -> { ambientTexture = ambient.ambientTexture ambientFactor = ambient.colorFactor } is AmbientColor.DualImageBased -> { ambientFactor = ambient.colorFactor } } } sealed class AmbientColor { class Uniform(val color: Color) : AmbientColor() class ImageBased(val ambientTexture: TextureCube?, val colorFactor: Color) : AmbientColor() class DualImageBased(val colorFactor: Color) : AmbientColor() } open class LitShaderConfig { val vertexCfg = BasicVertexConfig() val colorCfg = ColorBlockConfig("baseColor") val normalMapCfg = NormalMapConfig() val pipelineCfg = PipelineConfig() val shadowCfg = ShadowConfig() var ambientColor: AmbientColor = AmbientColor.Uniform(Color(0.2f, 0.2f, 0.2f).toLinear()) var colorSpaceConversion = ColorSpaceConversion.LINEAR_TO_sRGB_HDR var maxNumberOfLights = 4 var lightStrength = 1f var isSsao = false var defaultSsaoMap: Texture2d? = null var alphaMode: AlphaMode = AlphaMode.Blend() var modelCustomizer: (KslProgram.() -> Unit)? = null fun enableSsao(ssaoMap: Texture2d? = null) { isSsao = true defaultSsaoMap = ssaoMap } fun color(block: ColorBlockConfig.() -> Unit) { colorCfg.block() } fun uniformAmbientColor(color: Color = Color(0.2f, 0.2f, 0.2f).toLinear()) { ambientColor = AmbientColor.Uniform(color) } fun imageBasedAmbientColor(ambientTexture: TextureCube? = null, colorFactor: Color = Color.WHITE) { ambientColor = AmbientColor.ImageBased(ambientTexture, colorFactor) } fun dualImageBasedAmbientColor(colorFactor: Color = Color.WHITE) { ambientColor = AmbientColor.DualImageBased(colorFactor) } fun normalMapping(block: NormalMapConfig.() -> Unit) { normalMapCfg.block() } fun pipeline(block: PipelineConfig.() -> Unit) { pipelineCfg.block() } fun shadow(block: ShadowConfig.() -> Unit) { shadowCfg.block() } fun vertices(block: BasicVertexConfig.() -> Unit) { vertexCfg.block() } } abstract class LitShaderModel<T: LitShaderConfig>(name: String) : KslProgram(name) { open fun createModel(cfg: T) { val camData = cameraData() val positionWorldSpace = interStageFloat3("positionWorldSpace") val normalWorldSpace = interStageFloat3("normalWorldSpace") val projPosition = interStageFloat4("screenUv") var tangentWorldSpace: KslInterStageVector<KslTypeFloat4, KslTypeFloat1>? = null val texCoordBlock: TexCoordAttributeBlock val shadowMapVertexStage: ShadowBlockVertexStage vertexStage { main { val uModelMat = modelMatrix() val viewProj = mat4Var(camData.viewProjMat) val modelMat = mat4Var(uModelMat.matrix) if (cfg.vertexCfg.isInstanced) { val instanceModelMat = instanceAttribMat4(Attribute.INSTANCE_MODEL_MAT.name) modelMat *= instanceModelMat } if (cfg.vertexCfg.isArmature) { val armatureBlock = armatureBlock(cfg.vertexCfg.maxNumberOfBones) armatureBlock.inBoneWeights(vertexAttribFloat4(Attribute.WEIGHTS.name)) armatureBlock.inBoneIndices(vertexAttribInt4(Attribute.JOINTS.name)) modelMat *= armatureBlock.outBoneTransform } // transform vertex attributes into world space and forward them to fragment stage val localPos = float4Value(vertexAttribFloat3(Attribute.POSITIONS.name), 1f) val localNormal = float4Value(vertexAttribFloat3(Attribute.NORMALS.name), 0f) // world position and normal are made available via ports for custom models to modify them val worldPos = float3Port("worldPos", float3Var((modelMat * localPos).xyz)) val worldNormal = float3Port("worldNormal", float3Var(normalize((modelMat * localNormal).xyz))) positionWorldSpace.input set worldPos normalWorldSpace.input set worldNormal projPosition.input set (viewProj * float4Value(worldPos, 1f)) outPosition set projPosition.input // if normal mapping is enabled, the input vertex data is expected to have a tangent attribute if (cfg.normalMapCfg.isNormalMapped) { tangentWorldSpace = interStageFloat4().apply { input set modelMat * float4Value(vertexAttribFloat4(Attribute.TANGENTS.name).xyz, 0f) } } // texCoordBlock is used by various other blocks to access texture coordinate vertex // attributes (usually either none, or Attribute.TEXTURE_COORDS but there can be more) texCoordBlock = texCoordAttributeBlock() // project coordinates into shadow map / light space shadowMapVertexStage = vertexShadowBlock(cfg.shadowCfg) { inPositionWorldSpace(worldPos) inNormalWorldSpace(worldNormal) } } } fragmentStage { val uNormalMapStrength = uniformFloat1("uNormalMapStrength") val lightData = sceneLightData(cfg.maxNumberOfLights) main { // determine main color (albedo) val colorBlock = fragmentColorBlock(cfg.colorCfg) val baseColorPort = float4Port("baseColor", colorBlock.outColor) // discard fragment output if alpha mode is mask and fragment alpha value is below cutoff value (cfg.alphaMode as? AlphaMode.Mask)?.let { mask -> `if`(baseColorPort.a lt mask.cutOff.const) { discard() } } val vertexNormal = float3Var(normalize(normalWorldSpace.output)) if (cfg.pipelineCfg.cullMethod.isBackVisible && cfg.vertexCfg.isFlipBacksideNormals) { `if`(!inIsFrontFacing) { vertexNormal *= (-1f).const3 } } // do normal map computations (if enabled) and adjust material block input normal accordingly val bumpedNormal = if (cfg.normalMapCfg.isNormalMapped) { normalMapBlock(cfg.normalMapCfg) { inTangentWorldSpace(normalize(tangentWorldSpace!!.output)) inNormalWorldSpace(vertexNormal) inStrength(uNormalMapStrength) inTexCoords(texCoordBlock.getAttributeCoords(cfg.normalMapCfg.coordAttribute)) }.outBumpNormal } else { vertexNormal } // make final normal value available to model customizer val normal = float3Port("normal", bumpedNormal) // create an array with light strength values per light source (1.0 = full strength) val shadowFactors = float1Array(lightData.maxLightCount, 1f.const) // adjust light strength values by shadow maps fragmentShadowBlock(shadowMapVertexStage, shadowFactors) val aoFactor = float1Var(1f.const) if (cfg.isSsao) { val aoMap = texture2d("tSsaoMap") val aoUv = float2Var(projPosition.output.xy / projPosition.output.w * 0.5f.const + 0.5f.const) aoFactor set sampleTexture(aoMap, aoUv).x } val irradiance = when (cfg.ambientColor) { is AmbientColor.Uniform -> uniformFloat4("uAmbientColor").rgb is AmbientColor.ImageBased -> { val ambientOri = uniformMat3("uAmbientTextureOri") val ambientTex = textureCube("tAmbientTexture") (sampleTexture(ambientTex, ambientOri * normal) * uniformFloat4("uAmbientColor")).rgb } is AmbientColor.DualImageBased -> { val ambientOri = uniformMat3("uAmbientTextureOri") val ambientTexs = textureArrayCube("tAmbientTextures", 2) val ambientWeights = uniformFloat2("tAmbientWeights") val ambientColor = float4Var(sampleTexture(ambientTexs[0], ambientOri * normal) * ambientWeights.x) `if`(ambientWeights.y gt 0f.const) { ambientColor += float4Var(sampleTexture(ambientTexs[1], ambientOri * normal) * ambientWeights.y) } (ambientColor * uniformFloat4("uAmbientColor")).rgb } } // main material block val materialColor = createMaterial( cfg = cfg, camData = camData, irradiance = irradiance, lightData = lightData, shadowFactors = shadowFactors, aoFactor = aoFactor, normal = normal, fragmentWorldPos = positionWorldSpace.output, baseColor = baseColorPort ) val materialColorPort = float4Port("materialColor", materialColor) // set fragment stage output color val outRgb = float3Var(materialColorPort.rgb) outRgb set convertColorSpace(outRgb, cfg.colorSpaceConversion) if (cfg.pipelineCfg.blendMode == BlendMode.BLEND_PREMULTIPLIED_ALPHA) { outRgb set outRgb * materialColorPort.a } when (cfg.alphaMode) { is AlphaMode.Blend -> colorOutput(outRgb, materialColorPort.a) is AlphaMode.Mask -> colorOutput(outRgb, 1f.const) is AlphaMode.Opaque -> colorOutput(outRgb, 1f.const) } } } cfg.modelCustomizer?.invoke(this) } protected abstract fun KslScopeBuilder.createMaterial( cfg: T, camData: CameraData, irradiance: KslExprFloat3, lightData: SceneLightData, shadowFactors: KslExprFloat1Array, aoFactor: KslExprFloat1, normal: KslExprFloat3, fragmentWorldPos: KslExprFloat3, baseColor: KslExprFloat4, ): KslExprFloat4 } }
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/KslLitShader.kt
408092646
package com.softwareleyline import bytecodeparser.analysis.decoders.DecodedMethodInvocationOp import bytecodeparser.analysis.stack.StackAnalyzer import javassist.ClassPool /** * Created by Geoff on 4/28/2016. */ class Assig3Driver { /** * executes the call to profile with installed instrimentation as per the provided graph. */ fun determinePathFor(targetClassName: String, callGraph: Node, callToProfile: () -> Unit) : Pair<Int, () -> Path> { val map = buildNodeMap(callGraph) val pathMap = generatePathIDByPathNodeNamesMap(map, callGraph); println("Path Id's are as follows:\n $pathMap") assert( ! isLoaded(targetClassName)) { "the class $targetClassName was already available in this class loader, aborting." } rewriteByteCode(targetClassName, map, callGraph.flattened()) val result = try { callToProfile() path; } finally { reset(); } val pathProvider : () -> Path = { pathMap.entries.single{ it.value == result }.key } return Pair(result, pathProvider); } private fun isLoaded(targetClassName: String): Boolean { val findLoadedClass = ClassLoader::class.java.getDeclaredMethod("findLoadedClass", String::class.java) findLoadedClass.isAccessible = true; val cl = ClassLoader.getSystemClassLoader(); val loaded = findLoadedClass.invoke(cl, targetClassName); return loaded != null; } private fun generatePathIDByPathNodeNamesMap(map: Map<Node, Int>, callGraph: Node) : Map<Path, Int> { val visitor = PathTrackingVisitor(map); callGraph.accept(visitor); return visitor.pathIDByNodeNames; } // builds the path-count-to-exit-by-node map // assumes there is only one zero-successor node. // if there are multiple zero-successor nodes, all of them are assumed to be 'exits'. // not sure if this algorithm still works under that condition // intuition says it should for some, if not all, possible graphs. private fun buildNodeMap(root : Node) : Map<Node, Int>{ val visitor = PathCountingVisitor() root.accept(visitor) return visitor.pathCountByNode; } private fun rewriteByteCode(target : String, nodeByPathCount : Map<Node, Int>, nodesToReWrite : Set<Node>){ pathCountByNodeName = nodeByPathCount.mapKeys { it.key.name } nodeByName = nodesToReWrite.associateBy { it.name } val pool = ClassPool.getDefault(); var clazz = pool.get(target) for(node in nodesToReWrite){ val method = clazz.getMethod(node.name, node.signature) //ok, the byte code from the resulting re-write looks like this: // LDC "A" // INVOKESTATIC com/softwareleyline/Assig3DriverKt.hit (Ljava/lang/String;)V //so what I want to know //is the first op code LDC, is the first opcodes arg "A", is the second op code INVOKESTATIC, is the target 'hit'. val analyzer = StackAnalyzer(method); val targetFrame = analyzer.analyze().map{ it.decodedOp }.take(2).last() if(targetFrame is DecodedMethodInvocationOp && targetFrame.run { declaringClassName == "com.softwareleyline.Assig3DriverKt" && name == "hit" }){ continue; } method.insertBefore("com.softwareleyline.Assig3DriverKt.hit(\"${node.name}\");") } clazz.freeze() val targetDir = javaClass.protectionDomain.codeSource.location.path clazz.writeFile(targetDir.toString()) } } //TODO this isn't thread safe. // could get some thread safety by using THreadLocal, // but that blows up if the annotated methods do their own thread hoping. // could add a UUID to the static closure, a little yucky but would do the job. var pathCountByNodeName : Map<String, Int> = emptyMap() var nodeByName : Map<String, Node> = emptyMap(); var path = 0 var lastVisitedNode = "" private fun reset(){ path = 0; lastVisitedNode = ""; pathCountByNodeName = emptyMap(); nodeByName = emptyMap(); } //well, insertBefore doesnt take a closure, annoyingly, // so im reduced to this kind of singleton. @Suppress("unused") // called via byte-code rewrite fun hit(name : String) { if(lastVisitedNode.isEmpty()){ lastVisitedNode = name; return; } if (name !in nodeByName.keys){ println("<saw hit on uninstructed method>") return; } val olderSibs = nodeByName.get(name)!!.getOlderSiblingsBy(nodeByName.get(lastVisitedNode)!!) path += olderSibs.sumBy { pathCountByNodeName[it.name]!! } lastVisitedNode = name; return; }
src/com/softwareleyline/Assig3Driver.kt
350195303
package com.kickstarter.services.apiresponses import android.os.Parcelable import com.kickstarter.models.Project import kotlinx.parcelize.Parcelize @Parcelize class ProjectsEnvelope private constructor( private val projects: List<Project>, private val urls: UrlsEnvelope ) : Parcelable { fun projects() = this.projects fun urls() = this.urls @Parcelize data class Builder( private var projects: List<Project> = emptyList(), private var urls: UrlsEnvelope = UrlsEnvelope.builder().build() ) : Parcelable { fun projects(projects: List<Project>) = apply { this.projects = projects } fun urls(urls: UrlsEnvelope) = apply { this.urls = urls } fun build() = ProjectsEnvelope( projects = projects, urls = urls ) } fun toBuilder() = Builder( projects = projects, urls = urls ) companion object { @JvmStatic fun builder() = Builder() } override fun equals(other: Any?): Boolean { var equals = super.equals(other) if (other is ProjectsEnvelope) { equals = projects() == other.projects() && urls() == other.urls() } return equals } @Parcelize class UrlsEnvelope private constructor( private val api: ApiEnvelope ) : Parcelable { fun api() = this.api @Parcelize data class Builder( private var api: ApiEnvelope = ApiEnvelope.builder().build() ) : Parcelable { fun api(api: ApiEnvelope) = apply { this.api = api } fun build() = UrlsEnvelope( api = api ) } fun toBuilder() = Builder( api = api ) companion object { @JvmStatic fun builder() = Builder() } override fun equals(other: Any?): Boolean { var equals = super.equals(other) if (other is UrlsEnvelope) { equals = api() == other.api() } return equals } @Parcelize class ApiEnvelope private constructor( private val moreProjects: String ) : Parcelable { fun moreProjects() = this.moreProjects @Parcelize data class Builder( private var moreProjects: String = "" ) : Parcelable { fun moreProjects(moreProjects: String?) = apply { this.moreProjects = moreProjects ?: "" } fun build() = ApiEnvelope( moreProjects = moreProjects ) } fun toBuilder() = Builder( moreProjects = moreProjects ) companion object { @JvmStatic fun builder() = Builder() } override fun equals(other: Any?): Boolean { var equals = super.equals(other) if (other is ApiEnvelope) { equals = moreProjects() == other.moreProjects() } return equals } } } }
app/src/main/java/com/kickstarter/services/apiresponses/ProjectsEnvelope.kt
3493091103
package i_introduction._9_Extension_Functions import util.TODO import util.doc9 import i_introduction._9_Extension_Functions.nested_package.r fun String.lastChar() = this.get(this.length - 1) // 'this' can be omitted fun String.lastChar1() = get(length - 1) fun use() { // try Ctrl+Space "default completion" after the dot: lastChar() is visible "abc".lastChar() } // 'lastChar' is compiled to a static function in the class ExtensionFunctionsKt (see JavaCode9.useExtension) fun todoTask9(): Nothing = TODO( """ Task 9. Implement the extension functions Int.r(), Pair<Int, Int>.r() to support the following manner of creating rational numbers: 1.r(), Pair(1, 2).r() """, documentation = doc9(), references = { 1.r(); Pair(1, 2).r(); RationalNumber(1, 9) }) data class RationalNumber(val numerator: Int, val denominator: Int)
src/i_introduction/_9_Extension_Functions/ExtensionFunctions.kt
4287254203
package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag class MsgSetTempBasalStart( injector: HasAndroidInjector, private var percent: Int, private var durationInHours: Int ) : MessageBase(injector) { init { SetCommand(0x0401) //HARDCODED LIMITS if (percent < 0) percent = 0 if (percent > 200) percent = 200 if (durationInHours < 1) durationInHours = 1 if (durationInHours > 24) durationInHours = 24 AddParamByte((percent and 255).toByte()) AddParamByte((durationInHours and 255).toByte()) aapsLogger.debug(LTag.PUMPCOMM, "Temp basal start percent: $percent duration hours: $durationInHours") } override fun handleMessage(bytes: ByteArray) { val result = intFromBuff(bytes, 0, 1) if (result != 1) { failed = true aapsLogger.debug(LTag.PUMPCOMM, "Set temp basal start result: $result FAILED!!!") } else { failed = false aapsLogger.debug(LTag.PUMPCOMM, "Set temp basal start result: $result") } } }
danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetTempBasalStart.kt
2816056095
package com.kickstarter.ui.activities import android.os.Bundle import android.util.Pair import androidx.core.widget.doOnTextChanged import com.jakewharton.rxbinding.view.RxView import com.kickstarter.R import com.kickstarter.databinding.SignupLayoutBinding import com.kickstarter.libs.BaseActivity import com.kickstarter.libs.qualifiers.RequiresActivityViewModel import com.kickstarter.libs.utils.SwitchCompatUtils import com.kickstarter.libs.utils.TransitionUtils import com.kickstarter.libs.utils.ViewUtils import com.kickstarter.ui.extensions.hideKeyboard import com.kickstarter.ui.views.LoginPopupMenu import com.kickstarter.viewmodels.SignupViewModel import rx.android.schedulers.AndroidSchedulers @RequiresActivityViewModel(SignupViewModel.ViewModel::class) class SignupActivity : BaseActivity<SignupViewModel.ViewModel>() { private lateinit var binding: SignupLayoutBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = SignupLayoutBinding.inflate(layoutInflater) setContentView(binding.root) binding.loginToolbar.loginToolbar.title = getString(R.string.signup_button) viewModel.outputs.signupSuccess() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { onSuccess() } viewModel.outputs.formSubmitting() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { setFormDisabled(it) } viewModel.outputs.formIsValid() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { setFormEnabled(it) } viewModel.outputs.sendNewslettersIsChecked() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { SwitchCompatUtils.setCheckedWithoutAnimation(binding.signupFormView.newsletterSwitch, it) } viewModel.outputs.errorString() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { ViewUtils.showDialog(this, null, it) } RxView.clicks(binding.signupFormView.newsletterSwitch) .skip(1) .compose(bindToLifecycle()) .subscribe { viewModel .inputs .sendNewslettersClick(binding.signupFormView.newsletterSwitch.isChecked) } binding.signupFormView.disclaimer.setOnClickListener { disclaimerClick() } binding.signupFormView.signupButton.setOnClickListener { signupButtonOnClick() } binding.signupFormView.name.doOnTextChanged { name, _, _, _ -> name?.let { onNameTextChanged(it) } } binding.signupFormView.email.doOnTextChanged { email, _, _, _ -> email?.let { onEmailTextChanged(it) } } binding.signupFormView.password.doOnTextChanged { password, _, _, _ -> password?.let { onPasswordTextChange(it) } } } private fun disclaimerClick() { LoginPopupMenu(this, binding.loginToolbar.helpButton).show() } private fun onNameTextChanged(name: CharSequence) { viewModel.inputs.name(name.toString()) } private fun onEmailTextChanged(email: CharSequence) { viewModel.inputs.email(email.toString()) } private fun onPasswordTextChange(password: CharSequence) { viewModel.inputs.password(password.toString()) } private fun signupButtonOnClick() { viewModel.inputs.signupClick() this.hideKeyboard() } private fun onSuccess() { setResult(RESULT_OK) finish() } private fun setFormEnabled(enabled: Boolean) { binding.signupFormView.signupButton.isEnabled = enabled } private fun setFormDisabled(disabled: Boolean) { setFormEnabled(!disabled) } override fun exitTransition(): Pair<Int, Int>? { return TransitionUtils.slideInFromLeft() } }
app/src/main/java/com/kickstarter/ui/activities/SignupActivity.kt
1323134015
// 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.maddyhome.idea.copyright import com.intellij.configurationStore.SerializableScheme import com.intellij.configurationStore.serializeObjectInto import com.intellij.openapi.components.BaseState import com.intellij.openapi.options.ExternalizableScheme import com.intellij.util.xmlb.annotations.OptionTag import com.intellij.util.xmlb.annotations.Transient import com.maddyhome.idea.copyright.pattern.EntityUtil import org.jdom.Element @JvmField val DEFAULT_COPYRIGHT_NOTICE: String = EntityUtil.encode( "Copyright (c) \$today.year. Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n" + "Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. \n" + "Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. \n" + "Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. \n" + "Vestibulum commodo. Ut rhoncus gravida arcu. ") class CopyrightProfile @JvmOverloads constructor(profileName: String? = null) : ExternalizableScheme, BaseState(), SerializableScheme { // ugly name to preserve compatibility // must be not private because otherwise binding is not created for private accessor @Suppress("MemberVisibilityCanBePrivate") @get:OptionTag("myName") var profileName: String? by string() var notice: String? by string(DEFAULT_COPYRIGHT_NOTICE) var keyword: String? by string(EntityUtil.encode("Copyright")) var allowReplaceRegexp: String? by string() @Deprecated("use allowReplaceRegexp instead", ReplaceWith("")) var allowReplaceKeyword: String? by string() init { // otherwise will be as default value and name will be not serialized this.profileName = profileName } // ugly name to preserve compatibility @Transient override fun getName(): String = profileName ?: "" override fun setName(value: String) { profileName = value } override fun toString(): String = profileName ?: "" override fun writeScheme(): Element { val element = Element("copyright") serializeObjectInto(this, element) return element } }
plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightProfile.kt
428768715
package com.zeke.music.api import com.kingz.base.BaseApiService import com.zeke.music.bean.RelatedVideoInfo import com.zeke.music.bean.VideoInfo import com.zeke.music.bean.VideoListInfo import retrofit2.http.GET import retrofit2.http.Query /** * author:ZekeWang * date:2021/5/14 * description:音乐台数据API接口 */ interface YinYueTaiApiService: BaseApiService { /** * 根据影片类型获取数据 * videoType: * 1:内地 * 2:香港 * 3:台湾 * 4:日韩欧美 * 5:音悦V榜几自制 */ @GET("/video/getTypeVideoList") suspend fun getVideoList(@Query("videoType") type:Int, @Query("pageNum") pageNum:Int, @Query("pageSize") pageSize:Int):VideoListInfo @GET("/video/getVideoInfo") suspend fun getVideoInfo(@Query("id") id:Int): VideoInfo @GET("/video/getRelatedVideoList") suspend fun getRelatedVideoList(@Query("id") id:Int): List<RelatedVideoInfo> }
module-Music/src/main/java/com/zeke/music/api/YinYueTaiApiService.kt
81296859
/* * 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.ch0201 import cc.altruix.econsimtr01.AbstractAccountant import cc.altruix.econsimtr01.IAgent import cc.altruix.econsimtr01.PlResource /** * Created by pisarenko on 11.04.2016. */ class Sim1Accountant(logTarget: StringBuilder, agents: List<IAgent>, resources: List<PlResource>) : AbstractAccountant( logTarget, agents, resources) { }
src/main/java/cc/altruix/econsimtr01/ch0201/Sim1Accountant.kt
2269101819
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.service.ui.util import com.intellij.ide.macro.Macro import com.intellij.ide.macro.MacrosDialog import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.util.NlsContexts interface FileChooserInfo { val fileChooserTitle: @NlsContexts.DialogTitle String? val fileChooserDescription: @NlsContexts.Label String? val fileChooserDescriptor: FileChooserDescriptor val fileChooserMacroFilter: ((Macro) -> Boolean)? companion object { val ALL = { it: Macro -> MacrosDialog.Filters.ALL.test(it) } val NONE = { it: Macro -> MacrosDialog.Filters.NONE.test(it) } val ANY_PATH = { it: Macro -> MacrosDialog.Filters.ANY_PATH.test(it) } val DIRECTORY_PATH = { it: Macro -> MacrosDialog.Filters.DIRECTORY_PATH.test(it) } val FILE_PATH = { it: Macro -> MacrosDialog.Filters.FILE_PATH.test(it) } } }
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/util/FileChooserInfo.kt
2362262215
/* * Copyright (c) 2017 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.android.vmb import android.os.StrictMode import android.os.StrictMode.ThreadPolicy import android.os.StrictMode.VmPolicy import androidx.multidex.MultiDexApplication import io.reactivex.exceptions.OnErrorNotImplementedException import io.reactivex.exceptions.UndeliverableException import io.reactivex.plugins.RxJavaPlugins import net.mm2d.android.vmb.customtabs.CustomTabsHelperHolder import net.mm2d.android.vmb.settings.Settings import net.mm2d.log.Logger import net.mm2d.log.android.AndroidSenders /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ @Suppress("unused") class App : MultiDexApplication() { override fun onCreate() { super.onCreate() setUpLogger() setStrictMode() RxJavaPlugins.setErrorHandler { logError(it) } Settings.initialize(this) CustomTabsHelperHolder.initialize(this) } private fun logError(e: Throwable) { when (e) { is UndeliverableException -> Logger.w(e.cause, "UndeliverableException:") is OnErrorNotImplementedException -> Logger.w(e.cause, "OnErrorNotImplementedException:") else -> Logger.w(e) } } private fun setUpLogger() { if (!BuildConfig.DEBUG) { return } Logger.setSender(AndroidSenders.create()) Logger.setLogLevel(Logger.VERBOSE) AndroidSenders.appendCaller(true) AndroidSenders.appendThread(true) } private fun setStrictMode() { if (BuildConfig.DEBUG) { StrictMode.enableDefaults() } else { StrictMode.setThreadPolicy(ThreadPolicy.LAX) StrictMode.setVmPolicy(VmPolicy.LAX) } } }
app/src/main/java/net/mm2d/android/vmb/App.kt
1080089361
// "Add non-null asserted (!!) call" "true" operator fun Int.get(row: Int, column: Int) = this fun foo(arg: Int?) = arg<caret>[42, 13]
plugins/kotlin/idea/tests/testData/quickfix/expressions/unsafeCall4.kt
1263951692
@file:InternalTestAnnotation package test import test.InternalClass1 // InternalClass1, ClassA1, ClassB1 are in module1 class ClassInheritedFromInternal1: InternalClass1() @InternalClassAnnotation class ClassAA1 : ClassA1(10) class ClassBB1 : ClassB1() { internal override val member = 10 } // InternalClass2, ClassA2, ClassB2 are in module2 class ClassInheritedFromInternal2: InternalClass2() class ClassAA2 : ClassA2(10) class ClassBB2 : ClassB2() { internal override val member = 10 } fun f() { val x1 = ClassAA1().member val x2 = ClassAA2().member }
plugins/kotlin/jps/jps-plugin/tests/testData/general/InternalFromAnotherModule/module2/src/module2.kt
1950757921
package org.penella.store import org.penella.structures.triples.HashTriple import org.penella.structures.triples.Triple /** * 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. * * Created by alisle on 9/27/16. */ interface IStore { fun add(value: String) : Long fun add(triple: Triple) fun get(value: Long) : String? fun get(hashTriple: HashTriple) : Triple? fun generateHash(value: String): Long }
src/main/java/org/penella/store/IStore.kt
1743236589
package com.github.kerubistan.kerub.planner.steps.storage.migrate.dead import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.StorageCapability import com.github.kerubistan.kerub.model.VirtualStorageDevice import com.github.kerubistan.kerub.model.dynamic.VirtualStorageAllocation import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.reservations.Reservation import com.github.kerubistan.kerub.planner.reservations.UseHostReservation import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStep import com.github.kerubistan.kerub.planner.steps.base.AbstractUnAllocate import com.github.kerubistan.kerub.planner.steps.storage.AbstractCreateVirtualStorage abstract class AbstractMigrateAllocation : AbstractOperationalStep { abstract val sourceHost: Host abstract val targetHost: Host abstract val virtualStorage: VirtualStorageDevice abstract val sourceAllocation: VirtualStorageAllocation abstract val allocationStep: AbstractCreateVirtualStorage<out VirtualStorageAllocation, out StorageCapability> abstract val deAllocationStep: AbstractUnAllocate<*> override fun take(state: OperationalState): OperationalState = deAllocationStep.take(allocationStep.take(state.copy())) protected open fun validate() { check(allocationStep.host.id == targetHost.id) { "target allocation step is on ${allocationStep.host.id} ${allocationStep.host.address} " + " - it must be on the target server ${targetHost.id} ${targetHost.address}" } check(deAllocationStep.host.id == sourceHost.id) { "source allocation step is on ${deAllocationStep.host.id} ${deAllocationStep.host.address} " + " - it must be on the target server ${sourceHost.id} ${sourceHost.address}" } check(sourceHost.id != targetHost.id) { "source host must not be the same as target host (${sourceHost.id})" } } override fun reservations(): List<Reservation<*>> = listOf( UseHostReservation(sourceHost), UseHostReservation(targetHost) ) }
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/migrate/dead/AbstractMigrateAllocation.kt
215032377
// "Replace '@JvmField' with 'const'" "false" // WITH_STDLIB // ERROR: JvmField has no effect on a private property // ACTION: Convert to lazy property // ACTION: Add 'const' modifier // ACTION: Make internal // ACTION: Make public // ACTION: Specify type explicitly // ACTION: Add use-site target 'field' // ACTION: Remove @JvmField annotation val three = 3 <caret>@JvmField private val text = "${2 + three}"
plugins/kotlin/idea/tests/testData/quickfix/replaceJvmFieldWithConst/stringTemplateWithVal.kt
3106327933
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.samples import androidx.annotation.Sampled import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.border import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CutCornerShape import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.TileMode import androidx.compose.ui.unit.dp @Composable @Sampled fun BorderSample() { Text( "Text with square border", modifier = Modifier.border(4.dp, Color.Magenta).padding(10.dp) ) } @Composable @Sampled fun BorderSampleWithBrush() { val gradientBrush = Brush.horizontalGradient( colors = listOf(Color.Red, Color.Blue, Color.Green), startX = 0.0f, endX = 500.0f, tileMode = TileMode.Repeated ) Text( "Text with gradient border", modifier = Modifier.border(width = 2.dp, brush = gradientBrush, shape = CircleShape) .padding(10.dp) ) } @Composable @Sampled fun BorderSampleWithDataClass() { Text( "Text with gradient border", modifier = Modifier.border( border = BorderStroke(2.dp, Color.Blue), shape = CutCornerShape(8.dp) ).padding(10.dp) ) }
compose/foundation/foundation/samples/src/main/java/androidx/compose/foundation/samples/BorderSamples.kt
4005337949
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.compiler.plugins.kotlin.inference /** * Call bindings are the binding variables for either a function being inferred or a target of a * call. If a call and the function's call bindings can be unified the call is valid and the * variables bound by the unification contribute to the environment for the any subsequent bindings. * * @param target the binding variable for the call target. * @param parameters the call bindings the lambda parameters (if any). */ class CallBindings( val target: Binding, val parameters: List<CallBindings> = emptyList(), val result: CallBindings?, val anyParameters: Boolean ) { override fun toString(): String { val paramsString = if (parameters.isEmpty()) "" else ", ${ parameters.joinToString(", ") { it.toString() } }" val anyParametersStr = if (anyParameters) "*" else "" val resultString = result?.let { "-> $it" } ?: "" return "[$target$anyParametersStr$paramsString$resultString]" } }
compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/inference/CallBindings.kt
2722927535
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform import androidx.compose.ui.text.AnnotatedString import org.junit.Test import com.google.common.truth.Truth.assertThat class ClipboardManagerTest { @Test fun clipboardManagerWithoutHasText_returnsTrue_withNonEmptyGetText() { val clipboardManager = object : ClipboardManager { override fun setText(annotatedString: AnnotatedString) { } override fun getText() = AnnotatedString("Something") } assertThat(clipboardManager.hasText()).isTrue() } @Test fun clipboardManagerWithoutHasText_returnsFalse_withNullGetText() { val clipboardManager = object : ClipboardManager { override fun setText(annotatedString: AnnotatedString) { } override fun getText() = null } assertThat(clipboardManager.hasText()).isFalse() } @Test fun clipboardManagerWithoutHasText_returnsFalse_withEmptyGetText() { val clipboardManager = object : ClipboardManager { override fun setText(annotatedString: AnnotatedString) { } override fun getText() = AnnotatedString("") } assertThat(clipboardManager.hasText()).isFalse() } }
compose/ui/ui/src/test/kotlin/androidx/compose/ui/platform/ClipboardManagerTest.kt
2748361787
package org.thoughtcrime.securesms.mediasend.v2.text import android.text.Editable import android.text.TextWatcher import android.util.TypedValue import android.view.Gravity import android.widget.EditText import android.widget.TextView import org.signal.core.util.BreakIteratorCompat import org.signal.core.util.DimensionUnit import org.signal.core.util.EditTextUtil import org.thoughtcrime.securesms.util.doOnEachLayout class TextStoryTextWatcher private constructor(private val textView: TextView) : TextWatcher { override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { ensureProperTextSize(textView) } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) = Unit override fun afterTextChanged(s: Editable) = Unit companion object { fun ensureProperTextSize(textView: TextView) { val breakIteratorCompat = BreakIteratorCompat.getInstance() breakIteratorCompat.setText(textView.text) val length = breakIteratorCompat.countBreaks() val expectedTextSize = when { length < 50 -> 34f length < 200 -> 24f else -> 18f } if (expectedTextSize < 24f) { textView.gravity = Gravity.START } else { textView.gravity = Gravity.CENTER } textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, DimensionUnit.DP.toPixels(expectedTextSize)) if (textView !is EditText) { textView.requestLayout() } } fun install(textView: TextView) { val watcher = TextStoryTextWatcher(textView) if (textView is EditText) { EditTextUtil.addGraphemeClusterLimitFilter(textView, 700) } else { textView.doOnEachLayout { val contentHeight = textView.height - textView.paddingTop - textView.paddingBottom if (textView.layout != null && textView.layout.height > contentHeight) { val percentShown = contentHeight / textView.layout.height.toFloat() textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, DimensionUnit.DP.toPixels(18f * percentShown)) } } } textView.addTextChangedListener(watcher) } } }
app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/text/TextStoryTextWatcher.kt
4240379863
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.text.AnnotatedString.Builder import androidx.compose.ui.text.AnnotatedString.Range import androidx.compose.ui.text.intl.LocaleList import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastMap /** * The basic data structure of text with multiple styles. To construct an [AnnotatedString] you * can use [Builder]. */ @Immutable class AnnotatedString internal constructor( val text: String, val spanStyles: List<Range<SpanStyle>> = emptyList(), val paragraphStyles: List<Range<ParagraphStyle>> = emptyList(), internal val annotations: List<Range<out Any>> = emptyList() ) : CharSequence { /** * The basic data structure of text with multiple styles. To construct an [AnnotatedString] * you can use [Builder]. * * @param text the text to be displayed. * @param spanStyles a list of [Range]s that specifies [SpanStyle]s on certain portion of the * text. These styles will be applied in the order of the list. And the [SpanStyle]s applied * later can override the former styles. Notice that [SpanStyle] attributes which are null or * [androidx.compose.ui.unit.TextUnit.Unspecified] won't change the current ones. * @param paragraphStyles a list of [Range]s that specifies [ParagraphStyle]s on certain * portion of the text. Each [ParagraphStyle] with a [Range] defines a paragraph of text. * It's required that [Range]s of paragraphs don't overlap with each other. If there are gaps * between specified paragraph [Range]s, a default paragraph will be created in between. * * @throws IllegalArgumentException if [paragraphStyles] contains any two overlapping [Range]s. * @sample androidx.compose.ui.text.samples.AnnotatedStringConstructorSample * * @see SpanStyle * @see ParagraphStyle */ constructor( text: String, spanStyles: List<Range<SpanStyle>> = listOf(), paragraphStyles: List<Range<ParagraphStyle>> = listOf() ) : this(text, spanStyles, paragraphStyles, listOf()) init { var lastStyleEnd = -1 paragraphStyles.sortedBy { it.start }.fastForEach { paragraphStyle -> require(paragraphStyle.start >= lastStyleEnd) { "ParagraphStyle should not overlap" } require(paragraphStyle.end <= text.length) { "ParagraphStyle range [${paragraphStyle.start}, ${paragraphStyle.end})" + " is out of boundary" } lastStyleEnd = paragraphStyle.end } } override val length: Int get() = text.length override operator fun get(index: Int): Char = text[index] /** * Return a substring for the AnnotatedString and include the styles in the range of [startIndex] * (inclusive) and [endIndex] (exclusive). * * @param startIndex the inclusive start offset of the range * @param endIndex the exclusive end offset of the range */ override fun subSequence(startIndex: Int, endIndex: Int): AnnotatedString { require(startIndex <= endIndex) { "start ($startIndex) should be less or equal to end ($endIndex)" } if (startIndex == 0 && endIndex == text.length) return this val text = text.substring(startIndex, endIndex) return AnnotatedString( text = text, spanStyles = filterRanges(spanStyles, startIndex, endIndex), paragraphStyles = filterRanges(paragraphStyles, startIndex, endIndex), annotations = filterRanges(annotations, startIndex, endIndex) ) } /** * Return a substring for the AnnotatedString and include the styles in the given [range]. * * @param range the text range * * @see subSequence(start: Int, end: Int) */ fun subSequence(range: TextRange): AnnotatedString { return subSequence(range.min, range.max) } @Stable operator fun plus(other: AnnotatedString): AnnotatedString { return with(Builder(this)) { append(other) toAnnotatedString() } } /** * Query the string annotations attached on this AnnotatedString. * Annotations are metadata attached on the AnnotatedString, for example, a URL is a string * metadata attached on the a certain range. Annotations are also store with [Range] like the * styles. * * @param tag the tag of the annotations that is being queried. It's used to distinguish * the annotations for different purposes. * @param start the start of the query range, inclusive. * @param end the end of the query range, exclusive. * @return a list of annotations stored in [Range]. Notice that All annotations that intersect * with the range [start, end) will be returned. When [start] is bigger than [end], an empty * list will be returned. */ @Suppress("UNCHECKED_CAST") fun getStringAnnotations(tag: String, start: Int, end: Int): List<Range<String>> = annotations.fastFilter { it.item is String && tag == it.tag && intersect(start, end, it.start, it.end) } as List<Range<String>> /** * Query all of the string annotations attached on this AnnotatedString. * * @param start the start of the query range, inclusive. * @param end the end of the query range, exclusive. * @return a list of annotations stored in [Range]. Notice that All annotations that intersect * with the range [start, end) will be returned. When [start] is bigger than [end], an empty * list will be returned. */ @Suppress("UNCHECKED_CAST") fun getStringAnnotations(start: Int, end: Int): List<Range<String>> = annotations.fastFilter { it.item is String && intersect(start, end, it.start, it.end) } as List<Range<String>> /** * Query all of the [TtsAnnotation]s attached on this [AnnotatedString]. * * @param start the start of the query range, inclusive. * @param end the end of the query range, exclusive. * @return a list of annotations stored in [Range]. Notice that All annotations that intersect * with the range [start, end) will be returned. When [start] is bigger than [end], an empty * list will be returned. */ @Suppress("UNCHECKED_CAST") fun getTtsAnnotations(start: Int, end: Int): List<Range<TtsAnnotation>> = annotations.fastFilter { it.item is TtsAnnotation && intersect(start, end, it.start, it.end) } as List<Range<TtsAnnotation>> /** * Query all of the [UrlAnnotation]s attached on this [AnnotatedString]. * * @param start the start of the query range, inclusive. * @param end the end of the query range, exclusive. * @return a list of annotations stored in [Range]. Notice that All annotations that intersect * with the range [start, end) will be returned. When [start] is bigger than [end], an empty * list will be returned. */ @ExperimentalTextApi @Suppress("UNCHECKED_CAST") fun getUrlAnnotations(start: Int, end: Int): List<Range<UrlAnnotation>> = annotations.fastFilter { it.item is UrlAnnotation && intersect(start, end, it.start, it.end) } as List<Range<UrlAnnotation>> override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is AnnotatedString) return false if (text != other.text) return false if (spanStyles != other.spanStyles) return false if (paragraphStyles != other.paragraphStyles) return false if (annotations != other.annotations) return false return true } override fun hashCode(): Int { var result = text.hashCode() result = 31 * result + spanStyles.hashCode() result = 31 * result + paragraphStyles.hashCode() result = 31 * result + annotations.hashCode() return result } override fun toString(): String { // AnnotatedString.toString has special value, it converts it into regular String // rather than debug string. return text } /** * The information attached on the text such as a [SpanStyle]. * * @param item The object attached to [AnnotatedString]s. * @param start The start of the range where [item] takes effect. It's inclusive * @param end The end of the range where [item] takes effect. It's exclusive * @param tag The tag used to distinguish the different ranges. It is useful to store custom * data. And [Range]s with same tag can be queried with functions such as [getStringAnnotations]. */ @Immutable data class Range<T>(val item: T, val start: Int, val end: Int, val tag: String) { constructor(item: T, start: Int, end: Int) : this(item, start, end, "") init { require(start <= end) { "Reversed range is not supported" } } } /** * Builder class for AnnotatedString. Enables construction of an [AnnotatedString] using * methods such as [append] and [addStyle]. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderSample * * This class implements [Appendable] and can be used with other APIs that don't know about * [AnnotatedString]s: * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderAppendableSample * * @param capacity initial capacity for the internal char buffer */ class Builder(capacity: Int = 16) : Appendable { private data class MutableRange<T>( val item: T, val start: Int, var end: Int = Int.MIN_VALUE, val tag: String = "" ) { /** * Create an immutable [Range] object. * * @param defaultEnd if the end is not set yet, it will be set to this value. */ fun toRange(defaultEnd: Int = Int.MIN_VALUE): Range<T> { val end = if (end == Int.MIN_VALUE) defaultEnd else end check(end != Int.MIN_VALUE) { "Item.end should be set first" } return Range(item = item, start = start, end = end, tag = tag) } } private val text: StringBuilder = StringBuilder(capacity) private val spanStyles: MutableList<MutableRange<SpanStyle>> = mutableListOf() private val paragraphStyles: MutableList<MutableRange<ParagraphStyle>> = mutableListOf() private val annotations: MutableList<MutableRange<out Any>> = mutableListOf() private val styleStack: MutableList<MutableRange<out Any>> = mutableListOf() /** * Create an [Builder] instance using the given [String]. */ constructor(text: String) : this() { append(text) } /** * Create an [Builder] instance using the given [AnnotatedString]. */ constructor(text: AnnotatedString) : this() { append(text) } /** * Returns the length of the [String]. */ val length: Int get() = text.length /** * Appends the given [String] to this [Builder]. * * @param text the text to append */ fun append(text: String) { this.text.append(text) } @Deprecated( message = "Replaced by the append(Char) method that returns an Appendable. " + "This method must be kept around for binary compatibility.", level = DeprecationLevel.HIDDEN ) @Suppress("FunctionName", "unused") // Set the JvmName to preserve compatibility with bytecode that expects a void return type. @JvmName("append") fun deprecated_append_returning_void(char: Char) { append(char) } /** * Appends [text] to this [Builder] if non-null, and returns this [Builder]. * * If [text] is an [AnnotatedString], all spans and annotations will be copied over as well. * No other subtypes of [CharSequence] will be treated specially. For example, any * platform-specific types, such as `SpannedString` on Android, will only have their text * copied and any other information held in the sequence, such as Android `Span`s, will be * dropped. */ @Suppress("BuilderSetStyle") override fun append(text: CharSequence?): Builder { if (text is AnnotatedString) { append(text) } else { this.text.append(text) } return this } /** * Appends the range of [text] between [start] (inclusive) and [end] (exclusive) to this * [Builder] if non-null, and returns this [Builder]. * * If [text] is an [AnnotatedString], all spans and annotations from [text] between * [start] and [end] will be copied over as well. * No other subtypes of [CharSequence] will be treated specially. For example, any * platform-specific types, such as `SpannedString` on Android, will only have their text * copied and any other information held in the sequence, such as Android `Span`s, will be * dropped. * * @param start The index of the first character in [text] to copy over (inclusive). * @param end The index after the last character in [text] to copy over (exclusive). */ @Suppress("BuilderSetStyle") override fun append(text: CharSequence?, start: Int, end: Int): Builder { if (text is AnnotatedString) { append(text, start, end) } else { this.text.append(text, start, end) } return this } // Kdoc comes from interface method. override fun append(char: Char): Builder { this.text.append(char) return this } /** * Appends the given [AnnotatedString] to this [Builder]. * * @param text the text to append */ fun append(text: AnnotatedString) { val start = this.text.length this.text.append(text.text) // offset every style with start and add to the builder text.spanStyles.fastForEach { addStyle(it.item, start + it.start, start + it.end) } text.paragraphStyles.fastForEach { addStyle(it.item, start + it.start, start + it.end) } text.annotations.fastForEach { annotations.add( MutableRange(it.item, start + it.start, start + it.end, it.tag) ) } } /** * Appends the range of [text] between [start] (inclusive) and [end] (exclusive) to this * [Builder]. All spans and annotations from [text] between [start] and [end] will be copied * over as well. * * @param start The index of the first character in [text] to copy over (inclusive). * @param end The index after the last character in [text] to copy over (exclusive). */ @Suppress("BuilderSetStyle") fun append(text: AnnotatedString, start: Int, end: Int) { val insertionStart = this.text.length this.text.append(text.text, start, end) // offset every style with insertionStart and add to the builder text.getLocalSpanStyles(start, end).fastForEach { addStyle(it.item, insertionStart + it.start, insertionStart + it.end) } text.getLocalParagraphStyles(start, end).fastForEach { addStyle(it.item, insertionStart + it.start, insertionStart + it.end) } text.getLocalAnnotations(start, end).fastForEach { annotations.add( MutableRange( it.item, insertionStart + it.start, insertionStart + it.end, it.tag ) ) } } /** * Set a [SpanStyle] for the given [range]. * * @param style [SpanStyle] to be applied * @param start the inclusive starting offset of the range * @param end the exclusive end offset of the range */ fun addStyle(style: SpanStyle, start: Int, end: Int) { spanStyles.add(MutableRange(item = style, start = start, end = end)) } /** * Set a [ParagraphStyle] for the given [range]. When a [ParagraphStyle] is applied to the * [AnnotatedString], it will be rendered as a separate paragraph. * * @param style [ParagraphStyle] to be applied * @param start the inclusive starting offset of the range * @param end the exclusive end offset of the range */ fun addStyle(style: ParagraphStyle, start: Int, end: Int) { paragraphStyles.add(MutableRange(item = style, start = start, end = end)) } /** * Set an Annotation for the given [range]. * * @param tag the tag used to distinguish annotations * @param annotation the string annotation that is attached * @param start the inclusive starting offset of the range * @param end the exclusive end offset of the range * @see getStringAnnotations * @sample androidx.compose.ui.text.samples.AnnotatedStringAddStringAnnotationSample */ fun addStringAnnotation(tag: String, annotation: String, start: Int, end: Int) { annotations.add(MutableRange(annotation, start, end, tag)) } /** * Set a [TtsAnnotation] for the given [range]. * * @param ttsAnnotation an object that stores text to speech metadata that intended for the * TTS engine. * @param start the inclusive starting offset of the range * @param end the exclusive end offset of the range * @see getStringAnnotations * @sample androidx.compose.ui.text.samples.AnnotatedStringAddStringAnnotationSample */ @ExperimentalTextApi @Suppress("SetterReturnsThis") fun addTtsAnnotation(ttsAnnotation: TtsAnnotation, start: Int, end: Int) { annotations.add(MutableRange(ttsAnnotation, start, end)) } /** * Set a [UrlAnnotation] for the given [range]. URLs may be treated specially by screen * readers, including being identified while reading text with an audio icon or being * summarized in a links menu. * * @param urlAnnotation A [UrlAnnotation] object that stores the URL being linked to. * @param start the inclusive starting offset of the range * @param end the exclusive end offset of the range * @see getStringAnnotations * @sample androidx.compose.ui.text.samples.AnnotatedStringAddStringAnnotationSample */ @ExperimentalTextApi @Suppress("SetterReturnsThis") fun addUrlAnnotation(urlAnnotation: UrlAnnotation, start: Int, end: Int) { annotations.add(MutableRange(urlAnnotation, start, end)) } /** * Applies the given [SpanStyle] to any appended text until a corresponding [pop] is * called. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderPushSample * * @param style SpanStyle to be applied */ fun pushStyle(style: SpanStyle): Int { MutableRange(item = style, start = text.length).also { styleStack.add(it) spanStyles.add(it) } return styleStack.size - 1 } /** * Applies the given [ParagraphStyle] to any appended text until a corresponding [pop] * is called. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderPushParagraphStyleSample * * @param style ParagraphStyle to be applied */ fun pushStyle(style: ParagraphStyle): Int { MutableRange(item = style, start = text.length).also { styleStack.add(it) paragraphStyles.add(it) } return styleStack.size - 1 } /** * Attach the given [annotation] to any appended text until a corresponding [pop] * is called. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderPushStringAnnotationSample * * @param tag the tag used to distinguish annotations * @param annotation the string annotation attached on this AnnotatedString * @see getStringAnnotations * @see Range */ fun pushStringAnnotation(tag: String, annotation: String): Int { MutableRange(item = annotation, start = text.length, tag = tag).also { styleStack.add(it) annotations.add(it) } return styleStack.size - 1 } /** * Attach the given [ttsAnnotation] to any appended text until a corresponding [pop] * is called. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderPushStringAnnotationSample * * @param ttsAnnotation an object that stores text to speech metadata that intended for the * TTS engine. * @see getStringAnnotations * @see Range */ fun pushTtsAnnotation(ttsAnnotation: TtsAnnotation): Int { MutableRange(item = ttsAnnotation, start = text.length).also { styleStack.add(it) annotations.add(it) } return styleStack.size - 1 } /** * Attach the given [UrlAnnotation] to any appended text until a corresponding [pop] * is called. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderPushStringAnnotationSample * * @param urlAnnotation A [UrlAnnotation] object that stores the URL being linked to. * @see getStringAnnotations * @see Range */ @Suppress("BuilderSetStyle") @ExperimentalTextApi fun pushUrlAnnotation(urlAnnotation: UrlAnnotation): Int { MutableRange(item = urlAnnotation, start = text.length).also { styleStack.add(it) annotations.add(it) } return styleStack.size - 1 } /** * Ends the style or annotation that was added via a push operation before. * * @see pushStyle * @see pushStringAnnotation */ fun pop() { check(styleStack.isNotEmpty()) { "Nothing to pop." } // pop the last element val item = styleStack.removeAt(styleStack.size - 1) item.end = text.length } /** * Ends the styles or annotation up to and `including` the [pushStyle] or * [pushStringAnnotation] that returned the given index. * * @param index the result of the a previous [pushStyle] or [pushStringAnnotation] in order * to pop to * * @see pop * @see pushStyle * @see pushStringAnnotation */ fun pop(index: Int) { check(index < styleStack.size) { "$index should be less than ${styleStack.size}" } while ((styleStack.size - 1) >= index) { pop() } } /** * Constructs an [AnnotatedString] based on the configurations applied to the [Builder]. */ fun toAnnotatedString(): AnnotatedString { return AnnotatedString( text = text.toString(), spanStyles = spanStyles.fastMap { it.toRange(text.length) }, paragraphStyles = paragraphStyles.fastMap { it.toRange(text.length) }, annotations = annotations.fastMap { it.toRange(text.length) } ) } } } /** * A helper function used to determine the paragraph boundaries in [MultiParagraph]. * * It reads paragraph information from [AnnotatedString.paragraphStyles] where only some parts of * text has [ParagraphStyle] specified, and unspecified parts(gaps between specified paragraphs) * are considered as default paragraph with default [ParagraphStyle]. * For example, the following string with a specified paragraph denoted by "[]" * "Hello WorldHi!" * [ ] * The result paragraphs are "Hello World" and "Hi!". * * @param defaultParagraphStyle The default [ParagraphStyle]. It's used for both unspecified * default paragraphs and specified paragraph. When a specified paragraph's [ParagraphStyle] has * a null attribute, the default one will be used instead. */ internal fun AnnotatedString.normalizedParagraphStyles( defaultParagraphStyle: ParagraphStyle ): List<Range<ParagraphStyle>> { val length = text.length val paragraphStyles = paragraphStyles var lastOffset = 0 val result = mutableListOf<Range<ParagraphStyle>>() paragraphStyles.fastForEach { (style, start, end) -> if (start != lastOffset) { result.add(Range(defaultParagraphStyle, lastOffset, start)) } result.add(Range(defaultParagraphStyle.merge(style), start, end)) lastOffset = end } if (lastOffset != length) { result.add(Range(defaultParagraphStyle, lastOffset, length)) } // This is a corner case where annotatedString is an empty string without any ParagraphStyle. // In this case, an empty ParagraphStyle is created. if (result.isEmpty()) { result.add(Range(defaultParagraphStyle, 0, 0)) } return result } /** * Helper function used to find the [SpanStyle]s in the given paragraph range and also convert the * range of those [SpanStyle]s to paragraph local range. * * @param start The start index of the paragraph range, inclusive * @param end The end index of the paragraph range, exclusive * @return The list of converted [SpanStyle]s in the given paragraph range */ private fun AnnotatedString.getLocalSpanStyles( start: Int, end: Int ): List<Range<SpanStyle>> { if (start == end) return listOf() // If the given range covers the whole AnnotatedString, return SpanStyles without conversion. if (start == 0 && end >= this.text.length) { return spanStyles } return spanStyles.fastFilter { intersect(start, end, it.start, it.end) } .fastMap { Range( it.item, it.start.coerceIn(start, end) - start, it.end.coerceIn(start, end) - start ) } } /** * Helper function used to find the [ParagraphStyle]s in the given range and also convert the range * of those styles to the local range. * * @param start The start index of the range, inclusive * @param end The end index of the range, exclusive */ private fun AnnotatedString.getLocalParagraphStyles( start: Int, end: Int ): List<Range<ParagraphStyle>> { if (start == end) return listOf() // If the given range covers the whole AnnotatedString, return SpanStyles without conversion. if (start == 0 && end >= this.text.length) { return paragraphStyles } return paragraphStyles.fastFilter { intersect(start, end, it.start, it.end) } .fastMap { Range( it.item, it.start.coerceIn(start, end) - start, it.end.coerceIn(start, end) - start ) } } /** * Helper function used to find the annotations in the given range and also convert the range * of those annotations to the local range. * * @param start The start index of the range, inclusive * @param end The end index of the range, exclusive */ private fun AnnotatedString.getLocalAnnotations( start: Int, end: Int ): List<Range<out Any>> { if (start == end) return listOf() // If the given range covers the whole AnnotatedString, return SpanStyles without conversion. if (start == 0 && end >= this.text.length) { return annotations } return annotations.fastFilter { intersect(start, end, it.start, it.end) } .fastMap { Range( tag = it.tag, item = it.item, start = it.start.coerceIn(start, end) - start, end = it.end.coerceIn(start, end) - start ) } } /** * Helper function used to return another AnnotatedString that is a substring from [start] to * [end]. This will ignore the [ParagraphStyle]s and the resulting [AnnotatedString] will have no * [ParagraphStyle]s. * * @param start The start index of the paragraph range, inclusive * @param end The end index of the paragraph range, exclusive * @return The list of converted [SpanStyle]s in the given paragraph range */ private fun AnnotatedString.substringWithoutParagraphStyles( start: Int, end: Int ): AnnotatedString { return AnnotatedString( text = if (start != end) text.substring(start, end) else "", spanStyles = getLocalSpanStyles(start, end) ) } internal inline fun <T> AnnotatedString.mapEachParagraphStyle( defaultParagraphStyle: ParagraphStyle, crossinline block: ( annotatedString: AnnotatedString, paragraphStyle: Range<ParagraphStyle> ) -> T ): List<T> { return normalizedParagraphStyles(defaultParagraphStyle).fastMap { paragraphStyleRange -> val annotatedString = substringWithoutParagraphStyles( paragraphStyleRange.start, paragraphStyleRange.end ) block(annotatedString, paragraphStyleRange) } } /** * Create upper case transformed [AnnotatedString] * * The uppercase sometimes maps different number of characters. This function adjusts the text * style and paragraph style ranges to transformed offset. * * Note, if the style's offset is middle of the uppercase mapping context, this function won't * transform the character, e.g. style starts from between base alphabet character and accent * character. * * @param localeList A locale list used for upper case mapping. Only the first locale is * effective. If empty locale list is passed, use the current locale instead. * @return A uppercase transformed string. */ fun AnnotatedString.toUpperCase(localeList: LocaleList = LocaleList.current): AnnotatedString { return transform { str, start, end -> str.substring(start, end).toUpperCase(localeList) } } /** * Create lower case transformed [AnnotatedString] * * The lowercase sometimes maps different number of characters. This function adjusts the text * style and paragraph style ranges to transformed offset. * * Note, if the style's offset is middle of the lowercase mapping context, this function won't * transform the character, e.g. style starts from between base alphabet character and accent * character. * * @param localeList A locale list used for lower case mapping. Only the first locale is * effective. If empty locale list is passed, use the current locale instead. * @return A lowercase transformed string. */ fun AnnotatedString.toLowerCase(localeList: LocaleList = LocaleList.current): AnnotatedString { return transform { str, start, end -> str.substring(start, end).toLowerCase(localeList) } } /** * Create capitalized [AnnotatedString] * * The capitalization sometimes maps different number of characters. This function adjusts the * text style and paragraph style ranges to transformed offset. * * Note, if the style's offset is middle of the capitalization context, this function won't * transform the character, e.g. style starts from between base alphabet character and accent * character. * * @param localeList A locale list used for capitalize mapping. Only the first locale is * effective. If empty locale list is passed, use the current locale instead. * Note that, this locale is currently ignored since underlying Kotlin method * is experimental. * @return A capitalized string. */ fun AnnotatedString.capitalize(localeList: LocaleList = LocaleList.current): AnnotatedString { return transform { str, start, end -> if (start == 0) { str.substring(start, end).capitalize(localeList) } else { str.substring(start, end) } } } /** * Create capitalized [AnnotatedString] * * The decapitalization sometimes maps different number of characters. This function adjusts * the text style and paragraph style ranges to transformed offset. * * Note, if the style's offset is middle of the decapitalization context, this function won't * transform the character, e.g. style starts from between base alphabet character and accent * character. * * @param localeList A locale list used for decapitalize mapping. Only the first locale is * effective. If empty locale list is passed, use the current locale instead. * Note that, this locale is currently ignored since underlying Kotlin method * is experimental. * @return A decapitalized string. */ fun AnnotatedString.decapitalize(localeList: LocaleList = LocaleList.current): AnnotatedString { return transform { str, start, end -> if (start == 0) { str.substring(start, end).decapitalize(localeList) } else { str.substring(start, end) } } } /** * The core function of [AnnotatedString] transformation. * * @param transform the transformation method * @return newly allocated transformed AnnotatedString */ internal expect fun AnnotatedString.transform( transform: (String, Int, Int) -> String ): AnnotatedString /** * Pushes [style] to the [AnnotatedString.Builder], executes [block] and then pops the [style]. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderWithStyleSample * * @param style [SpanStyle] to be applied * @param block function to be executed * * @return result of the [block] * * @see AnnotatedString.Builder.pushStyle * @see AnnotatedString.Builder.pop */ inline fun <R : Any> Builder.withStyle( style: SpanStyle, block: Builder.() -> R ): R { val index = pushStyle(style) return try { block(this) } finally { pop(index) } } /** * Pushes [style] to the [AnnotatedString.Builder], executes [block] and then pops the [style]. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderWithStyleSample * * @param style [SpanStyle] to be applied * @param block function to be executed * * @return result of the [block] * * @see AnnotatedString.Builder.pushStyle * @see AnnotatedString.Builder.pop */ inline fun <R : Any> Builder.withStyle( style: ParagraphStyle, crossinline block: Builder.() -> R ): R { val index = pushStyle(style) return try { block(this) } finally { pop(index) } } /** * Pushes an annotation to the [AnnotatedString.Builder], executes [block] and then pops the * annotation. * * @param tag the tag used to distinguish annotations * @param annotation the string annotation attached on this AnnotatedString * @param block function to be executed * * @return result of the [block] * * @see AnnotatedString.Builder.pushStringAnnotation * @see AnnotatedString.Builder.pop */ @ExperimentalTextApi inline fun <R : Any> Builder.withAnnotation( tag: String, annotation: String, crossinline block: Builder.() -> R ): R { val index = pushStringAnnotation(tag, annotation) return try { block(this) } finally { pop(index) } } /** * Pushes an [TtsAnnotation] to the [AnnotatedString.Builder], executes [block] and then pops the * annotation. * * @param ttsAnnotation an object that stores text to speech metadata that intended for the TTS * engine. * @param block function to be executed * * @return result of the [block] * * @see AnnotatedString.Builder.pushStringAnnotation * @see AnnotatedString.Builder.pop */ @ExperimentalTextApi inline fun <R : Any> Builder.withAnnotation( ttsAnnotation: TtsAnnotation, crossinline block: Builder.() -> R ): R { val index = pushTtsAnnotation(ttsAnnotation) return try { block(this) } finally { pop(index) } } /** * Pushes an [UrlAnnotation] to the [AnnotatedString.Builder], executes [block] and then pops the * annotation. * * @param urlAnnotation A [UrlAnnotation] object that stores the URL being linked to. * @param block function to be executed * * @return result of the [block] * * @see AnnotatedString.Builder.pushStringAnnotation * @see AnnotatedString.Builder.pop */ @ExperimentalTextApi inline fun <R : Any> Builder.withAnnotation( urlAnnotation: UrlAnnotation, crossinline block: Builder.() -> R ): R { val index = pushUrlAnnotation(urlAnnotation) return try { block(this) } finally { pop(index) } } /** * Filter the range list based on [Range.start] and [Range.end] to include ranges only in the range * of [start] (inclusive) and [end] (exclusive). * * @param start the inclusive start offset of the text range * @param end the exclusive end offset of the text range */ private fun <T> filterRanges(ranges: List<Range<out T>>, start: Int, end: Int): List<Range<T>> { require(start <= end) { "start ($start) should be less than or equal to end ($end)" } return ranges.fastFilter { intersect(start, end, it.start, it.end) }.fastMap { Range( item = it.item, start = maxOf(start, it.start) - start, end = minOf(end, it.end) - start, tag = it.tag ) } } /** * Create an AnnotatedString with a [spanStyle] that will apply to the whole text. * * @param spanStyle [SpanStyle] to be applied to whole text * @param paragraphStyle [ParagraphStyle] to be applied to whole text */ fun AnnotatedString( text: String, spanStyle: SpanStyle, paragraphStyle: ParagraphStyle? = null ): AnnotatedString = AnnotatedString( text, listOf(Range(spanStyle, 0, text.length)), if (paragraphStyle == null) listOf() else listOf(Range(paragraphStyle, 0, text.length)) ) /** * Create an AnnotatedString with a [paragraphStyle] that will apply to the whole text. * * @param paragraphStyle [ParagraphStyle] to be applied to whole text */ fun AnnotatedString( text: String, paragraphStyle: ParagraphStyle ): AnnotatedString = AnnotatedString( text, listOf(), listOf(Range(paragraphStyle, 0, text.length)) ) /** * Build a new AnnotatedString by populating newly created [AnnotatedString.Builder] provided * by [builder]. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderLambdaSample * * @param builder lambda to modify [AnnotatedString.Builder] */ inline fun buildAnnotatedString(builder: (Builder).() -> Unit): AnnotatedString = Builder().apply(builder).toAnnotatedString() /** * Helper function that checks if the range [baseStart, baseEnd) contains the range * [targetStart, targetEnd). * * @return true if [baseStart, baseEnd) contains [targetStart, targetEnd), vice versa. * When [baseStart]==[baseEnd] it return true iff [targetStart]==[targetEnd]==[baseStart]. */ internal fun contains(baseStart: Int, baseEnd: Int, targetStart: Int, targetEnd: Int) = (baseStart <= targetStart && targetEnd <= baseEnd) && (baseEnd != targetEnd || (targetStart == targetEnd) == (baseStart == baseEnd)) /** * Helper function that checks if the range [lStart, lEnd) intersects with the range * [rStart, rEnd). * * @return [lStart, lEnd) intersects with range [rStart, rEnd), vice versa. */ internal fun intersect(lStart: Int, lEnd: Int, rStart: Int, rEnd: Int) = maxOf(lStart, rStart) < minOf(lEnd, rEnd) || contains(lStart, lEnd, rStart, rEnd) || contains(rStart, rEnd, lStart, lEnd) private val EmptyAnnotatedString: AnnotatedString = AnnotatedString("") /** * Returns an AnnotatedString with empty text and no annotations. */ internal fun emptyAnnotatedString() = EmptyAnnotatedString
compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/AnnotatedString.kt
3636785124
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.google.maps.android.ktx import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.SupportMapFragment import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume /** * A suspending function that provides an instance of a [GoogleMap] from this [SupportMapFragment]. * This is an alternative to using [SupportMapFragment.getMapAsync] by using coroutines to obtain * a [GoogleMap]. * * @return the [GoogleMap] instance */ public suspend inline fun SupportMapFragment.awaitMap(): GoogleMap = suspendCancellableCoroutine { continuation -> getMapAsync { continuation.resume(it) } }
maps-ktx/src/main/java/com/google/maps/android/ktx/SupportMapFragment.kt
1520601053
// 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.codeInsight.hints import com.intellij.codeInsight.hints.presentation.InlayPresentation import org.jetbrains.annotations.Contract import java.awt.Color import java.awt.Point import java.awt.event.MouseEvent import javax.swing.Icon interface InlayPresentationFactory { /** * Text that can be used for elements that ARE valid syntax if they are pasted into file. */ @Contract(pure = true) fun text(text: String) : InlayPresentation /** * Small text should be used for elements which text is not a valid syntax of the file, where this inlay is inserted. * Should be used with [container] to be aligned and properly placed * @return presentation that renders small text */ @Contract(pure = true) fun smallText(text: String) : InlayPresentation /** * @return presentation that wraps existing with borders, background and rounded corners if set * @param padding properties of space between [presentation] and border that is filled with background and has corners * @param roundedCorners properties of rounded corners. If null, corners will have right angle * @param background color of background, if null, no background will be rendered * @param backgroundAlpha value from 0 to 1 of background opacity */ @Contract(pure = true) fun container( presentation: InlayPresentation, padding: Padding? = null, roundedCorners: RoundedCorners? = null, background: Color? = null, backgroundAlpha: Float = 0.55f ) : InlayPresentation /** * @return presentation that renders icon */ @Contract(pure = true) fun icon(icon: Icon) : InlayPresentation /** * @return presentation with given mouse handlers */ @Contract(pure = true) fun mouseHandling(base: InlayPresentation, clickListener: ClickListener?, hoverListener: HoverListener?) : InlayPresentation interface HoverListener { fun onHover(event: MouseEvent, translated: Point) fun onHoverFinished() } fun interface ClickListener { fun onClick(event: MouseEvent, translated: Point) } data class Padding( val left: Int, val right: Int, val top: Int, val bottom: Int ) data class RoundedCorners( val arcWidth: Int, val arcHeight: Int ) @Contract(pure = true) fun smallScaledIcon(icon: Icon): InlayPresentation }
platform/lang-api/src/com/intellij/codeInsight/hints/InlayPresentationFactory.kt
2274573836
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.ui.cloneDialog import org.jetbrains.plugins.github.api.data.GithubRepo import org.jetbrains.plugins.github.api.data.GithubUser import org.jetbrains.plugins.github.authentication.accounts.GithubAccount sealed class GHRepositoryListItem( val account: GithubAccount ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as GHRepositoryListItem if (account != other.account) return false return true } override fun hashCode(): Int { return account.hashCode() } class Repo( account: GithubAccount, val user: GithubUser, val repo: GithubRepo ) : GHRepositoryListItem(account) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false if (!super.equals(other)) return false other as Repo if (user != other.user) return false if (repo != other.repo) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + user.hashCode() result = 31 * result + repo.hashCode() return result } } class Error(account: GithubAccount, val error: Throwable) : GHRepositoryListItem(account) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false if (!super.equals(other)) return false other as Error if (error != other.error) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + error.hashCode() return result } } }
plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHRepositoryListItem.kt
4203543723
package sequentialInlineFunctionCalls inline fun simpleInlineFun() { //Breakpoint! println() } inline fun Any.inlineExt(): Any { //Breakpoint! return this } fun Any.normalExt(): Any { //Breakpoint! return this } inline fun complexInlineFun() { //Breakpoint! 12.inlineExt().normalExt().inlineExt().normalExt() //Breakpoint! 12.normalExt().normalExt() } inline fun nestedInlineFun() { //Breakpoint! simpleInlineFun() //Breakpoint! complexInlineFun() } inline fun doubleNestedInlineFun() { //Breakpoint! nestedInlineFun().inlineExt().normalExt().inlineExt() } fun main() { simpleInlineFun() simpleInlineFun() complexInlineFun() nestedInlineFun() doubleNestedInlineFun() } // RESUME: 36
plugins/kotlin/jvm-debugger/test/testData/stepping/custom/sequentialInlineFunctionCalls.kt
2515319262
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.merge import com.intellij.openapi.util.NlsSafe import git4idea.i18n.GitBundle import org.jetbrains.annotations.Nls enum class GitMergeOption(@NlsSafe val option: String, @Nls val description: String) { NO_FF("--no-ff", GitBundle.message("merge.option.no.ff")), FF_ONLY("--ff-only", GitBundle.message("merge.option.ff.only")), SQUASH("--squash", GitBundle.message("merge.option.squash")), COMMIT_MESSAGE("-m", GitBundle.message("merge.option.msg")), NO_COMMIT("--no-commit", GitBundle.message("merge.option.no.commit")), NO_VERIFY("--no-verify", GitBundle.message("merge.option.no.verify")); fun isOptionSuitable(option: GitMergeOption): Boolean { return when (this) { NO_FF -> option !in NO_FF_INCOMPATIBLE FF_ONLY -> option !in FF_ONLY_INCOMPATIBLE SQUASH -> option !in SQUASH_INCOMPATIBLE COMMIT_MESSAGE -> option !in COMMIT_MSG_INCOMPATIBLE NO_COMMIT -> option != COMMIT_MESSAGE NO_VERIFY -> true } } companion object { private val NO_FF_INCOMPATIBLE = listOf(FF_ONLY, SQUASH) private val FF_ONLY_INCOMPATIBLE = listOf(NO_FF, SQUASH, COMMIT_MESSAGE) private val SQUASH_INCOMPATIBLE = listOf(NO_FF, FF_ONLY, COMMIT_MESSAGE) private val COMMIT_MSG_INCOMPATIBLE = listOf(FF_ONLY, SQUASH, NO_COMMIT) } }
plugins/git4idea/src/git4idea/merge/GitMergeOption.kt
3901529166
// "Import extension function 'Int.ext'" "true" package p open class A { fun Int.ext() {} } object AObject : A() fun usage() { val x: Int = 12 x.<caret>ext() }
plugins/kotlin/idea/tests/testData/quickfix/autoImports/callablesDeclaredInClasses/intTypeExtensionFunctionVariable.kt
836122382
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.test.kotlin.comparison import com.intellij.testFramework.LightProjectDescriptor import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.uast.test.common.kotlin.UastResolveApiFixtureTestBase import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class FE1UastResolveApiFixtureTest : KotlinLightCodeInsightFixtureTestCase(), UastResolveApiFixtureTestBase { override val isFirUastPlugin: Boolean = false override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance() fun testResolveStringFromUast() { checkResolveStringFromUast(myFixture, project) } fun testMultiResolve() { checkMultiResolve(myFixture) } fun testMultiResolveJava() { checkMultiResolveJava(myFixture) } fun testMultiResolveJavaAmbiguous() { checkMultiResolveJavaAmbiguous(myFixture) } fun testResolveFromBaseJava() { checkResolveFromBaseJava(myFixture) } fun testMultiResolveInClass() { checkMultiResolveInClass(myFixture) } fun testResolveToFacade() { checkResolveToFacade(myFixture) } fun testMultiConstructorResolve() { checkMultiConstructorResolve(myFixture, project) } fun testMultiInvokableObjectResolve() { checkMultiInvokableObjectResolve(myFixture) } fun testMultiResolveJvmOverloads() { checkMultiResolveJvmOverloads(myFixture) } fun testLocalResolve() { checkLocalResolve(myFixture) } fun testResolveLocalDefaultConstructor() { checkResolveLocalDefaultConstructor(myFixture) } fun testResolveJavaClassAsAnonymousObjectSuperType() { checkResolveJavaClassAsAnonymousObjectSuperType(myFixture) } fun testResolveCompiledAnnotation() { checkResolveCompiledAnnotation(myFixture) } fun testResolveExplicitLambdaParameter() { checkResolveExplicitLambdaParameter(myFixture) } fun testResolveImplicitLambdaParameter() { checkResolveImplicitLambdaParameter(myFixture) } fun testResolveSyntheticMethod() { checkResolveSyntheticMethod(myFixture) } fun testMapFunctions() { checkMapFunctions(myFixture) } fun testListIterator() { checkListIterator(myFixture) } fun testStringJVM() { checkStringJVM(myFixture) } fun testArgumentMappingDefaultValue() { checkArgumentMappingDefaultValue(myFixture) } fun testArgumentMappingExtensionFunction() { checkArgumentMappingExtensionFunction(myFixture) } fun testArgumentMappingVararg() { checkArgumentMappingVararg(myFixture) } fun testArgumentMappingOOBE() { checkArgumentMappingOOBE(myFixture) } fun testSyntheticEnumMethods() { checkSyntheticEnumMethods(myFixture) } fun testArrayAccessOverloads() { checkArrayAccessOverloads(myFixture) } fun testOperatorOverloads() { checkOperatorOverloads(myFixture) } fun testResolveSyntheticJavaPropertyAccessor() { checkResolveSyntheticJavaPropertyAccessor(myFixture) } fun testResolveKotlinPropertyAccessor() { checkResolveKotlinPropertyAccessor(myFixture) } fun testResolveToSubstituteOverride() { checkResolveToSubstituteOverride(myFixture) } fun testResolveEnumEntrySuperType() { checkResolveEnumEntrySuperType(myFixture) } fun testResolveLambdaInvoke() { checkLambdaInvoke(myFixture) } }
plugins/kotlin/uast/uast-kotlin/tests/test/org/jetbrains/uast/test/kotlin/comparison/FE1UastResolveApiFixtureTest.kt
3558639267
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.run import com.intellij.execution.PsiLocation import com.intellij.execution.RunManager import com.intellij.execution.actions.ConfigurationContext import com.intellij.execution.actions.ConfigurationFromContext import com.intellij.execution.impl.RunManagerImpl import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl import com.intellij.execution.junit.JUnitConfiguration import com.intellij.execution.junit.TestInClassConfigurationProducer import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import com.intellij.refactoring.RefactoringFactory import com.intellij.util.ThrowableRunnable import org.jetbrains.kotlin.idea.junit.KotlinJUnitRunConfigurationProducer import org.jetbrains.kotlin.idea.search.allScope import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR import org.jetbrains.kotlin.idea.test.MockLibraryFacility import org.jetbrains.kotlin.idea.test.runAll import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.psiUtil.findFunctionByName import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class KotlinJUnitRunConfigurationTest : AbstractRunConfigurationTest() { private lateinit var mockLibraryFacility: MockLibraryFacility override fun setUp() { super.setUp() mockLibraryFacility = MockLibraryFacility(testDataDirectory.resolve("mock")) mockLibraryFacility.setUp(module) } override fun tearDown() { runAll( ThrowableRunnable { (RunManager.Companion.getInstance(myProject) as RunManagerImpl).clearAll() }, ThrowableRunnable { mockLibraryFacility.tearDown(module) }, ThrowableRunnable { super.tearDown() } ) } fun testSimple() { configureProject() val configuredModule = configuredModules.single() val testDir = configuredModule.testDir!! val javaFile = testDir.findChild("MyJavaTest.java")!! val kotlinFile = testDir.findChild("MyKotlinTest.kt")!! val javaClassConfiguration = getConfiguration(javaFile, project, "MyTest") assert(javaClassConfiguration.isProducedBy(TestInClassConfigurationProducer::class.java)) assert(javaClassConfiguration.configuration.name == "MyJavaTest") val javaMethodConfiguration = getConfiguration(javaFile, project, "testA") assert(javaMethodConfiguration.isProducedBy(TestInClassConfigurationProducer::class.java)) assert(javaMethodConfiguration.configuration.name == "MyJavaTest.testA") val kotlinClassConfiguration = getConfiguration(kotlinFile, project, "MyKotlinTest") assert(kotlinClassConfiguration.isProducedBy(KotlinJUnitRunConfigurationProducer::class.java)) assert(kotlinClassConfiguration.configuration.name == "MyKotlinTest") val kotlinFunctionConfiguration = getConfiguration(kotlinFile, project, "testA") assert(kotlinFunctionConfiguration.isProducedBy(KotlinJUnitRunConfigurationProducer::class.java)) assert(kotlinFunctionConfiguration.configuration.name == "MyKotlinTest.testA") } fun testRenameKotlinClass() { configureProject(testDirectory = "Simple") val configuredModule = configuredModules.single() val testDir = configuredModule.testDir!! val kotlinFile = testDir.findChild("MyKotlinTest.kt")!! val manager = RunManager.Companion.getInstance(myProject) as RunManagerImpl val kotlinClassConfiguration = getConfiguration(kotlinFile, project, "MyKotlinTest") assert(kotlinClassConfiguration.configuration is JUnitConfiguration) manager.setTemporaryConfiguration(RunnerAndConfigurationSettingsImpl(manager, kotlinClassConfiguration.configuration)) val kotlinFunctionConfiguration = getConfiguration(kotlinFile, project, "testA") assert(kotlinFunctionConfiguration.configuration is JUnitConfiguration) manager.setTemporaryConfiguration(RunnerAndConfigurationSettingsImpl(manager, kotlinFunctionConfiguration.configuration)) val obj = KotlinFullClassNameIndex.getInstance().get("MyKotlinTest", project, project.allScope()).single() val rename = RefactoringFactory.getInstance(project).createRename(obj, "MyBarKotlinTest") rename.run() assert((kotlinClassConfiguration.configuration as JUnitConfiguration).persistentData.MAIN_CLASS_NAME == "MyBarKotlinTest") assert((kotlinFunctionConfiguration.configuration as JUnitConfiguration).persistentData.MAIN_CLASS_NAME == "MyBarKotlinTest") } fun testRenameKotlinMethod() { configureProject(testDirectory = "Simple") val configuredModule = configuredModules.single() val testDir = configuredModule.testDir!! val kotlinFile = testDir.findChild("MyKotlinTest.kt")!! val manager = RunManager.Companion.getInstance(myProject) as RunManagerImpl val kotlinFunctionConfiguration = getConfiguration(kotlinFile, project, "testA") assert(kotlinFunctionConfiguration.configuration is JUnitConfiguration) assert((kotlinFunctionConfiguration.configuration as JUnitConfiguration).persistentData.TEST_OBJECT == JUnitConfiguration.TEST_METHOD) manager.setTemporaryConfiguration(RunnerAndConfigurationSettingsImpl(manager, kotlinFunctionConfiguration.configuration)) val obj: KtClassOrObject = KotlinFullClassNameIndex.getInstance().get("MyKotlinTest", project, project.allScope()).single() val method = (obj as KtClass).findFunctionByName("testA") assert(method != null) val rename = RefactoringFactory.getInstance(project).createRename(method!!, "testA1") rename.run() assert((kotlinFunctionConfiguration.configuration as JUnitConfiguration).persistentData.METHOD_NAME == "testA1") } override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("runConfigurations/junit") } fun getConfiguration(file: VirtualFile, project: Project, pattern: String): ConfigurationFromContext { val psiFile = PsiManager.getInstance(project).findFile(file) ?: error("PsiFile not found for $file") val offset = psiFile.text.indexOf(pattern) val psiElement = psiFile.findElementAt(offset) val location = PsiLocation(psiElement) val context = ConfigurationContext.createEmptyContextForLocation(location) return context.configurationsFromContext.orEmpty().singleOrNull() ?: error("Configuration not found for pattern $pattern") }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/run/KotlinJUnitRunConfigurationTest.kt
1152193327
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.gradlebuild.versioning import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.tasks.wrapper.Wrapper import com.google.gson.Gson import org.gradle.kotlin.dsl.* import java.net.URL class WrapperPlugin : Plugin<Project> { override fun apply(project: Project): Unit = project.run { wrapperUpdateTask("nightly", "nightly") wrapperUpdateTask("rc", "release-candidate") wrapperUpdateTask("current", "current") tasks.withType<Wrapper>().configureEach { val jvmOpts = "-Xmx128m -Dfile.encoding=UTF-8" inputs.property("jvmOpts", jvmOpts) // TODO Do we want to use doLast or a finalizedBy task? doLast { val optsEnvVar = "DEFAULT_JVM_OPTS" scriptFile.writeText(scriptFile.readText().replace("$optsEnvVar=\"\"", "$optsEnvVar=\"$jvmOpts\"")) batchScript.writeText(batchScript.readText().replace("set $optsEnvVar=", "set $optsEnvVar=$jvmOpts")) } } } private fun Project.wrapperUpdateTask(name: String, label: String) { val wrapperTaskName = "${name}Wrapper" val configureWrapperTaskName = "configure${wrapperTaskName.capitalize()}" val wrapperTask = tasks.register(wrapperTaskName, Wrapper::class) { dependsOn(configureWrapperTaskName) group = "wrapper" } // TODO Avoid late configuration tasks.register(configureWrapperTaskName) { doLast { val jsonText = URL("https://services.gradle.org/versions/$label").readText() val versionInfo = Gson().fromJson(jsonText, VersionDownloadInfo::class.java) println("updating wrapper to $label version: ${versionInfo.version} (downloadUrl: ${versionInfo.downloadUrl})") wrapperTask.get().distributionUrl = versionInfo.downloadUrl } } } } private data class VersionDownloadInfo(val version: String, val downloadUrl: String)
buildSrc/subprojects/versioning/src/main/kotlin/org/gradle/gradlebuild/versioning/WrapperPlugin.kt
4029196311
package com.maubis.scarlet.base.notification import android.app.IntentService import android.app.NotificationManager import android.content.Context import android.content.Intent import com.maubis.scarlet.base.config.ApplicationBase import com.maubis.scarlet.base.config.CoreConfig.Companion.notesDb import com.maubis.scarlet.base.support.INTENT_KEY_ACTION import com.maubis.scarlet.base.support.INTENT_KEY_NOTE_ID import com.maubis.scarlet.base.support.utils.throwOrReturn class NotificationIntentService : IntentService("NotificationIntentService") { override fun onHandleIntent(intent: Intent?) { if (intent === null) { return } val context = applicationContext if (context === null) { return } val action = getAction(intent.getStringExtra(INTENT_KEY_ACTION)) if (action === null) { return } val noteId = intent.getIntExtra(INTENT_KEY_NOTE_ID, 0) if (noteId == 0) { return } val note = notesDb.getByID(noteId) if (note === null) { return } when (action) { NoteAction.COPY -> ApplicationBase.instance.noteActions(note).copy(context) NoteAction.SHARE -> ApplicationBase.instance.noteActions(note).share(context) NoteAction.DELETE -> { ApplicationBase.instance.noteActions(note).softDelete(context) val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(note.uid) } } } private fun getAction(action: String?): NoteAction? { if (action === null) { return null } try { return NoteAction.valueOf(action) } catch (exception: Exception) { return throwOrReturn(exception, null) } } enum class NoteAction { COPY, SHARE, DELETE, } }
base/src/main/java/com/maubis/scarlet/base/notification/NotificationIntentService.kt
1843026132
package com.github.kerubistan.kerub.planner.steps.storage.lvm.pool.extend import com.github.kerubistan.kerub.data.config.HostConfigurationDao import com.github.kerubistan.kerub.data.dynamic.HostDynamicDao import com.github.kerubistan.kerub.host.HostCommandExecutor import com.github.kerubistan.kerub.model.LvmStorageCapability import com.github.kerubistan.kerub.testHost import com.github.kerubistan.kerub.testHostCapabilities import com.github.kerubistan.kerub.toInputStream import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doAnswer import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import io.github.kerubistan.kroki.size.GB import io.github.kerubistan.kroki.size.TB import org.apache.commons.io.input.NullInputStream import org.apache.sshd.client.channel.ChannelExec import org.apache.sshd.client.future.OpenFuture import org.apache.sshd.client.session.ClientSession import org.junit.Test import java.math.BigInteger import kotlin.test.assertEquals class ExtendLvmPoolExecutorTest { private val hostCommandExecutor: HostCommandExecutor = mock() private val hostConfigDao: HostConfigurationDao = mock() private val hostDynDao: HostDynamicDao = mock() @Test fun update() { val host = testHost.copy( capabilities = testHostCapabilities.copy( storageCapabilities = listOf( LvmStorageCapability( volumeGroupName = "test-vg", size = 2.TB, physicalVolumes = mapOf("/dev/sda" to 1.TB, "/dev/sdb" to 1.TB) ) ) ) ) //TODO can't mock hostDynDao.update() ExtendLvmPoolExecutor(hostCommandExecutor, hostConfigDao, hostDynDao).update( ExtendLvmPool(host = host, vgName = "test-vg", pool = "test-pool", addSize = 10.GB), 1.TB to 128.GB ) //TODO and then there is nothing to verify } @Test fun perform() { val clientSession = mock<ClientSession>() val channel : ChannelExec = mock() val future : OpenFuture = mock() whenever(clientSession.createExecChannel(any())).thenReturn(channel) whenever(channel.open()).thenReturn(future) whenever(channel.invertedErr).then { NullInputStream(0) } whenever(channel.invertedOut).then { "".toInputStream() } .then { """uPPT5K-Rtym-cxQX-f3iu-oiZf-M4Z3-t8v4We:test-vg:4286578688B:1065353216B:1022:254 """.toInputStream() }.then { """test-vg:la6xp4-En1K-fkhX-0Zus-PWp7-1cat-mBXKUk:test-pool::21474836480B:::thin,pool:0.00 """.toInputStream() } doAnswer { val callback = it.arguments[1] as (ClientSession) -> Pair<BigInteger, BigInteger> callback(clientSession) } .whenever(hostCommandExecutor) .execute(eq(testHost), any<(ClientSession) -> Pair<BigInteger, BigInteger>>()) val updates = ExtendLvmPoolExecutor(hostCommandExecutor, hostConfigDao, hostDynDao).perform( ExtendLvmPool(host = testHost, vgName = "test-vg", pool = "test-pool", addSize = 10.GB) ) verify(hostCommandExecutor).execute(eq(testHost), any<(ClientSession) -> Pair<BigInteger, BigInteger>>()) assertEquals(1065353216.toBigInteger(), updates.first) assertEquals(21474836480.toBigInteger(), updates.second) } }
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/lvm/pool/extend/ExtendLvmPoolExecutorTest.kt
3959972159
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi import com.intellij.codeInsight.completion.CompletionUtilCoreImpl import com.intellij.lang.jvm.JvmModifier import com.intellij.model.search.SearchService import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.DumbService import com.intellij.openapi.util.Key import com.intellij.patterns.ElementPattern import com.intellij.patterns.uast.UExpressionPattern import com.intellij.patterns.uast.injectionHostUExpression import com.intellij.psi.impl.cache.CacheManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.PsiSearchHelper.SearchCostResult import com.intellij.psi.search.UsageSearchContext import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValueProvider.Result import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.util.ProcessingContext import com.intellij.util.containers.ContainerUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* internal class UastReferenceByUsageAdapter(private val usagePattern: ElementPattern<out UElement>, private val provider: UastReferenceProvider) : UastReferenceProvider(UExpression::class.java) { override fun acceptsTarget(target: PsiElement): Boolean { return provider.acceptsTarget(target) } override fun getReferencesByElement(element: UElement, context: ProcessingContext): Array<PsiReference> { val parentVariable = when (val uastParent = getOriginalUastParent(element)) { is UVariable -> uastParent is UPolyadicExpression -> uastParent.uastParent as? UVariable // support .withUastParentOrSelf() patterns else -> null } if (parentVariable == null || parentVariable.name.isNullOrEmpty() || !parentVariable.type.equalsToText(CommonClassNames.JAVA_LANG_STRING)) { return PsiReference.EMPTY_ARRAY } val usage = getDirectVariableUsages(parentVariable).find { usage -> val refExpression = getUsageReferenceExpressionWithCache(usage, context) refExpression != null && usagePattern.accepts(refExpression, context) } ?: return PsiReference.EMPTY_ARRAY context.put(USAGE_PSI_ELEMENT, usage) return provider.getReferencesByElement(element, context) } override fun toString(): String = "uastReferenceByUsageAdapter($provider)" } @ApiStatus.Experimental fun uInjectionHostInVariable(): UExpressionPattern<*, *> = injectionHostUExpression().filter { it.uastParent is UVariable } @ApiStatus.Experimental fun uExpressionInVariable(): UExpressionPattern<*, *> = injectionHostUExpression().filter { val parent = it.uastParent parent is UVariable || (parent is UPolyadicExpression && parent.uastParent is UVariable) } private val USAGE_REFERENCE_EXPRESSION: Key<UReferenceExpression> = Key.create("uast.referenceExpressions.byUsage") private fun getUsageReferenceExpressionWithCache(usage: PsiElement, context: ProcessingContext): UReferenceExpression? { val cachedElement = context.sharedContext.get(USAGE_REFERENCE_EXPRESSION, usage) if (cachedElement != null) return cachedElement val newElement = usage.toUElementOfType<UReferenceExpression>() if (newElement != null) { context.sharedContext.put(USAGE_REFERENCE_EXPRESSION, usage, newElement) } return newElement } private fun getOriginalUastParent(element: UElement): UElement? { // Kotlin sends non-original element on completion val src = element.sourcePsi ?: return null val original = CompletionUtilCoreImpl.getOriginalElement(src) ?: src return original.toUElement()?.uastParent } private fun getDirectVariableUsages(uVar: UVariable): Sequence<PsiElement> { val variablePsi = uVar.sourcePsi ?: return emptySequence() val project = variablePsi.project if (DumbService.isDumb(project)) return emptySequence() // do not try to search in dumb mode val cachedValue = CachedValuesManager.getManager(project).getCachedValue(variablePsi, CachedValueProvider { val anchors = findDirectVariableUsages(variablePsi).map(PsiAnchor::create) Result.createSingleDependency(anchors, PsiModificationTracker.MODIFICATION_COUNT) }) return cachedValue.asSequence().mapNotNull(PsiAnchor::retrieve) } private const val MAX_FILES_TO_FIND_USAGES: Int = 5 private val STRICT_CONSTANT_NAME_PATTERN: Regex = Regex("[\\p{Upper}_0-9]+") private fun findDirectVariableUsages(variablePsi: PsiElement): Iterable<PsiElement> { val uVariable = variablePsi.toUElementOfType<UVariable>() val variableName = uVariable?.name if (variableName.isNullOrEmpty()) return emptyList() val currentFile = variablePsi.containingFile ?: return emptyList() val localUsages = findVariableUsages(variablePsi, variableName, arrayOf(currentFile)) // non-local searches are limited for real-life use cases, we do not try to find all possible usages if (uVariable is ULocalVariable || (variablePsi is PsiModifierListOwner && variablePsi.hasModifier(JvmModifier.PRIVATE)) || !STRICT_CONSTANT_NAME_PATTERN.matches(variableName)) { return localUsages } val module = ModuleUtilCore.findModuleForPsiElement(variablePsi) ?: return localUsages val uastScope = getUastScope(module.moduleScope) val searchHelper = PsiSearchHelper.getInstance(module.project) if (searchHelper.isCheapEnoughToSearch(variableName, uastScope, currentFile, null) != SearchCostResult.FEW_OCCURRENCES) { return localUsages } val cacheManager = CacheManager.getInstance(variablePsi.project) val containingFiles = cacheManager.getVirtualFilesWithWord( variableName, UsageSearchContext.IN_CODE, uastScope, true) val useScope = variablePsi.useScope val psiManager = PsiManager.getInstance(module.project) val filesToSearch = containingFiles.asSequence() .filter { useScope.contains(it) && it != currentFile.virtualFile } .mapNotNull { psiManager.findFile(it) } .sortedBy { it.virtualFile.canonicalPath } .take(MAX_FILES_TO_FIND_USAGES) .toList() .toTypedArray() val nonLocalUsages = findVariableUsages(variablePsi, variableName, filesToSearch) return ContainerUtil.concat(localUsages, nonLocalUsages) } private fun findVariableUsages(variablePsi: PsiElement, variableName: String, files: Array<PsiFile>): List<PsiElement> { if (files.isEmpty()) return emptyList() return SearchService.getInstance() .searchWord(variablePsi.project, variableName) .inScope(LocalSearchScope(files, null, true)) .buildQuery { (_, occurrencePsi, _) -> val uRef = occurrencePsi.findContaining(UReferenceExpression::class.java) val expressionType = uRef?.getExpressionType() if (expressionType != null && expressionType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) { val occurrenceResolved = uRef.tryResolve() if (occurrenceResolved != null && PsiManager.getInstance(occurrencePsi.project).areElementsEquivalent(occurrenceResolved, variablePsi)) { return@buildQuery listOfNotNull(uRef.sourcePsi) } } emptyList<PsiElement>() } .findAll() .sortedWith(compareBy({ it.containingFile?.virtualFile?.canonicalPath ?: "" }, { it.textOffset })) } private fun getUastScope(originalScope: GlobalSearchScope): GlobalSearchScope { val fileTypes = UastLanguagePlugin.getInstances().map { it.language.associatedFileType }.toTypedArray() return GlobalSearchScope.getScopeRestrictedByFileTypes(originalScope, *fileTypes) }
uast/uast-common/src/com/intellij/psi/UastReferenceByUsageAdapter.kt
322738616
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING import com.intellij.codeInspection.ProblemHighlightType.INFORMATION import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor import org.jetbrains.kotlin.idea.base.psi.getLineCount import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isElseIf import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class LiftReturnOrAssignmentInspection @JvmOverloads constructor(private val skipLongExpressions: Boolean = true) : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = object : KtVisitorVoid() { override fun visitExpression(expression: KtExpression) { val states = getState(expression, skipLongExpressions) ?: return if (expression.isUsedAsExpression(expression.analyze(BodyResolveMode.PARTIAL_WITH_CFA))) return states.forEach { state -> registerProblem( expression, state.keyword, state.isSerious, when (state.liftType) { LiftType.LIFT_RETURN_OUT -> LiftReturnOutFix(state.keyword.text) LiftType.LIFT_ASSIGNMENT_OUT -> LiftAssignmentOutFix(state.keyword.text) }, state.highlightElement, state.highlightType ) } } private fun registerProblem( expression: KtExpression, keyword: PsiElement, isSerious: Boolean, fix: LocalQuickFix, highlightElement: PsiElement = keyword, highlightType: ProblemHighlightType = if (isSerious) GENERIC_ERROR_OR_WARNING else INFORMATION ) { val subject = if (fix is LiftReturnOutFix) KotlinBundle.message("text.Return") else KotlinBundle.message("text.Assignment") holder.registerProblemWithoutOfflineInformation( expression, KotlinBundle.message("0.1.be.lifted.out.of.2", subject, keyword.text), isOnTheFly, highlightType, highlightElement.textRange?.shiftRight(-expression.startOffset), fix ) } } private class LiftReturnOutFix(private val keyword: String) : LocalQuickFix { override fun getName() = KotlinBundle.message("lift.return.out.fix.text.0", keyword) override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val replaced = BranchedFoldingUtils.foldToReturn(descriptor.psiElement as KtExpression) replaced.findExistingEditor()?.caretModel?.moveToOffset(replaced.startOffset) } } private class LiftAssignmentOutFix(private val keyword: String) : LocalQuickFix { override fun getName() = KotlinBundle.message("lift.assignment.out.fix.text.0", keyword) override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { BranchedFoldingUtils.tryFoldToAssignment(descriptor.psiElement as KtExpression) } } companion object { private const val LINES_LIMIT = 15 fun getState(expression: KtExpression, skipLongExpressions: Boolean) = when (expression) { is KtWhenExpression -> getStateForWhenOrTry(expression, expression.whenKeyword, skipLongExpressions) is KtIfExpression -> getStateForWhenOrTry(expression, expression.ifKeyword, skipLongExpressions) is KtTryExpression -> expression.tryKeyword?.let { getStateForWhenOrTry(expression, it, skipLongExpressions) } else -> null } private fun getStateForWhenOrTry( expression: KtExpression, keyword: PsiElement, skipLongExpressions: Boolean ): List<LiftState>? { if (skipLongExpressions && expression.getLineCount() > LINES_LIMIT) return null if (expression.isElseIf()) return null val foldableReturns = BranchedFoldingUtils.getFoldableReturns(expression) if (foldableReturns?.isNotEmpty() == true) { val hasOtherReturns = expression.anyDescendantOfType<KtReturnExpression> { it !in foldableReturns } val isSerious = !hasOtherReturns && foldableReturns.size > 1 return foldableReturns.map { LiftState(keyword, isSerious, LiftType.LIFT_RETURN_OUT, it, INFORMATION) } + LiftState(keyword, isSerious, LiftType.LIFT_RETURN_OUT) } val assignmentNumber = BranchedFoldingUtils.getFoldableAssignmentNumber(expression) if (assignmentNumber > 0) { val isSerious = assignmentNumber > 1 return listOf(LiftState(keyword, isSerious, LiftType.LIFT_ASSIGNMENT_OUT)) } return null } enum class LiftType { LIFT_RETURN_OUT, LIFT_ASSIGNMENT_OUT } data class LiftState( val keyword: PsiElement, val isSerious: Boolean, val liftType: LiftType, val highlightElement: PsiElement = keyword, val highlightType: ProblemHighlightType = if (isSerious) GENERIC_ERROR_OR_WARNING else INFORMATION ) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/LiftReturnOrAssignmentInspection.kt
738856455
// 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.ui.laf import com.intellij.openapi.util.SystemInfo import java.awt.Component import java.awt.event.MouseEvent internal class MouseDragSelectionEventHandler(private val mouseDraggedOriginal: (MouseEvent) -> Unit) { var isNativeSelectionEnabled = false fun mouseDragged(e: MouseEvent) { when (dragSelectionMode()) { DragSelectionMode.ORIGINAL -> mouseDraggedOriginal(e) DragSelectionMode.WINDOWS -> mouseDraggedWindows(e) DragSelectionMode.UNIX -> mouseDraggedUnix(e) } } private fun dragSelectionMode(): DragSelectionMode = when { !isNativeSelectionEnabled -> DragSelectionMode.ORIGINAL SystemInfo.isWindows -> DragSelectionMode.WINDOWS else -> DragSelectionMode.UNIX } private enum class DragSelectionMode { ORIGINAL, WINDOWS, UNIX } private fun mouseDraggedWindows(e: MouseEvent) { // Pretend the mouse always moves horizontally, // as this is what Windows users generally expect. mouseDragged(e, e.x, e.sourceHeight?.div(2) ?: e.y) } private fun mouseDraggedUnix(e: MouseEvent) { val height = e.sourceHeight val width = e.sourceWidth if (height == null || width == null) { // A next-to-impossible scenario, fall back to original behavior. mouseDraggedOriginal(e) return } // In case of the mouse cursor moved above or below the component, // imitate fast selection by moving the mouse cursor far away horizontally either left or right. val normalizedY = height / 2 when { e.y < 0 -> mouseDragged(e, -OMG_ITS_OVER_9000, normalizedY) e.y > height -> mouseDragged(e, width + OMG_ITS_OVER_9000, normalizedY) else -> mouseDragged(e, e.x, e.y) } } private val MouseEvent.sourceWidth: Int? get() = (source as? Component)?.width private val MouseEvent.sourceHeight: Int? get() = (source as? Component)?.height private fun mouseDragged(e: MouseEvent, x: Int, y: Int) { val originalX = e.x val originalY = e.y e.translatePoint(x - originalX, y - originalY) try { mouseDraggedOriginal(e) } finally { e.translatePoint(originalX - x, originalY - y) } } } private const val OMG_ITS_OVER_9000 = 9999
platform/platform-impl/src/com/intellij/ide/ui/laf/MouseDragSelectionEventHandler.kt
502772499
// 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.editor.tables import com.intellij.testFramework.LightPlatformCodeInsightTestCase import com.intellij.testFramework.RegistryKeyRule import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) @Suppress("MarkdownIncorrectTableFormatting") class MarkdownTableColumnShrinkTest: LightPlatformCodeInsightTestCase() { @get:Rule val rule = RegistryKeyRule("markdown.tables.editing.support.enable", true) @Test fun `test right after cell content`() { // language=Markdown doTest( """ | none | none | |-------|------| | a <caret> | asd | """.trimIndent(), """ | none | none | |------|------| | a<caret> | asd | """.trimIndent() ) } @Test fun `test between spaces on the right side`() { // language=Markdown doTest( """ | none | none | |-------|------| | a <caret> | asd | """.trimIndent(), """ | none | none | |------|------| | a <caret> | asd | """.trimIndent() ) } @Test fun `test just before right pipe`() { // language=Markdown doTest( """ | none | none | |-------|------| | a <caret>| asd | """.trimIndent(), """ | none | none | |------|------| | a <caret>| asd | """.trimIndent() ) } @Test fun `test right before cell content`() { // language=Markdown doTest( """ | none | none | |-------|------| | <caret>a | asd | """.trimIndent(), """ | none | none | |------|------| | <caret>a | asd | """.trimIndent() ) } @Test fun `test just after left pipe`() { // language=Markdown doTest( """ | none | none | |-------|------| | <caret> a | asd | """.trimIndent(), """ | none | none | |------|------| |<caret> a | asd | """.trimIndent() ) } @Test fun `test in separator`() { doTest( """ | none | none | |---<caret>----|------| | a | asd | """.trimIndent(), """ | none | none | |--<caret>----|------| | a | asd | """.trimIndent() ) } @Test fun `test in separator with colon`() { doTest( """ | none | none | |:<caret>------|------| | a | asd | """.trimIndent(), """ | none | none | |<caret>------|------| | a | asd | """.trimIndent() ) } private fun doTest(content: String, expected: String, count: Int = 1) { TableTestUtils.runWithChangedSettings(project) { configureFromFileText("some.md", content) repeat(count) { backspace() } checkResultByText(expected) } } }
plugins/markdown/test/src/org/intellij/plugins/markdown/editor/tables/MarkdownTableColumnShrinkTest.kt
4022670345
@file:SuppressLint("RestrictedApi") package com.okta.oidc.clients import android.annotation.SuppressLint internal val AuthAPI.isCancelled get() = mCancel.get() internal fun AuthAPI.resetCurrentStateInt() = resetCurrentState()
gto-support-okta/src/main/kotlin/com/okta/oidc/clients/AuthAPIInternals.kt
3478891822
package foo fun mainJdk8(x: List<String>, j6List: Jdk6List<String>) { x.stream().filter { it.length > 0 } j6List.size // TODO: stream should be available j6List.stream() buildList().stream() }
plugins/kotlin/idea/tests/testData/multiModuleHighlighting/differentJdk/jdk8/main.kt
2948999847
// 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.propertyBased import com.intellij.lang.Language import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.roots.impl.PushedFilePropertiesUpdater import com.intellij.openapi.util.Conditions import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiManager import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.impl.source.PostprocessReformattingAspect import com.intellij.psi.impl.source.PsiFileImpl import com.intellij.testFramework.fixtures.CodeInsightTestFixture import com.intellij.util.FileContentUtilCore import com.intellij.util.indexing.FileBasedIndex import com.intellij.util.indexing.FileBasedIndexImpl import com.intellij.util.ref.GCUtil import org.junit.Assert.fail object PsiIndexConsistencyTester { val commonRefs: List<RefKind> = listOf(RefKind.PsiFileRef, RefKind.DocumentRef, RefKind.DirRef, RefKind.AstRef(null), RefKind.StubRef(null), RefKind.GreenStubRef(null)) val commonActions: List<Action> = listOf(Action.Commit, Action.FlushIndexes, Action.Gc, Action.ReparseFile, Action.FilePropertiesChanged, Action.ReloadFromDisk, Action.Reformat, Action.PostponedFormatting, Action.RenamePsiFile, Action.RenameVirtualFile, Action.Save) fun refActions(refs: List<RefKind>): Iterable<Action> = refs.flatMap { listOf(Action.LoadRef(it), Action.ClearRef(it)) } fun runActions(model: Model, vararg actions: Action) { WriteCommandAction.runWriteCommandAction(model.project) { try { actions.forEach { it.performAction(model) } } finally { try { Action.Save.performAction(model) model.vFile.delete(this) } catch (e: Throwable) { e.printStackTrace() } } } } open class Model(val vFile: VirtualFile, val fixture: CodeInsightTestFixture) { val refs = hashMapOf<RefKind, Any?>() val project = fixture.project!! fun findPsiFile(language: Language? = null) = findViewProvider().let { vp -> vp.getPsi(language ?: vp.baseLanguage) }!! private fun findViewProvider() = PsiManager.getInstance(project).findViewProvider(vFile)!! fun getDocument() = FileDocumentManager.getInstance().getDocument(vFile)!! fun isCommitted(): Boolean { val document = FileDocumentManager.getInstance().getCachedDocument(vFile) return document == null || PsiDocumentManager.getInstance(project).isCommitted(document) } open fun onCommit() {} open fun onReload() {} open fun onSave() {} } interface Action { fun performAction(model: Model) abstract class SimpleAction: Action { override fun toString(): String = javaClass.simpleName } object FlushIndexes: SimpleAction() { override fun performAction(model: Model) { (FileBasedIndex.getInstance() as FileBasedIndexImpl).flushIndexes() } } object Gc: SimpleAction() { override fun performAction(model: Model) = GCUtil.tryGcSoftlyReachableObjects() } object Commit: SimpleAction() { override fun performAction(model: Model) { PsiDocumentManager.getInstance(model.project).commitAllDocuments() model.onCommit() } } object Save: SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) FileDocumentManager.getInstance().saveAllDocuments() model.onSave() } } object PostponedFormatting: SimpleAction() { override fun performAction(model: Model) = PostprocessReformattingAspect.getInstance(model.project).doPostponedFormatting() } object ReparseFile : SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) FileContentUtilCore.reparseFiles(model.vFile) } } object FilePropertiesChanged : SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) PushedFilePropertiesUpdater.getInstance(model.project).filePropertiesChanged(model.vFile, Conditions.alwaysTrue()) } } object ReloadFromDisk : SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) PsiManager.getInstance(model.project).reloadFromDisk(model.findPsiFile()) model.onReload() if (model.isCommitted()) { model.onCommit() } } } object RenameVirtualFile: SimpleAction() { override fun performAction(model: Model) { model.vFile.rename(this, model.vFile.nameWithoutExtension + "1." + model.vFile.extension) } } object RenamePsiFile: SimpleAction() { override fun performAction(model: Model) { val newName = model.vFile.nameWithoutExtension + "1." + model.vFile.extension model.findPsiFile().name = newName assert(model.findPsiFile().name == newName) assert(model.vFile.name == newName) } } object Reformat: SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) Commit.performAction(model) CodeStyleManager.getInstance(model.project).reformat(model.findPsiFile()) } } data class LoadRef(val kind: RefKind): Action { override fun performAction(model: Model) { val oldValue = model.refs[kind] val newValue = kind.loadRef(model) if (oldValue !== null && newValue !== null && oldValue !== newValue) { kind.checkDuplicates(oldValue, newValue) } model.refs[kind] = newValue } } data class ClearRef(val kind: RefKind): Action { override fun performAction(model: Model) { model.refs.remove(kind) } } data class SetDocumentText(val text: String): Action { override fun performAction(model: Model) { PostponedFormatting.performAction(model) model.getDocument().setText(text) } } data class SetFileText(val text: String): Action { override fun performAction(model: Model) { PostponedFormatting.performAction(model) Save.performAction(model) VfsUtil.saveText(model.vFile, text) } } } abstract class RefKind { abstract fun loadRef(model: Model): Any? open fun checkDuplicates(oldValue: Any, newValue: Any) { if (oldValue is PsiElement && oldValue.isValid && newValue is PsiElement) { fail("Duplicate PSI elements: $oldValue and $newValue") } } object PsiFileRef : RefKind() { override fun loadRef(model: Model): Any? = model.findPsiFile() } object DocumentRef : RefKind() { override fun loadRef(model: Model): Any? = model.getDocument() } object DirRef : RefKind() { override fun loadRef(model: Model): Any? = model.findPsiFile().containingDirectory } data class AstRef(val language: Language?) : RefKind() { override fun loadRef(model: Model): Any? = model.findPsiFile(language).node } data class StubRef(val language: Language?) : RefKind() { override fun loadRef(model: Model): Any? = (model.findPsiFile(language) as PsiFileImpl).stubTree } data class GreenStubRef(val language: Language?) : RefKind() { override fun loadRef(model: Model): Any? = (model.findPsiFile(language) as PsiFileImpl).greenStubTree } } }
platform/testFramework/src/com/intellij/testFramework/propertyBased/PsiIndexConsistencyTester.kt
4011498439
// "Create class 'A'" "true" // ERROR: Unresolved reference: A import J.<caret>A class X { }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/importDirective/classWithJavaQualifier.before.Main.kt
907313389
// PROBLEM: none val x = 2.<caret>equals("")
plugins/kotlin/idea/tests/testData/inspectionsLocal/conventionNameCalls/replaceCallWithBinaryOperator/equalsBetweenInconvertibleTypes.kt
1883179323
interface First { fun foo123() fun foo12_() fun foo1_3() fun foo_23() val bar123: String val bar12_: String val bar1_3: String val bar_23: String fun foo1__() fun foo_2_() fun foo__3() val bar1__: String val bar_2_: String val bar__3: String fun foo___() val bar___: String } abstract class A1 : First { override fun foo123() {} override fun foo12_() {} override fun foo1_3() {} override val bar123 = "test" override val bar12_ = "test" override val bar1_3 = "test" override fun foo1__() {} override val bar1__ = "test" } abstract class A2 : A1() { override fun foo123() {} override fun foo12_() {} override fun foo_23() {} override val bar123 = "test" override val bar12_ = "test" override val bar_23 = "test" override fun foo_2_() {} override val bar_2_ = "test" } open class A3 : A2() { override fun foo123() {} override fun foo1_3() {} override fun foo_23() {} override val bar123 = "test" override val bar1_3 = "test" override val bar_23 = "test" override fun foo__3() {} override val bar__3 = "test" }
plugins/kotlin/idea/tests/testData/structureView/fileStructure/CheckLocationForKotlin.Data.kt
2421861214