content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.chiclaim.jetpack.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import com.chiclaim.jetpack.bean.Contributor import com.chiclaim.jetpack.calladapter.LiveDataCallAdapterFactory import com.chiclaim.jetpack.repository.Github import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class GithubViewModel : ViewModel() { private val retrofit: Retrofit = Retrofit.Builder() .baseUrl("https://api.github.com") .addCallAdapterFactory(LiveDataCallAdapterFactory()) .addConverterFactory(GsonConverterFactory.create()) .build() private var githubService: Github = retrofit.create(Github::class.java) fun getContributors(owner: String?, repo: String?): LiveData<List<Contributor?>?>? { return githubService.contributors(owner, repo) } }
android-archietecture/jetpack/jetpack-sample/app/src/main/java/com/chiclaim/jetpack/viewmodel/GithubViewModel.kt
1433485971
package lt.markmerkk.widgets.help.html class StyledText { private val mutableStyles: MutableList<StyleElement> = mutableListOf() fun elements(): List<StyleElement> { return mutableStyles .filter { it.text.isNotEmpty() } .toList() } fun text(): String { return elements() .map { it.text } .joinToString(separator = "") } fun appendTextBasic(text: String) { this.mutableStyles.add(ElementNoStyle(text = text)) } fun appendTextWithStyles(text: String, styles: Map<String, String>) { val indexStart: Int = text().length val indexEnd: Int = indexStart + text.length this.mutableStyles.add( ElementStyleBasic( text = text, styles = styles, range = IntRange( start = indexStart, endInclusive = indexEnd, ) ) ) } fun clear() { this.mutableStyles.clear() } sealed class StyleElement( val text: String, ) class ElementNoStyle( text: String, ) : StyleElement(text = text) class ElementStyleBasic( text: String, val styles: Map<String, String>, val range: IntRange, ) : StyleElement(text = text) { fun stylesAsString(): String { return styles .map { entry -> "%s: %s;".format(entry.key, entry.value) } .joinToString(separator = " ") } } }
app/src/main/java/lt/markmerkk/widgets/help/html/StyledText.kt
2031760703
package io.casey.musikcube.remote.ui.shared.activity import com.google.android.material.floatingactionbutton.FloatingActionButton interface IFabConsumer { val fabVisible: Boolean fun onFabPress(fab: FloatingActionButton) }
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/shared/activity/IFabConsumer.kt
4060527367
/* * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.demo import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.activity.addCallback import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.commit import androidx.fragment.app.viewModels import androidx.navigation.fragment.NavHostFragment import androidx.navigation.fragment.navArgs import com.google.android.fhir.datacapture.QuestionnaireFragment /** A fragment class to show screener questionnaire screen. */ class ScreenerFragment : Fragment(R.layout.screener_encounter_fragment) { private val viewModel: ScreenerViewModel by viewModels() private val args: ScreenerFragmentArgs by navArgs() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpActionBar() setHasOptionsMenu(true) updateArguments() onBackPressed() observeResourcesSaveAction() if (savedInstanceState == null) { addQuestionnaireFragment() } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.screen_encounter_fragment_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_add_patient_submit -> { onSubmitAction() true } android.R.id.home -> { showCancelScreenerQuestionnaireAlertDialog() true } else -> super.onOptionsItemSelected(item) } } private fun setUpActionBar() { (requireActivity() as AppCompatActivity).supportActionBar?.apply { setDisplayHomeAsUpEnabled(true) } } private fun updateArguments() { requireArguments().putString(QUESTIONNAIRE_FILE_PATH_KEY, "screener-questionnaire.json") } private fun addQuestionnaireFragment() { val fragment = QuestionnaireFragment() fragment.arguments = bundleOf(QuestionnaireFragment.EXTRA_QUESTIONNAIRE_JSON_STRING to viewModel.questionnaire) childFragmentManager.commit { add(R.id.add_patient_container, fragment, QUESTIONNAIRE_FRAGMENT_TAG) } } private fun onSubmitAction() { val questionnaireFragment = childFragmentManager.findFragmentByTag(QUESTIONNAIRE_FRAGMENT_TAG) as QuestionnaireFragment viewModel.saveScreenerEncounter( questionnaireFragment.getQuestionnaireResponse(), args.patientId ) } private fun showCancelScreenerQuestionnaireAlertDialog() { val alertDialog: AlertDialog? = activity?.let { val builder = AlertDialog.Builder(it) builder.apply { setMessage(getString(R.string.cancel_questionnaire_message)) setPositiveButton(getString(android.R.string.yes)) { _, _ -> NavHostFragment.findNavController(this@ScreenerFragment).navigateUp() } setNegativeButton(getString(android.R.string.no)) { _, _ -> } } builder.create() } alertDialog?.show() } private fun onBackPressed() { activity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner) { showCancelScreenerQuestionnaireAlertDialog() } } private fun observeResourcesSaveAction() { viewModel.isResourcesSaved.observe(viewLifecycleOwner) { if (!it) { Toast.makeText(requireContext(), getString(R.string.inputs_missing), Toast.LENGTH_SHORT) .show() return@observe } Toast.makeText(requireContext(), getString(R.string.resources_saved), Toast.LENGTH_SHORT) .show() NavHostFragment.findNavController(this).navigateUp() } } companion object { const val QUESTIONNAIRE_FILE_PATH_KEY = "questionnaire-file-path-key" const val QUESTIONNAIRE_FRAGMENT_TAG = "questionnaire-fragment-tag" } }
demo/src/main/java/com/google/android/fhir/demo/ScreenerFragment.kt
4192526364
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package egl.templates import egl.* import org.lwjgl.generator.* val NOK_texture_from_pixmap = "NOKTextureFromPixmap".nativeClassEGL("NOK_texture_from_pixmap", postfix = NOK) { documentation = """ Native bindings to the $registryLink extension. This extension allows a color buffer to be used for both rendering and texturing. EGL allows the use of color buffers of pbuffer drawables for texturing, this extension extends this to allow the use of color buffers of pixmaps too. Other types of drawables could be supported by future extensions layered on top of this extension, though only windows are really left which are problematic. The functionality of this extension is similar to WGL_ARB_render_texture which was incorporated into EGL 1.1. However, the purpose of this extension is not to provide "render to texture" like functionality but rather the ability to bind existing native drawables (for instance X pixmaps) to a texture. Though, there is nothing that prohibits it from being used for "render to texture". ${ul( "Windows are problematic as they can change size and therefore are not supported by this extension.", """ Only a color buffer of a EGL pixmap created using an EGLConfig with attribute EGL_BIND_TO_TEXTURE_RGB or EGL_BIND_TO_TEXTURE_RGBA set to TRUE can be bound as a texture. """, """ The texture internal format is determined when the color buffer is associated with the texture, guaranteeing that the color buffer format is equivalent to the texture internal format. """, "A client can create a complete set of mipmap images." )} Requires ${EGL11.core}. """ IntConstant( "", "Y_INVERTED_NOK"..0x307F ) }
modules/lwjgl/egl/src/templates/kotlin/egl/templates/NOK_texture_from_pixmap.kt
1753743650
package mods.betterfoliage.client.render.column import mods.betterfoliage.client.Client import mods.betterfoliage.client.chunk.ChunkOverlayLayer import mods.betterfoliage.client.chunk.ChunkOverlayManager import mods.betterfoliage.client.config.Config import mods.betterfoliage.client.integration.ShadersModIntegration.renderAs import mods.betterfoliage.client.render.* import mods.betterfoliage.client.render.column.ColumnLayerData.SpecialRender.BlockType.* import mods.betterfoliage.client.render.column.ColumnLayerData.SpecialRender.QuadrantType import mods.betterfoliage.client.render.column.ColumnLayerData.SpecialRender.QuadrantType.* import mods.octarinecore.client.render.* import mods.octarinecore.client.resource.ModelRenderRegistry import mods.octarinecore.common.* import net.minecraft.block.state.IBlockState import net.minecraft.client.renderer.BlockRendererDispatcher import net.minecraft.client.renderer.BufferBuilder import net.minecraft.client.renderer.texture.TextureAtlasSprite import net.minecraft.util.BlockRenderLayer import net.minecraft.util.EnumBlockRenderType import net.minecraft.util.EnumBlockRenderType.MODEL import net.minecraft.util.EnumFacing.* import net.minecraft.util.math.BlockPos import net.minecraft.world.IBlockAccess import net.minecraftforge.fml.relauncher.Side import net.minecraftforge.fml.relauncher.SideOnly @SideOnly(Side.CLIENT) @Suppress("NOTHING_TO_INLINE") abstract class AbstractRenderColumn(modId: String) : AbstractBlockRenderingHandler(modId) { /** The rotations necessary to bring the models in position for the 4 quadrants */ val quadrantRotations = Array(4) { Rotation.rot90[UP.ordinal] * it } // ============================ // Configuration // ============================ abstract val overlayLayer: ColumnRenderLayer abstract val connectPerpendicular: Boolean abstract val radiusSmall: Double abstract val radiusLarge: Double // ============================ // Models // ============================ val sideSquare = model { columnSideSquare(-0.5, 0.5) } val sideRoundSmall = model { columnSide(radiusSmall, -0.5, 0.5) } val sideRoundLarge = model { columnSide(radiusLarge, -0.5, 0.5) } val extendTopSquare = model { columnSideSquare(0.5, 0.5 + radiusLarge, topExtension(radiusLarge)) } val extendTopRoundSmall = model { columnSide(radiusSmall, 0.5, 0.5 + radiusLarge, topExtension(radiusLarge)) } val extendTopRoundLarge = model { columnSide(radiusLarge, 0.5, 0.5 + radiusLarge, topExtension(radiusLarge)) } inline fun extendTop(type: QuadrantType) = when(type) { SMALL_RADIUS -> extendTopRoundSmall.model LARGE_RADIUS -> extendTopRoundLarge.model SQUARE -> extendTopSquare.model INVISIBLE -> extendTopSquare.model else -> null } val extendBottomSquare = model { columnSideSquare(-0.5 - radiusLarge, -0.5, bottomExtension(radiusLarge)) } val extendBottomRoundSmall = model { columnSide(radiusSmall, -0.5 - radiusLarge, -0.5, bottomExtension(radiusLarge)) } val extendBottomRoundLarge = model { columnSide(radiusLarge, -0.5 - radiusLarge, -0.5, bottomExtension(radiusLarge)) } inline fun extendBottom(type: QuadrantType) = when (type) { SMALL_RADIUS -> extendBottomRoundSmall.model LARGE_RADIUS -> extendBottomRoundLarge.model SQUARE -> extendBottomSquare.model INVISIBLE -> extendBottomSquare.model else -> null } val topSquare = model { columnLidSquare() } val topRoundSmall = model { columnLid(radiusSmall) } val topRoundLarge = model { columnLid(radiusLarge) } inline fun flatTop(type: QuadrantType) = when(type) { SMALL_RADIUS -> topRoundSmall.model LARGE_RADIUS -> topRoundLarge.model SQUARE -> topSquare.model INVISIBLE -> topSquare.model else -> null } val bottomSquare = model { columnLidSquare() { it.rotate(rot(EAST) * 2 + rot(UP)).mirrorUV(true, true) } } val bottomRoundSmall = model { columnLid(radiusSmall) { it.rotate(rot(EAST) * 2 + rot(UP)).mirrorUV(true, true) } } val bottomRoundLarge = model { columnLid(radiusLarge) { it.rotate(rot(EAST) * 2 + rot(UP)).mirrorUV(true, true) } } inline fun flatBottom(type: QuadrantType) = when(type) { SMALL_RADIUS -> bottomRoundSmall.model LARGE_RADIUS -> bottomRoundLarge.model SQUARE -> bottomSquare.model INVISIBLE -> bottomSquare.model else -> null } val transitionTop = model { mix(sideRoundLarge.model, sideRoundSmall.model) { it > 1 } } val transitionBottom = model { mix(sideRoundSmall.model, sideRoundLarge.model) { it > 1 } } inline fun continuous(q1: QuadrantType, q2: QuadrantType) = q1 == q2 || ((q1 == SQUARE || q1 == INVISIBLE) && (q2 == SQUARE || q2 == INVISIBLE)) @Suppress("NON_EXHAUSTIVE_WHEN") override fun render(ctx: BlockContext, dispatcher: BlockRendererDispatcher, renderer: BufferBuilder, layer: BlockRenderLayer): Boolean { val roundLog = ChunkOverlayManager.get(overlayLayer, ctx.world!!, ctx.pos) when(roundLog) { ColumnLayerData.SkipRender -> return true ColumnLayerData.NormalRender -> return renderWorldBlockBase(ctx, dispatcher, renderer, null) ColumnLayerData.ResolveError, null -> { Client.logRenderError(ctx.blockState(Int3.zero), ctx.pos) return renderWorldBlockBase(ctx, dispatcher, renderer, null) } } // if log axis is not defined and "Default to vertical" config option is not set, render normally if ((roundLog as ColumnLayerData.SpecialRender).column.axis == null && !overlayLayer.defaultToY) { return renderWorldBlockBase(ctx, dispatcher, renderer, null) } // get AO data modelRenderer.updateShading(Int3.zero, allFaces) val baseRotation = rotationFromUp[((roundLog.column.axis ?: Axis.Y) to AxisDirection.POSITIVE).face.ordinal] renderAs(ctx.blockState(Int3.zero), MODEL, renderer) { quadrantRotations.forEachIndexed { idx, quadrantRotation -> // set rotation for the current quadrant val rotation = baseRotation + quadrantRotation // disallow sharp discontinuities in the chamfer radius, or tapering-in where inappropriate if (roundLog.quadrants[idx] == LARGE_RADIUS && roundLog.upType == PARALLEL && roundLog.quadrantsTop[idx] != LARGE_RADIUS && roundLog.downType == PARALLEL && roundLog.quadrantsBottom[idx] != LARGE_RADIUS) { roundLog.quadrants[idx] = SMALL_RADIUS } // render side of current quadrant val sideModel = when (roundLog.quadrants[idx]) { SMALL_RADIUS -> sideRoundSmall.model LARGE_RADIUS -> if (roundLog.upType == PARALLEL && roundLog.quadrantsTop[idx] == SMALL_RADIUS) transitionTop.model else if (roundLog.downType == PARALLEL && roundLog.quadrantsBottom[idx] == SMALL_RADIUS) transitionBottom.model else sideRoundLarge.model SQUARE -> sideSquare.model else -> null } if (sideModel != null) modelRenderer.render( renderer, sideModel, rotation, icon = roundLog.column.side, postProcess = noPost ) // render top and bottom end of current quadrant var upModel: Model? = null var downModel: Model? = null var upIcon = roundLog.column.top var downIcon = roundLog.column.bottom var isLidUp = true var isLidDown = true when (roundLog.upType) { NONSOLID -> upModel = flatTop(roundLog.quadrants[idx]) PERPENDICULAR -> { if (!connectPerpendicular) { upModel = flatTop(roundLog.quadrants[idx]) } else { upIcon = roundLog.column.side upModel = extendTop(roundLog.quadrants[idx]) isLidUp = false } } PARALLEL -> { if (!continuous(roundLog.quadrants[idx], roundLog.quadrantsTop[idx])) { if (roundLog.quadrants[idx] == SQUARE || roundLog.quadrants[idx] == INVISIBLE) { upModel = topSquare.model } } } } when (roundLog.downType) { NONSOLID -> downModel = flatBottom(roundLog.quadrants[idx]) PERPENDICULAR -> { if (!connectPerpendicular) { downModel = flatBottom(roundLog.quadrants[idx]) } else { downIcon = roundLog.column.side downModel = extendBottom(roundLog.quadrants[idx]) isLidDown = false } } PARALLEL -> { if (!continuous(roundLog.quadrants[idx], roundLog.quadrantsBottom[idx]) && (roundLog.quadrants[idx] == SQUARE || roundLog.quadrants[idx] == INVISIBLE)) { downModel = bottomSquare.model } } } if (upModel != null) modelRenderer.render( renderer, upModel, rotation, icon = upIcon, postProcess = { _, _, _, _, _ -> if (isLidUp) { rotateUV(idx + if (roundLog.column.axis == Axis.X) 1 else 0) } } ) if (downModel != null) modelRenderer.render( renderer, downModel, rotation, icon = downIcon, postProcess = { _, _, _, _, _ -> if (isLidDown) { rotateUV((if (roundLog.column.axis == Axis.X) 0 else 3) - idx) } } ) } } return true } }
src/main/kotlin/mods/betterfoliage/client/render/column/AbstractRenderer.kt
458964969
/* * MIT License * * Copyright (c) 2017 Frederik Ar. Mikkelsen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package fredboat.command.moderation import com.fredboat.sentinel.SentinelExchanges import com.fredboat.sentinel.entities.ModRequest import com.fredboat.sentinel.entities.ModRequestType import fredboat.messaging.internal.Context import fredboat.perms.Permission import fredboat.util.DiscordUtil import fredboat.util.TextUtils import fredboat.util.extension.escapeAndDefuse import kotlinx.coroutines.reactive.awaitFirst import kotlinx.coroutines.reactive.awaitLast import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.amqp.core.MessageDeliveryMode import reactor.core.publisher.Mono class SoftbanCommand(name: String, vararg aliases: String) : DiscordModerationCommand(name, *aliases) { companion object { private val log: Logger = LoggerFactory.getLogger(SoftbanCommand::class.java) } override fun modAction(args: DiscordModerationCommand.ModActionInfo): Mono<Unit> { val deleteDays = if(args.isKeepMessages) 0 else DiscordModerationCommand.DEFAULT_DELETE_DAYS return args.context.sentinel.genericMonoSendAndReceive<String, Unit>( exchange = SentinelExchanges.REQUESTS, request = ModRequest( guildId = args.context.guild.id, userId = args.targetUser.id, type = ModRequestType.BAN, banDeleteDays = deleteDays, reason = args.formattedReason ), routingKey = args.context.routingKey, mayBeEmpty = true, deliveryMode = MessageDeliveryMode.PERSISTENT, transform = {} ) } private fun unbanAsync(args: DiscordModerationCommand.ModActionInfo) { args.context.sentinel.genericMonoSendAndReceive<String, Unit>( exchange = SentinelExchanges.REQUESTS, request = ModRequest( guildId = args.context.guild.id, userId = args.targetUser.id, type = ModRequestType.UNBAN ), routingKey = args.context.routingKey, mayBeEmpty = true, deliveryMode = MessageDeliveryMode.PERSISTENT, transform = {} ).doOnError { log.error("Failed to unban ${args.targetUser.id} while doing softban in ${args.context.guild}", it) }.subscribe() } override fun requiresMember(): Boolean { return false } override fun onSuccess(args: DiscordModerationCommand.ModActionInfo): () -> Unit { val successOutput = (args.context.i18nFormat("softbanSuccess", args.targetUser.asMention + " " + TextUtils.escapeAndDefuse(args.targetAsString())) + "\n" + TextUtils.escapeAndDefuse(args.plainReason)) return { unbanAsync(args) args.context.replyWithName(successOutput) } } override fun onFail(args: DiscordModerationCommand.ModActionInfo): (t: Throwable) -> Unit { val escapedTargetName = TextUtils.escapeAndDefuse(args.targetAsString()) return { t -> log.error("Failed to softban ${args.targetUser.id} from ${args.context.guild}", t) args.context.replyWithName(args.context.i18nFormat("modBanFail", args.targetUser.asMention + " " + escapedTargetName)) unbanAsync(args) } } override suspend fun checkAuthorizationWithFeedback(args: DiscordModerationCommand.ModActionInfo): Boolean { val context = args.context val targetMember = args.targetMember val mod = context.member //A softban is like a kick + clear messages, so check for those on the invoker if (!context.checkInvokerPermissionsWithFeedback(Permission.KICK_MEMBERS + Permission.MESSAGE_MANAGE)) return false //We do however need ban perms to do this if (!context.checkSelfPermissionsWithFeedback(Permission.BAN_MEMBERS)) return false // if the target user is NOT member of the guild AND banned, the invoker needs to have BAN perms, because it is // essentially an UNBAN, and we dont want to allow users to unban anyone with just kick perms if (targetMember == null) { var isUnban = false fetchBanlist(context).doOnNext { if(it.user == args.targetUser.raw) isUnban = false }.awaitLast() if (!isUnban) return false return context.checkInvokerPermissionsWithFeedback(Permission.BAN_MEMBERS) } if (mod == targetMember) { context.replyWithName(context.i18n("softbanFailSelf")) return false } if (targetMember.isOwner()) { context.replyWithName(context.i18n("softbanFailOwner")) return false } if (targetMember == args.context.guild.selfMember) { context.replyWithName(context.i18n("softbanFailMyself")) return false } val modRole = DiscordUtil.getHighestRolePosition(mod).awaitFirst() val targetRole = DiscordUtil.getHighestRolePosition(targetMember).awaitFirst() val selfRole = DiscordUtil.getHighestRolePosition(mod.guild.selfMember).awaitFirst() if (modRole <= targetRole && !mod.isOwner()) { context.replyWithName(context.i18nFormat("modFailUserHierarchy", targetMember.effectiveName.escapeAndDefuse())) return false } if (selfRole <= targetRole) { context.replyWithName(context.i18nFormat("modFailBotHierarchy", targetMember.effectiveName.escapeAndDefuse())) return false } return true } override fun dmForTarget(args: DiscordModerationCommand.ModActionInfo): String? { return args.context.i18nFormat("modActionTargetDmKicked", // a softban is like a kick "**${TextUtils.escapeMarkdown(args.context.guild.name)}**", "${TextUtils.asString(args.context.user)}\n${args.plainReason}" ) } override fun help(context: Context): String { return ("{0}{1} <user>\n" + "{0}{1} <user> <reason>\n" + "{0}{1} <user> <reason> --keep\n" + "#" + context.i18n("helpSoftbanCommand") + "\n" + context.i18nFormat("modKeepMessages", "--keep or -k")) } }
FredBoat/src/main/java/fredboat/command/moderation/SoftbanCommand.kt
2765635501
package science.apolline.root import android.arch.lifecycle.ViewModel import com.github.salomonbrys.kodein.Kodein import com.github.salomonbrys.kodein.KodeinInjected import com.github.salomonbrys.kodein.KodeinInjector /** * Created by sparow on 2/25/2018. */ abstract class RootViewModel<out T> : ViewModel(), KodeinInjected { override val injector: KodeinInjector = KodeinInjector() @Suppress("UNCHECKED_CAST") fun init(kodein: Kodein): T { injector.inject(kodein) return this as T } }
app/src/main/java/science/apolline/root/RootViewModel.kt
3789689231
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.localanalytics.tests import org.hisp.dhis.android.core.utils.integration.mock.MockIntegrationTestDatabaseContent import org.hisp.dhis.android.core.utils.runner.D2JunitRunner import org.hisp.dhis.android.localanalytics.dbgeneration.LocalAnalyticsDataParams import org.junit.BeforeClass import org.junit.Ignore import org.junit.runner.RunWith @Ignore("Tests for local analytics. Only to be executed on demand") @RunWith(D2JunitRunner::class) internal class LocalAnalyticsTrackerDefaultMockIntegrationShould : BaseLocalAnalyticsTrackerMockIntegrationShould() { companion object LocalAnalyticsAggregatedLargeDataMockIntegrationShould { @BeforeClass @JvmStatic fun setUpClass() { setUpClass( LocalAnalyticsDataParams.DefaultFactor, MockIntegrationTestDatabaseContent.LocalAnalyticsDefaultDispatcher ) } } }
core/src/androidTest/java/org/hisp/dhis/android/localanalytics/tests/LocalAnalyticsTrackerDefaultMockIntegrationShould.kt
2767999649
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.core.models data class Frequency( var numerator: Int, var denominator: Int, ) { init { if (numerator == denominator) { denominator = 1 numerator = 1 } } fun toDouble(): Double { return numerator.toDouble() / denominator } companion object { @JvmField val DAILY = Frequency(1, 1) @JvmField val THREE_TIMES_PER_WEEK = Frequency(3, 7) @JvmField val TWO_TIMES_PER_WEEK = Frequency(2, 7) @JvmField val WEEKLY = Frequency(1, 7) } }
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/models/Frequency.kt
1264240144
// Copyright (c) 2019 The Gulden developers // Authored by: Malcolm MacLeod ([email protected]), Willem de Jonge ([email protected]) // Distributed under the GULDEN software license, see the accompanying // file COPYING package com.gulden.unity_wallet import android.content.Intent import android.net.Uri import android.widget.Toast import com.gulden.unity_wallet.util.AppBaseActivity // URI handlers need unity core active to function - however as they may be called when app is closed it is necessary to manually start the core in some cases // All URI handlers therefore come via this transparent activity // Which takes care of detecting whether core is already active or not and then handles the URI appropriately class URIHandlerActivity : AppBaseActivity() { private fun toastAndExit() { Toast.makeText(this, getString(R.string.toast_warn_uri_attempt_before_wallet_creation), Toast.LENGTH_SHORT).show() finish() } override fun onWalletCreate() { toastAndExit() } private fun handleURIAndClose() { if ((intentUri != null) && (scheme != null)) { try { val recipient = createRecipient(intentUri.toString()) SendCoinsFragment.newInstance(recipient, true).show(supportFragmentManager, SendCoinsFragment::class.java.simpleName) } catch (e : Exception) { //TODO: Improve error handling here finish() } } } private var intentUri : Uri? = null private var scheme : String? = null private fun isValidGuldenUri(uri: Uri?): Boolean { uri?.run { scheme?.run { toLowerCase().run { return startsWith("gulden") || startsWith("guldencoin") || startsWith("iban") || startsWith("sepa") } } } return false } override fun onWalletReady() { intentUri = intent.data scheme = intentUri?.scheme if (Intent.ACTION_VIEW == intent.action && isValidGuldenUri(intentUri)) { handleURIAndClose() } else { finish() } } }
src/frontend/android/unity_wallet/app/src/main/java/com/gulden/unity_wallet/URIHandlerActivity.kt
348669849
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator import javax.inject.Inject import org.hisp.dhis.android.core.analytics.aggregated.MetadataItem import org.hisp.dhis.android.core.analytics.aggregated.internal.AnalyticsServiceEvaluationItem import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.indicatorengine.IndicatorSQLEngine internal class IndicatorSQLEvaluator @Inject constructor( private val indicatorEngine: IndicatorSQLEngine ) : AnalyticsEvaluator { override fun evaluate( evaluationItem: AnalyticsServiceEvaluationItem, metadata: Map<String, MetadataItem> ): String? { val indicator = IndicatorEvaluatorHelper.getIndicator(evaluationItem, metadata) val contextEvaluationItem = IndicatorEvaluatorHelper.getContextEvaluationItem(evaluationItem, indicator) return indicatorEngine.evaluateIndicator( indicator = indicator, contextEvaluationItem = contextEvaluationItem, contextMetadata = metadata ) } override fun getSql( evaluationItem: AnalyticsServiceEvaluationItem, metadata: Map<String, MetadataItem> ): String { val indicator = IndicatorEvaluatorHelper.getIndicator(evaluationItem, metadata) val contextEvaluationItem = IndicatorEvaluatorHelper.getContextEvaluationItem(evaluationItem, indicator) return indicatorEngine.getSql( indicator = indicator, contextEvaluationItem = contextEvaluationItem, contextMetadata = metadata ) } }
core/src/main/java/org/hisp/dhis/android/core/analytics/aggregated/internal/evaluator/IndicatorSQLEvaluator.kt
3078682304
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.trackedentity.search import org.hisp.dhis.android.core.common.AssignedUserMode import org.mockito.ArgumentMatcher internal class QueryUserModeMatcher( private val assignedUserMode: AssignedUserMode ) : ArgumentMatcher<TrackedEntityInstanceQueryOnline> { override fun matches(query: TrackedEntityInstanceQueryOnline?): Boolean { return query?.let { it.assignedUserMode() == assignedUserMode } ?: false } }
core/src/test/java/org/hisp/dhis/android/core/trackedentity/search/QueryUserModeMatcher.kt
3413175812
package tripleklay.shaders /** * Shader related utility methods. */ object ShaderUtil { /** * Formats a floating point value for inclusion in a shader program. Ensures that the value * always contains a '.' and a trailing '0' if needed. */ fun format(value: Float): String { val fmt = value.toString() return if (fmt.indexOf('.') == -1) fmt + ".0" else fmt } }
tripleklay/src/main/kotlin/tripleklay/shaders/ShaderUtil.kt
3372710521
// "Create annotation 'foo'" "true" @[<caret>foo(fooBar = 1)] fun test() { }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/annotationEntry/singleNamedArgAnnotation.kt
3275179834
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.MovePropertyToConstructorIntention import org.jetbrains.kotlin.idea.intentions.loopToCallChain.hasUsages import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull class CanBePrimaryConstructorPropertyInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return propertyVisitor(fun(property) { if (property.isLocal) return if (property.getter != null || property.setter != null || property.delegate != null) return val assigned = property.initializer as? KtReferenceExpression ?: return val context = assigned.analyze() val assignedDescriptor = context.get(BindingContext.REFERENCE_TARGET, assigned) as? ValueParameterDescriptor ?: return val containingConstructor = assignedDescriptor.containingDeclaration as? ClassConstructorDescriptor ?: return if (containingConstructor.containingDeclaration.isData) return val propertyTypeReference = property.typeReference val propertyType = context.get(BindingContext.TYPE, propertyTypeReference) if (propertyType != null && propertyType != assignedDescriptor.type) return val nameIdentifier = property.nameIdentifier ?: return if (nameIdentifier.text != assignedDescriptor.name.asString()) return val assignedParameter = DescriptorToSourceUtils.descriptorToDeclaration(assignedDescriptor) as? KtParameter ?: return val containingClassOrObject = property.containingClassOrObject ?: return if (containingClassOrObject !== assignedParameter.containingClassOrObject) return if (containingClassOrObject.isInterfaceClass()) return if (property.hasModifier(KtTokens.OPEN_KEYWORD) && containingClassOrObject is KtClass && containingClassOrObject.isOpen() && assignedParameter.isUsedInClassInitializer(containingClassOrObject) ) return holder.registerProblem( holder.manager.createProblemDescriptor( nameIdentifier, nameIdentifier, KotlinBundle.message("property.is.explicitly.assigned.to.parameter.0.can", assignedDescriptor.name), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, MovePropertyToConstructorIntention() ) ) }) } private fun KtClass.isOpen(): Boolean { return hasModifier(KtTokens.OPEN_KEYWORD) || hasModifier(KtTokens.ABSTRACT_KEYWORD) || hasModifier(KtTokens.SEALED_KEYWORD) } private fun KtParameter.isUsedInClassInitializer(containingClass: KtClass): Boolean { val classInitializer = containingClass.body?.declarations?.firstIsInstanceOrNull<KtClassInitializer>() ?: return false return hasUsages(classInitializer) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/CanBePrimaryConstructorPropertyInspection.kt
2558512026
package com.packt.chapter11 import io.kotlintest.Eventually import io.kotlintest.Tag import io.kotlintest.specs.ShouldSpec object ElasticSearch : Tag() object Windows : Tag() class ConfigExample : ShouldSpec(), Eventually { init { should("run multiple times") { // test logic }.config(invocations = 5, threads = 4) should("run multiple times in multiple threads") { // test logic }.config(invocations = 20, threads = 4) should("be disabled") { // test logic }.config(enabled = false) fun isMultiCore(): Boolean = Runtime.getRuntime().availableProcessors() > 1 should("only run on multicore machines") { // test logic }.config(enabled = isMultiCore()) should("this test is tagged") { // test logic }.config(tags = setOf(ElasticSearch, Windows)) } } class OneInstanceOfTheseTests : ShouldSpec() { override val oneInstancePerTest = true init { // tests here } }
Chapter11/chapter11/src/main/kotlin/com/packt/chapter11/11.10.Config.kt
1807846543
package com.airbnb.epoxy.sample import android.view.View import com.airbnb.epoxy.AutoModel import com.airbnb.epoxy.DataBindingEpoxyModel import com.airbnb.epoxy.EpoxyAsyncUtil import com.airbnb.epoxy.TypedEpoxyController import com.airbnb.epoxy.sample.models.CarouselModelGroup import com.airbnb.epoxy.sample.views.HeaderViewModel_ class SampleController(private val callbacks: AdapterCallbacks) : TypedEpoxyController<List<CarouselData>>( EpoxyAsyncUtil.getAsyncBackgroundHandler(), EpoxyAsyncUtil.getAsyncBackgroundHandler() ) { interface AdapterCallbacks { fun onAddCarouselClicked() fun onClearCarouselsClicked() fun onShuffleCarouselsClicked() fun onChangeAllColorsClicked() fun onAddColorToCarouselClicked(carousel: CarouselData?) fun onClearCarouselClicked(carousel: CarouselData?) fun onShuffleCarouselColorsClicked(carousel: CarouselData?) fun onChangeCarouselColorsClicked(carousel: CarouselData?) fun onColorClicked(carousel: CarouselData?, colorPosition: Int) } @AutoModel lateinit var header: HeaderViewModel_ @AutoModel lateinit var addButton: ButtonBindingModel_ @AutoModel lateinit var clearButton: ButtonBindingModel_ @AutoModel lateinit var shuffleButton: ButtonBindingModel_ @AutoModel lateinit var changeColorsButton: ButtonBindingModel_ override fun buildModels(carousels: List<CarouselData>) { header .title(R.string.epoxy) .caption(R.string.header_subtitle) // "addTo" is not needed since implicit adding is enabled // (https://github.com/airbnb/epoxy/wiki/Epoxy-Controller#implicit-adding) addButton .textRes(R.string.button_add) .clickListener { model: ButtonBindingModel_?, parentView: DataBindingEpoxyModel.DataBindingHolder?, clickedView: View?, position: Int -> callbacks.onAddCarouselClicked() } clearButton .textRes(R.string.button_clear) .clickListener { v: View? -> callbacks.onClearCarouselsClicked() } .addIf(carousels.size > 0, this) shuffleButton .textRes(R.string.button_shuffle) .clickListener { v: View? -> callbacks.onShuffleCarouselsClicked() } .addIf(carousels.size > 1, this) changeColorsButton .textRes(R.string.button_change) .clickListener { v: View? -> callbacks.onChangeAllColorsClicked() } .addIf(carousels.size > 0, this) for (i in carousels.indices) { val carousel = carousels[i] add(CarouselModelGroup(carousel, callbacks)) } } override fun onExceptionSwallowed(exception: RuntimeException) { // Best practice is to throw in debug so you are aware of any issues that Epoxy notices. // Otherwise Epoxy does its best to swallow these exceptions and continue gracefully throw exception } init { // Demonstrating how model building and diffing can be done in the background. // You can control them separately by passing in separate handler, as shown below. // super(new Handler(), BACKGROUND_HANDLER); // super(BACKGROUND_HANDLER, new Handler()); isDebugLoggingEnabled = true } }
epoxy-sample/src/main/java/com/airbnb/epoxy/sample/SampleController.kt
2882175565
package co.smartreceipts.android.ocr.widget.configuration import co.smartreceipts.android.activities.NavigationHandler import co.smartreceipts.android.activities.SmartReceiptsActivity import co.smartreceipts.core.di.scopes.FragmentScope import javax.inject.Inject @FragmentScope class OcrConfigurationRouter @Inject constructor(private val navigationHandler: NavigationHandler<SmartReceiptsActivity>) { fun navigateBack(): Boolean { return this.navigationHandler.navigateBack() } fun navigateToLoginScreen() { navigationHandler.navigateToLoginScreen() } }
app/src/main/java/co/smartreceipts/android/ocr/widget/configuration/OcrConfigurationRouter.kt
972192904
package com.rubenwardy.minetestmodmanager.presenters import android.content.Context import android.util.Log import com.rubenwardy.minetestmodmanager.manager.ModManager import com.rubenwardy.minetestmodmanager.models.ModSpec class DisclaimerPresenter(val view: View) { fun onAcceptClicked(context: Context) { view.setAgreedToDisclaimer() val modspec = view.getModInfo() if (modspec.listname != null && !modspec.name.isEmpty()) { val modman = ModManager.getInstance() val list = modman.getModList(modspec.listname) if (list != null) { val mod = list.get(modspec.name, modspec.author) if (mod != null && !mod.link.isEmpty()) { modman.installUrlModAsync(context, mod, mod.link, modman.installDir) } else { Log.e("DAct", "Unable to find an installable mod of that name! " + modspec.name) } } else { Log.e("DAct", "Unable to find a ModList of that id! " + modspec.listname) } } view.finishActivity() } interface View { fun setAgreedToDisclaimer() fun finishActivity() fun getModInfo() : ModSpec } }
app/src/main/java/com/rubenwardy/minetestmodmanager/presenters/DisclaimerPresenter.kt
1895000653
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.jvm.kotlin.plugin import org.jetbrains.kotlin.compiler.plugin.AbstractCliOption import org.jetbrains.kotlin.compiler.plugin.CliOption import org.jetbrains.kotlin.compiler.plugin.CliOptionProcessingException import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.config.CompilerConfigurationKey class DependencyTrackerCommandLineProcessor : CommandLineProcessor { companion object { private const val OPTION_OUTPUT_PATH = "out" val ARG_OUTPUT_PATH = CompilerConfigurationKey<String>(OPTION_OUTPUT_PATH) } override val pluginId: String = "buck_deps_tracker" override val pluginOptions: Collection<AbstractCliOption> = listOf( CliOption( optionName = OPTION_OUTPUT_PATH, valueDescription = "[string]", description = "Absolute path to output JSON file", required = true)) override fun processOption( option: AbstractCliOption, value: String, configuration: CompilerConfiguration ) { when (option.optionName) { OPTION_OUTPUT_PATH -> configuration.put(ARG_OUTPUT_PATH, value) else -> throw CliOptionProcessingException("Unknown option: ${option.optionName}") } } }
src/com/facebook/buck/jvm/kotlin/plugin/DependencyTrackerCommandLineProcessor.kt
3017847227
package com.intellij.workspaceModel.storage.entities.test.api import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity interface MainEntityList : WorkspaceEntity { val x: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : MainEntityList, ModifiableWorkspaceEntity<MainEntityList>, ObjBuilder<MainEntityList> { override var entitySource: EntitySource override var x: String } companion object : Type<MainEntityList, Builder>() { operator fun invoke(x: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): MainEntityList { val builder = builder() builder.x = x builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: MainEntityList, modification: MainEntityList.Builder.() -> Unit) = modifyEntity( MainEntityList.Builder::class.java, entity, modification) var MainEntityList.Builder.child: @Child List<AttachedEntityList> by WorkspaceEntity.extension() //endregion interface AttachedEntityList : WorkspaceEntity { val ref: MainEntityList? val data: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : AttachedEntityList, ModifiableWorkspaceEntity<AttachedEntityList>, ObjBuilder<AttachedEntityList> { override var entitySource: EntitySource override var ref: MainEntityList? override var data: String } companion object : Type<AttachedEntityList, Builder>() { operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): AttachedEntityList { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: AttachedEntityList, modification: AttachedEntityList.Builder.() -> Unit) = modifyEntity( AttachedEntityList.Builder::class.java, entity, modification) //endregion val MainEntityList.child: List<@Child AttachedEntityList> by WorkspaceEntity.extension()
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/ExtensionFieldEntityList.kt
2117415211
package com.github.bumblebee.command.weather import com.github.bumblebee.command.SingleArgumentCommand import com.github.telegram.api.BotApi import com.github.telegram.domain.Update import org.springframework.stereotype.Component @Component class WeatherCommand(private val botApi: BotApi) : SingleArgumentCommand() { override fun handleCommand(update: Update, chatId: Long, argument: String?) { when (WeatherArgument.of(argument) ?: WeatherArgument.TEMPERATURE) { WeatherArgument.MAP_DYNAMIC -> botApi.sendDocument(chatId, MAP_URL_DYNAMIC.withTimestamp()) WeatherArgument.MAP_LATEST -> botApi.sendPhoto(chatId, MAP_URL_LATEST.withTimestamp()) WeatherArgument.TEMPERATURE -> botApi.sendPhoto(chatId, TEMPERATURE_URL.withTimestamp()) } } private enum class WeatherArgument constructor(val arguments: Set<String>) { MAP_DYNAMIC(setOf("md", "dynamic", "dyn")), MAP_LATEST(setOf("ml", "latest", "lt")), TEMPERATURE(setOf("t", "temp")); companion object { fun of(code: String?): WeatherArgument? { return values().firstOrNull { it.arguments.any { it.equals(code, ignoreCase = true) } } } } } private fun String.withTimestamp(): String = this + (if (contains('?')) "&" else "?" ) + "ts=" + System.currentTimeMillis() companion object { private val MAP_URL_DYNAMIC = "http://meteoinfo.by/radar/UMMN/radar-map.gif" private val MAP_URL_LATEST = "http://meteoinfo.by/radar/UMMN/UMMN_latest.png" private val TEMPERATURE_URL = "https://www.foreca.ru/meteogram.php?loc_id=100625144&lang=ru_RU" } }
telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/command/weather/WeatherCommand.kt
1220600054
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("Main") @file:Suppress("ReplacePutWithAssignment") package com.intellij.idea import com.intellij.concurrency.IdeaForkJoinWorkerThreadFactory import com.intellij.diagnostic.* import com.intellij.ide.BootstrapBundle import com.intellij.ide.plugins.StartupAbortedException import com.intellij.ide.startup.StartupActionScriptManager import com.intellij.openapi.application.PathManager import com.jetbrains.JBR import kotlinx.coroutines.* import java.awt.GraphicsEnvironment import java.io.IOException import java.lang.invoke.MethodHandles import java.lang.invoke.MethodType import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.function.Supplier import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext import kotlin.system.exitProcess fun main(rawArgs: Array<String>) { val startupTimings = LinkedHashMap<String, Long>(6) startupTimings.put("startup begin", System.nanoTime()) val args: List<String> = preProcessRawArgs(rawArgs) AppMode.setFlags(args) try { bootstrap(startupTimings) startupTimings.put("main scope creating", System.nanoTime()) runBlocking(rootTask()) { StartUpMeasurer.addTimings(startupTimings, "bootstrap") val appInitPreparationActivity = StartUpMeasurer.startActivity("app initialization preparation") val busyThread = Thread.currentThread() launch(CoroutineName("ForkJoin CommonPool configuration") + Dispatchers.Default) { IdeaForkJoinWorkerThreadFactory.setupForkJoinCommonPool(AppMode.isHeadless()) } // not IO-, but CPU-bound due to descrambling, don't use here IO dispatcher val appStarterDeferred = async(CoroutineName("main class loading") + Dispatchers.Default) { val aClass = AppStarter::class.java.classLoader.loadClass("com.intellij.idea.MainImpl") MethodHandles.lookup().findConstructor(aClass, MethodType.methodType(Void.TYPE)).invoke() as AppStarter } initProjectorIfNeeded(args) withContext(Dispatchers.Default + StartupAbortedExceptionHandler()) { StartUpMeasurer.appInitPreparationActivity = appInitPreparationActivity startApplication(args = args, appStarterDeferred = appStarterDeferred, mainScope = this@runBlocking, busyThread = busyThread) } awaitCancellation() } } catch (e: Throwable) { StartupErrorReporter.showMessage(BootstrapBundle.message("bootstrap.error.title.start.failed"), e) exitProcess(AppExitCodes.STARTUP_EXCEPTION) } } private fun initProjectorIfNeeded(args: List<String>) { if (args.isEmpty() || (AppMode.CWM_HOST_COMMAND != args[0] && AppMode.CWM_HOST_NO_LOBBY_COMMAND != args[0])) { return } if (!JBR.isProjectorUtilsSupported()) { error("JBR version 17.0.5b653.12 or later is required to run a remote-dev server") } runActivity("cwm host init") { JBR.getProjectorUtils().setLocalGraphicsEnvironmentProvider( Supplier { val projectorEnvClass = AppStarter::class.java.classLoader.loadClass("org.jetbrains.projector.awt.image.PGraphicsEnvironment") projectorEnvClass.getDeclaredMethod("getInstance").invoke(null) as GraphicsEnvironment }) val projectorMainClass = AppStarter::class.java.classLoader.loadClass("org.jetbrains.projector.server.ProjectorLauncher\$Starter") MethodHandles.privateLookupIn(projectorMainClass, MethodHandles.lookup()).findStatic( projectorMainClass, "runProjectorServer", MethodType.methodType(Boolean::class.javaPrimitiveType) ).invoke() } } private fun bootstrap(startupTimings: LinkedHashMap<String, Long>) { startupTimings.put("properties loading", System.nanoTime()) PathManager.loadProperties() startupTimings.put("plugin updates install", System.nanoTime()) // this check must be performed before system directories are locked if (!AppMode.isCommandLine() || java.lang.Boolean.getBoolean(AppMode.FORCE_PLUGIN_UPDATES)) { val configImportNeeded = !AppMode.isHeadless() && !Files.exists(Path.of(PathManager.getConfigPath())) if (!configImportNeeded) { // Consider following steps: // - user opens settings, and installs some plugins; // - the plugins are downloaded and saved somewhere; // - IDE prompts for restart; // - after restart, the plugins are moved to proper directories ("installed") by the next line. // TODO get rid of this: plugins should be installed before restarting the IDE installPluginUpdates() } } startupTimings.put("classloader init", System.nanoTime()) BootstrapClassLoaderUtil.initClassLoader(AppMode.isIsRemoteDevHost()) } private fun preProcessRawArgs(rawArgs: Array<String>): List<String> { if (rawArgs.size == 1 && rawArgs[0] == "%f") return emptyList() // Parse java properties from arguments and activate them val (propArgs, other) = rawArgs.partition { it.startsWith("-D") && it.contains("=") } propArgs.forEach { arg -> val (option, value) = arg.removePrefix("-D").split("=") System.setProperty(option, value) } return other } @Suppress("HardCodedStringLiteral") private fun installPluginUpdates() { try { // referencing `StartupActionScriptManager` is ok - a string constant will be inlined val scriptFile = Path.of(PathManager.getPluginTempPath(), StartupActionScriptManager.ACTION_SCRIPT_FILE) if (Files.isRegularFile(scriptFile)) { // load StartupActionScriptManager and all others related class (ObjectInputStream and so on loaded as part of class define) // only if there is an action script to execute StartupActionScriptManager.executeActionScript() } } catch (e: IOException) { StartupErrorReporter.showMessage( "Plugin Installation Error", """ The IDE failed to install or update some plugins. Please try again, and if the problem persists, please report it to https://jb.gg/ide/critical-startup-errors The cause: $e """.trimIndent(), false ) } } // separate class for nicer presentation in dumps private class StartupAbortedExceptionHandler : AbstractCoroutineContextElement(CoroutineExceptionHandler), CoroutineExceptionHandler { override fun handleException(context: CoroutineContext, exception: Throwable) { StartupAbortedException.processException(exception) } override fun toString() = "StartupAbortedExceptionHandler" }
platform/bootstrap/src/com/intellij/idea/Main.kt
725779034
// 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.openapi.wm.impl import com.intellij.openapi.actionSystem.ActionGroup internal interface ToolbarHolder { fun initToolbar(toolbarActionGroups: List<Pair<ActionGroup, String>>) fun updateToolbar() }
platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolbarHolder.kt
807071739
package io.dwak.injectionhelper import com.squareup.javapoet.ClassName import com.squareup.javapoet.JavaFile import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterSpec import com.squareup.javapoet.TypeName import com.squareup.javapoet.TypeSpec import java.io.IOException import javax.annotation.processing.Filer import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Element import javax.lang.model.element.Modifier class InjectionHelperBindingClass(private val classPackage: String, private val className: String, private val targetClass: String, private val processingEnv: ProcessingEnvironment) { companion object { const val SUFFIX = "InjectionHelper" const val METHOD_NAME = "inject" } private val bindings = hashMapOf<String, FieldBinding>() fun createAndAddBinding(element: Element) { val binding = FieldBinding(element) bindings.put(binding.name, binding) } fun generate(): TypeSpec { val classBuilder = TypeSpec.classBuilder(className) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) val injectBuilder = MethodSpec.methodBuilder(METHOD_NAME) .addParameter(ParameterSpec.builder(ClassName.get(classPackage, targetClass), "target") .build()) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(TypeName.VOID) bindings.values .forEach { injectBuilder.addParameter(ParameterSpec.builder(ClassName.get(it.type), it.name).build()) injectBuilder.addStatement("target.${it.name} = ${it.name}") } return classBuilder.addMethod(injectBuilder.build()) .build() } @Throws(IOException::class) fun writeToFiler(filer: Filer) { JavaFile.builder(classPackage, generate()).build().writeTo(filer) } }
processor/src/main/java/io/dwak/injectionhelper/InjectionHelperBindingClass.kt
383992373
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.bridgeEntities import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.url.VirtualFileUrl import kotlin.jvm.JvmName import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity interface ModuleEntity : WorkspaceEntityWithSymbolicId { val name: String val type: String? val dependencies: List<ModuleDependencyItem> val contentRoots: List<@Child ContentRootEntity> @Child val customImlData: ModuleCustomImlDataEntity? @Child val groupPath: ModuleGroupPathEntity? @Child val javaSettings: JavaModuleSettingsEntity? @Child val exModuleOptions: ExternalSystemModuleOptionsEntity? @Child val testProperties: TestModulePropertiesEntity? val facets: List<@Child FacetEntity> override val symbolicId: ModuleId get() = ModuleId(name) //region generated code @GeneratedCodeApiVersion(1) interface Builder : ModuleEntity, WorkspaceEntity.Builder<ModuleEntity>, ObjBuilder<ModuleEntity> { override var entitySource: EntitySource override var name: String override var type: String? override var dependencies: MutableList<ModuleDependencyItem> override var contentRoots: List<ContentRootEntity> override var customImlData: ModuleCustomImlDataEntity? override var groupPath: ModuleGroupPathEntity? override var javaSettings: JavaModuleSettingsEntity? override var exModuleOptions: ExternalSystemModuleOptionsEntity? override var testProperties: TestModulePropertiesEntity? override var facets: List<FacetEntity> } companion object : Type<ModuleEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(name: String, dependencies: List<ModuleDependencyItem>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleEntity { val builder = builder() builder.name = name builder.dependencies = dependencies.toMutableWorkspaceList() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ModuleEntity, modification: ModuleEntity.Builder.() -> Unit) = modifyEntity( ModuleEntity.Builder::class.java, entity, modification) var ModuleEntity.Builder.facetOrder: @Child FacetsOrderEntity? by WorkspaceEntity.extension() var ModuleEntity.Builder.sourceRoots: List<SourceRootEntity> by WorkspaceEntity.extension() //endregion interface ModuleCustomImlDataEntity : WorkspaceEntity { val module: ModuleEntity val rootManagerTagCustomData: String? val customModuleOptions: Map<String, String> //region generated code @GeneratedCodeApiVersion(1) interface Builder : ModuleCustomImlDataEntity, WorkspaceEntity.Builder<ModuleCustomImlDataEntity>, ObjBuilder<ModuleCustomImlDataEntity> { override var entitySource: EntitySource override var module: ModuleEntity override var rootManagerTagCustomData: String? override var customModuleOptions: Map<String, String> } companion object : Type<ModuleCustomImlDataEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(customModuleOptions: Map<String, String>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleCustomImlDataEntity { val builder = builder() builder.customModuleOptions = customModuleOptions builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ModuleCustomImlDataEntity, modification: ModuleCustomImlDataEntity.Builder.() -> Unit) = modifyEntity( ModuleCustomImlDataEntity.Builder::class.java, entity, modification) //endregion interface ModuleGroupPathEntity : WorkspaceEntity { val module: ModuleEntity val path: List<String> //region generated code @GeneratedCodeApiVersion(1) interface Builder : ModuleGroupPathEntity, WorkspaceEntity.Builder<ModuleGroupPathEntity>, ObjBuilder<ModuleGroupPathEntity> { override var entitySource: EntitySource override var module: ModuleEntity override var path: MutableList<String> } companion object : Type<ModuleGroupPathEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(path: List<String>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleGroupPathEntity { val builder = builder() builder.path = path.toMutableWorkspaceList() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ModuleGroupPathEntity, modification: ModuleGroupPathEntity.Builder.() -> Unit) = modifyEntity( ModuleGroupPathEntity.Builder::class.java, entity, modification) //endregion interface JavaModuleSettingsEntity: WorkspaceEntity { val module: ModuleEntity val inheritedCompilerOutput: Boolean val excludeOutput: Boolean val compilerOutput: VirtualFileUrl? val compilerOutputForTests: VirtualFileUrl? val languageLevelId: String? //region generated code @GeneratedCodeApiVersion(1) interface Builder : JavaModuleSettingsEntity, WorkspaceEntity.Builder<JavaModuleSettingsEntity>, ObjBuilder<JavaModuleSettingsEntity> { override var entitySource: EntitySource override var module: ModuleEntity override var inheritedCompilerOutput: Boolean override var excludeOutput: Boolean override var compilerOutput: VirtualFileUrl? override var compilerOutputForTests: VirtualFileUrl? override var languageLevelId: String? } companion object : Type<JavaModuleSettingsEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(inheritedCompilerOutput: Boolean, excludeOutput: Boolean, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): JavaModuleSettingsEntity { val builder = builder() builder.inheritedCompilerOutput = inheritedCompilerOutput builder.excludeOutput = excludeOutput builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: JavaModuleSettingsEntity, modification: JavaModuleSettingsEntity.Builder.() -> Unit) = modifyEntity( JavaModuleSettingsEntity.Builder::class.java, entity, modification) //endregion interface ExternalSystemModuleOptionsEntity: WorkspaceEntity { val module: ModuleEntity val externalSystem: String? val externalSystemModuleVersion: String? val linkedProjectPath: String? val linkedProjectId: String? val rootProjectPath: String? val externalSystemModuleGroup: String? val externalSystemModuleType: String? //region generated code @GeneratedCodeApiVersion(1) interface Builder : ExternalSystemModuleOptionsEntity, WorkspaceEntity.Builder<ExternalSystemModuleOptionsEntity>, ObjBuilder<ExternalSystemModuleOptionsEntity> { override var entitySource: EntitySource override var module: ModuleEntity override var externalSystem: String? override var externalSystemModuleVersion: String? override var linkedProjectPath: String? override var linkedProjectId: String? override var rootProjectPath: String? override var externalSystemModuleGroup: String? override var externalSystemModuleType: String? } companion object : Type<ExternalSystemModuleOptionsEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ExternalSystemModuleOptionsEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ExternalSystemModuleOptionsEntity, modification: ExternalSystemModuleOptionsEntity.Builder.() -> Unit) = modifyEntity( ExternalSystemModuleOptionsEntity.Builder::class.java, entity, modification) //endregion interface TestModulePropertiesEntity: WorkspaceEntity { val module: ModuleEntity val productionModuleId: ModuleId //region generated code @GeneratedCodeApiVersion(1) interface Builder : TestModulePropertiesEntity, WorkspaceEntity.Builder<TestModulePropertiesEntity>, ObjBuilder<TestModulePropertiesEntity> { override var entitySource: EntitySource override var module: ModuleEntity override var productionModuleId: ModuleId } companion object : Type<TestModulePropertiesEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(productionModuleId: ModuleId, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): TestModulePropertiesEntity { val builder = builder() builder.productionModuleId = productionModuleId builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: TestModulePropertiesEntity, modification: TestModulePropertiesEntity.Builder.() -> Unit) = modifyEntity( TestModulePropertiesEntity.Builder::class.java, entity, modification) //endregion
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/module.kt
2911167422
package com.github.vhromada.catalog.repository import com.github.vhromada.catalog.domain.Register import org.springframework.data.jpa.repository.JpaRepository import java.util.Optional /** * An interface represents repository for registers. * * @author Vladimir Hromada */ interface RegisterRepository : JpaRepository<Register, Int> { /** * Finds register by number. * * @param number number * @return register */ fun findByNumber(number: Int): Optional<Register> }
core/src/main/kotlin/com/github/vhromada/catalog/repository/RegisterRepository.kt
716057677
package io.multifunctions import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.shouldBe import io.multifunctions.models.Hepta import io.multifunctions.models.Hexa import io.multifunctions.models.Penta import io.multifunctions.models.Quad internal class MultiMapNotNullSpec : WordSpec() { init { "MultiMapNotNull" should { "produce a correct mapping from Pair" { val testData = listOf(Pair("one", "two")) testData mapNotNull { one, two -> one shouldBe "one" two shouldBe "two" Pair(one, two) } shouldBe testData } "produce a correct mapping from Triple" { val testData = listOf(Triple("one", "two", "three")) testData mapNotNull { one, two, three -> one shouldBe "one" two shouldBe "two" three shouldBe "three" Triple(one, two, three) } shouldBe testData } "produce a correct mapping from Quad" { val testData = listOf(Quad("one", "two", "three", "four")) testData mapNotNull { one, two, three, four -> one shouldBe "one" two shouldBe "two" three shouldBe "three" four shouldBe "four" Quad(one, two, three, four) } shouldBe testData } "produce a correct mapping from Penta" { val testData = listOf(Penta("one", "two", "three", "four", "five")) testData mapNotNull { one, two, three, four, five -> one shouldBe "one" two shouldBe "two" three shouldBe "three" four shouldBe "four" five shouldBe "five" Penta(one, two, three, four, five) } shouldBe testData } "produce a correct mapping from Hexa" { val testData = listOf(Hexa("one", "two", "three", "four", "five", "six")) testData mapNotNull { one, two, three, four, five, six -> one shouldBe "one" two shouldBe "two" three shouldBe "three" four shouldBe "four" five shouldBe "five" six shouldBe "six" Hexa(one, two, three, four, five, six) } shouldBe testData } "produce a correct mapping from Hepta" { val testData = listOf(Hepta("one", "two", "three", "four", "five", "six", "seven")) testData mapNotNull { one, two, three, four, five, six, seven -> one shouldBe "one" two shouldBe "two" three shouldBe "three" four shouldBe "four" five shouldBe "five" six shouldBe "six" seven shouldBe "seven" Hepta(one, two, three, four, five, six, seven) } shouldBe testData } "sort out null elements" { listOf( Pair(null, null), Pair("one", "two"), Pair("one", null), Pair(null, "two") ) mapNotNull { one, two -> Pair(one, two) } shouldBe listOf( Pair("one", "two"), Pair("one", null), Pair(null, "two") ) } "handle null values" { val actual = listOf( Pair("one", null), Pair("three", "four"), Pair("fife", "six"), Pair(null, null), Pair("ten", "eleven") ) val expected = listOf( Pair("one", null), Pair("three", "four"), Pair("fife", "six"), Pair("ten", "eleven") ) actual mapNotNull { one, two -> Pair(one, two) } shouldBe expected } } } }
multi-functions/src/test/kotlin/io/multifunctions/MultiMapNotNullSpec.kt
1063125497
import importInterface.data.TestInterface // "Import class 'TestInterface'" "true" // ERROR: Unresolved reference: TestInterface fun test() { val a = <caret>TestInterface } /* IGNORE_FIR */
plugins/kotlin/idea/tests/testData/quickfix/autoImports/importInterface.after.kt
1985841138
// 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.nj2k.tree import com.intellij.psi.PsiElement import com.intellij.psi.PsiExpression import com.intellij.psi.PsiSwitchExpression import org.jetbrains.kotlin.nj2k.symbols.* import org.jetbrains.kotlin.nj2k.tree.visitors.JKVisitor import org.jetbrains.kotlin.nj2k.types.JKContextType import org.jetbrains.kotlin.nj2k.types.JKNoType import org.jetbrains.kotlin.nj2k.types.JKType import org.jetbrains.kotlin.nj2k.types.JKTypeFactory abstract class JKExpression : JKAnnotationMemberValue(), PsiOwner by PsiOwnerImpl() { protected abstract val expressionType: JKType? open fun calculateType(typeFactory: JKTypeFactory): JKType? { val psiType = (psi as? PsiExpression)?.type ?: return null return typeFactory.fromPsiType(psiType) } } abstract class JKOperatorExpression : JKExpression() { abstract var operator: JKOperator override fun calculateType(typeFactory: JKTypeFactory) = expressionType ?: operator.returnType } class JKBinaryExpression( left: JKExpression, right: JKExpression, override var operator: JKOperator, override val expressionType: JKType? = null, ) : JKOperatorExpression() { var left by child(left) var right by child(right) override fun accept(visitor: JKVisitor) = visitor.visitBinaryExpression(this) } abstract class JKUnaryExpression : JKOperatorExpression() { abstract var expression: JKExpression } class JKPrefixExpression( expression: JKExpression, override var operator: JKOperator, override val expressionType: JKType? = null, ) : JKUnaryExpression() { override var expression by child(expression) override fun accept(visitor: JKVisitor) = visitor.visitPrefixExpression(this) } class JKPostfixExpression( expression: JKExpression, override var operator: JKOperator, override val expressionType: JKType? = null ) : JKUnaryExpression() { override var expression by child(expression) override fun accept(visitor: JKVisitor) = visitor.visitPostfixExpression(this) } class JKQualifiedExpression( receiver: JKExpression, selector: JKExpression, override val expressionType: JKType? = null, ) : JKExpression() { var receiver: JKExpression by child(receiver) var selector: JKExpression by child(selector) override fun accept(visitor: JKVisitor) = visitor.visitQualifiedExpression(this) } class JKParenthesizedExpression( expression: JKExpression, override val expressionType: JKType? = null ) : JKExpression() { var expression: JKExpression by child(expression) override fun calculateType(typeFactory: JKTypeFactory) = expressionType ?: expression.calculateType(typeFactory) override fun accept(visitor: JKVisitor) = visitor.visitParenthesizedExpression(this) } class JKTypeCastExpression( expression: JKExpression, type: JKTypeElement, override val expressionType: JKType? = null, ) : JKExpression() { var expression by child(expression) var type by child(type) override fun calculateType(typeFactory: JKTypeFactory) = expressionType ?: type.type override fun accept(visitor: JKVisitor) = visitor.visitTypeCastExpression(this) } class JKLiteralExpression( var literal: String, val type: LiteralType, override val expressionType: JKType? = null, ) : JKExpression() { override fun accept(visitor: JKVisitor) = visitor.visitLiteralExpression(this) override fun calculateType(typeFactory: JKTypeFactory): JKType { expressionType?.let { return it } return when (type) { LiteralType.CHAR -> typeFactory.types.char LiteralType.BOOLEAN -> typeFactory.types.boolean LiteralType.INT -> typeFactory.types.int LiteralType.LONG -> typeFactory.types.long LiteralType.FLOAT -> typeFactory.types.float LiteralType.DOUBLE -> typeFactory.types.double LiteralType.NULL -> typeFactory.types.nullableAny LiteralType.STRING, LiteralType.TEXT_BLOCK -> typeFactory.types.string } } enum class LiteralType { STRING, TEXT_BLOCK, CHAR, BOOLEAN, NULL, INT, LONG, FLOAT, DOUBLE } } class JKStubExpression(override val expressionType: JKType? = null) : JKExpression() { override fun calculateType(typeFactory: JKTypeFactory): JKType? = expressionType override fun accept(visitor: JKVisitor) = visitor.visitStubExpression(this) } class JKThisExpression( qualifierLabel: JKLabel, override val expressionType: JKType? = null, ) : JKExpression() { var qualifierLabel: JKLabel by child(qualifierLabel) override fun accept(visitor: JKVisitor) = visitor.visitThisExpression(this) } class JKSuperExpression( override val expressionType: JKType = JKNoType, val superTypeQualifier: JKClassSymbol? = null, outerTypeQualifier: JKLabel = JKLabelEmpty(), ) : JKExpression() { var outerTypeQualifier: JKLabel by child(outerTypeQualifier) override fun accept(visitor: JKVisitor) = visitor.visitSuperExpression(this) } class JKIfElseExpression( condition: JKExpression, thenBranch: JKExpression, elseBranch: JKExpression, override val expressionType: JKType? = null, ) : JKExpression() { var condition by child(condition) var thenBranch by child(thenBranch) var elseBranch by child(elseBranch) override fun accept(visitor: JKVisitor) = visitor.visitIfElseExpression(this) } class JKLambdaExpression( statement: JKStatement, parameters: List<JKParameter>, functionalType: JKTypeElement = JKTypeElement(JKNoType), returnType: JKTypeElement = JKTypeElement(JKContextType), override val expressionType: JKType? = null, ) : JKExpression() { var statement by child(statement) var parameters by children(parameters) var functionalType by child(functionalType) val returnType by child(returnType) override fun accept(visitor: JKVisitor) = visitor.visitLambdaExpression(this) } abstract class JKCallExpression : JKExpression(), JKTypeArgumentListOwner { abstract var identifier: JKMethodSymbol abstract var arguments: JKArgumentList } class JKDelegationConstructorCall( override var identifier: JKMethodSymbol, expression: JKExpression, arguments: JKArgumentList, override val expressionType: JKType? = null, ) : JKCallExpression() { override var typeArgumentList: JKTypeArgumentList by child(JKTypeArgumentList()) val expression: JKExpression by child(expression) override var arguments: JKArgumentList by child(arguments) override fun accept(visitor: JKVisitor) = visitor.visitDelegationConstructorCall(this) } class JKCallExpressionImpl( override var identifier: JKMethodSymbol, arguments: JKArgumentList = JKArgumentList(), typeArgumentList: JKTypeArgumentList = JKTypeArgumentList(), override val expressionType: JKType? = null, ) : JKCallExpression() { override var typeArgumentList by child(typeArgumentList) override var arguments by child(arguments) override fun accept(visitor: JKVisitor) = visitor.visitCallExpressionImpl(this) } class JKNewExpression( val classSymbol: JKClassSymbol, arguments: JKArgumentList, typeArgumentList: JKTypeArgumentList = JKTypeArgumentList(), classBody: JKClassBody = JKClassBody(), val isAnonymousClass: Boolean = false, override val expressionType: JKType? = null, ) : JKExpression() { var typeArgumentList by child(typeArgumentList) var arguments by child(arguments) var classBody by child(classBody) override fun accept(visitor: JKVisitor) = visitor.visitNewExpression(this) } class JKFieldAccessExpression( var identifier: JKFieldSymbol, override val expressionType: JKType? = null, ) : JKExpression() { override fun accept(visitor: JKVisitor) = visitor.visitFieldAccessExpression(this) } class JKPackageAccessExpression(var identifier: JKPackageSymbol) : JKExpression() { override val expressionType: JKType? get() = null override fun calculateType(typeFactory: JKTypeFactory): JKType? = null override fun accept(visitor: JKVisitor) = visitor.visitPackageAccessExpression(this) } class JKClassAccessExpression( var identifier: JKClassSymbol, override val expressionType: JKType? = null, ) : JKExpression() { override fun accept(visitor: JKVisitor) = visitor.visitClassAccessExpression(this) } class JKMethodAccessExpression(val identifier: JKMethodSymbol, override val expressionType: JKType? = null) : JKExpression() { override fun accept(visitor: JKVisitor) = visitor.visitMethodAccessExpression(this) } class JKTypeQualifierExpression(val type: JKType, override val expressionType: JKType? = null) : JKExpression() { override fun accept(visitor: JKVisitor) = visitor.visitTypeQualifierExpression(this) } class JKMethodReferenceExpression( qualifier: JKExpression, val identifier: JKSymbol, functionalType: JKTypeElement, val isConstructorCall: Boolean, override val expressionType: JKType? = null, ) : JKExpression() { val qualifier by child(qualifier) val functionalType by child(functionalType) override fun accept(visitor: JKVisitor) = visitor.visitMethodReferenceExpression(this) } class JKLabeledExpression( statement: JKStatement, labels: List<JKNameIdentifier>, override val expressionType: JKType? = null, ) : JKExpression() { var statement: JKStatement by child(statement) val labels: List<JKNameIdentifier> by children(labels) override fun accept(visitor: JKVisitor) = visitor.visitLabeledExpression(this) } class JKClassLiteralExpression( classType: JKTypeElement, var literalType: ClassLiteralType, override val expressionType: JKType? = null, ) : JKExpression() { val classType: JKTypeElement by child(classType) override fun accept(visitor: JKVisitor) = visitor.visitClassLiteralExpression(this) enum class ClassLiteralType { KOTLIN_CLASS, JAVA_CLASS, JAVA_PRIMITIVE_CLASS, JAVA_VOID_TYPE } } abstract class JKKtAssignmentChainLink : JKExpression() { abstract val receiver: JKExpression abstract val assignmentStatement: JKKtAssignmentStatement abstract val field: JKExpression override val expressionType: JKType? get() = null override fun calculateType(typeFactory: JKTypeFactory) = field.calculateType(typeFactory) } class JKAssignmentChainAlsoLink( receiver: JKExpression, assignmentStatement: JKKtAssignmentStatement, field: JKExpression ) : JKKtAssignmentChainLink() { override val receiver by child(receiver) override val assignmentStatement by child(assignmentStatement) override val field by child(field) override fun accept(visitor: JKVisitor) = visitor.visitAssignmentChainAlsoLink(this) } class JKAssignmentChainLetLink( receiver: JKExpression, assignmentStatement: JKKtAssignmentStatement, field: JKExpression ) : JKKtAssignmentChainLink() { override val receiver by child(receiver) override val assignmentStatement by child(assignmentStatement) override val field by child(field) override fun accept(visitor: JKVisitor) = visitor.visitAssignmentChainLetLink(this) } class JKIsExpression(expression: JKExpression, type: JKTypeElement) : JKExpression() { var type by child(type) var expression by child(expression) override val expressionType: JKType? get() = null override fun calculateType(typeFactory: JKTypeFactory) = typeFactory.types.boolean override fun accept(visitor: JKVisitor) = visitor.visitIsExpression(this) } class JKKtItExpression(override val expressionType: JKType) : JKExpression() { override fun accept(visitor: JKVisitor) = visitor.visitKtItExpression(this) } class JKKtAnnotationArrayInitializerExpression( initializers: List<JKAnnotationMemberValue>, override val expressionType: JKType? = null ) : JKExpression() { constructor(vararg initializers: JKAnnotationMemberValue) : this(initializers.toList()) val initializers: List<JKAnnotationMemberValue> by children(initializers) override fun calculateType(typeFactory: JKTypeFactory): JKType? = expressionType override fun accept(visitor: JKVisitor) = visitor.visitKtAnnotationArrayInitializerExpression(this) } class JKKtTryExpression( tryBlock: JKBlock, finallyBlock: JKBlock, catchSections: List<JKKtTryCatchSection>, override val expressionType: JKType? = null, ) : JKExpression() { var tryBlock: JKBlock by child(tryBlock) var finallyBlock: JKBlock by child(finallyBlock) var catchSections: List<JKKtTryCatchSection> by children(catchSections) override fun accept(visitor: JKVisitor) = visitor.visitKtTryExpression(this) } class JKThrowExpression(exception: JKExpression) : JKExpression() { var exception: JKExpression by child(exception) override val expressionType: JKType? get() = null override fun calculateType(typeFactory: JKTypeFactory) = typeFactory.types.nothing override fun accept(visitor: JKVisitor) = visitor.visitKtThrowExpression(this) } class JKJavaNewEmptyArray( initializer: List<JKExpression>, type: JKTypeElement, override val expressionType: JKType? = null ) : JKExpression() { val type by child(type) var initializer by children(initializer) override fun accept(visitor: JKVisitor) = visitor.visitJavaNewEmptyArray(this) } class JKJavaNewArray( initializer: List<JKExpression>, type: JKTypeElement, override val expressionType: JKType? = null ) : JKExpression() { val type by child(type) var initializer by children(initializer) override fun accept(visitor: JKVisitor) = visitor.visitJavaNewArray(this) } class JKJavaAssignmentExpression( field: JKExpression, expression: JKExpression, var operator: JKOperator, override val expressionType: JKType? = null ) : JKExpression() { var field by child(field) var expression by child(expression) override fun accept(visitor: JKVisitor) = visitor.visitJavaAssignmentExpression(this) } class JKJavaSwitchExpression( expression: JKExpression, cases: List<JKJavaSwitchCase>, override val expressionType: JKType? = null, ) : JKExpression(), JKJavaSwitchBlock { override var expression: JKExpression by child(expression) override var cases: List<JKJavaSwitchCase> by children(cases) override fun accept(visitor: JKVisitor) = visitor.visitJavaSwitchExpression(this) override fun calculateType(typeFactory: JKTypeFactory): JKType? { val psiType = (psi as? PsiSwitchExpression)?.type ?: return null return typeFactory.fromPsiType(psiType) } } class JKKtWhenExpression( expression: JKExpression, cases: List<JKKtWhenCase>, override val expressionType: JKType?, ) : JKExpression(), JKKtWhenBlock { override var expression: JKExpression by child(expression) override var cases: List<JKKtWhenCase> by children(cases) override fun accept(visitor: JKVisitor) = visitor.visitKtWhenExpression(this) override fun calculateType(typeFactory: JKTypeFactory): JKType? = expressionType } class JKErrorExpression( override var psi: PsiElement?, override val reason: String?, override val expressionType: JKType? = null ) : JKExpression(), JKErrorElement { override fun calculateType(typeFactory: JKTypeFactory): JKType = expressionType ?: typeFactory.types.nothing override fun accept(visitor: JKVisitor) = visitor.visitExpression(this) }
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/expressions.kt
3892848895
package org.jetbrains.haskell.debugger import com.intellij.xdebugger.XDebugProcess import com.intellij.xdebugger.XDebugSession import com.intellij.execution.ui.ExecutionConsole import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider import com.intellij.xdebugger.XSourcePosition import com.intellij.execution.process.ProcessHandler import com.intellij.xdebugger.breakpoints.XBreakpointProperties import com.intellij.xdebugger.breakpoints.XBreakpoint import com.intellij.xdebugger.breakpoints.XBreakpointHandler import com.intellij.execution.ui.ConsoleView import com.intellij.xdebugger.breakpoints.XLineBreakpoint import org.jetbrains.haskell.debugger.breakpoints.HaskellLineBreakpointType import org.jetbrains.haskell.debugger.breakpoints.HaskellLineBreakpointHandler import java.util.concurrent.locks.Lock import java.util.concurrent.locks.Condition import org.jetbrains.haskell.debugger.utils.HaskellUtils import org.jetbrains.haskell.debugger.highlighting.HsDebugSessionListener import org.jetbrains.haskell.debugger.parser.LocalBinding import java.util.concurrent.locks.ReentrantLock import org.jetbrains.haskell.debugger.protocol.ForceCommand import org.jetbrains.haskell.debugger.config.HaskellDebugSettings import com.intellij.xdebugger.ui.XDebugTabLayouter import com.intellij.openapi.actionSystem.DefaultActionGroup import org.jetbrains.haskell.debugger.protocol.SyncCommand import org.jetbrains.haskell.debugger.utils.SyncObject import org.jetbrains.haskell.debugger.breakpoints.HaskellExceptionBreakpointHandler import org.jetbrains.haskell.debugger.breakpoints.HaskellExceptionBreakpointProperties import java.util.ArrayList import org.jetbrains.haskell.debugger.protocol.BreakpointListCommand import org.jetbrains.haskell.debugger.protocol.SetBreakpointByIndexCommand import org.jetbrains.haskell.debugger.protocol.SetBreakpointCommand import org.jetbrains.haskell.debugger.parser.BreakInfo import com.intellij.notification.Notifications import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.xdebugger.impl.actions.StepOutAction import com.intellij.xdebugger.impl.actions.ForceStepIntoAction import org.jetbrains.haskell.debugger.procdebuggers.ProcessDebugger import org.jetbrains.haskell.debugger.procdebuggers.GHCiDebugger import org.jetbrains.haskell.debugger.procdebuggers.RemoteDebugger import org.jetbrains.haskell.debugger.history.HistoryManager import org.jetbrains.haskell.debugger.prochandlers.HaskellDebugProcessHandler import com.intellij.execution.ui.RunnerLayoutUi import java.util.Deque import com.intellij.xdebugger.frame.XSuspendContext import java.util.ArrayDeque import org.jetbrains.haskell.debugger.procdebuggers.utils.DefaultRespondent import org.jetbrains.haskell.debugger.procdebuggers.utils.DebugRespondent import com.intellij.xdebugger.impl.XDebugSessionImpl import org.jetbrains.haskell.debugger.config.DebuggerType import org.jetbrains.haskell.repl.HaskellConsole /** * Main class for managing debug process and sending commands to real debug process through it's ProcessDebugger member. * * Attention! When sending commands to the underlying ProcessDebugger they are enqueued. But some commands may require * a lot of time to finish and, for example, if you call asynchronous command that needs much time to finish and * after that call synchronous command that freezes UI thread, you will get all the UI frozen until the first * command is finished. To check no command is in progress use * {@link org.jetbrains.haskell.debugger.HaskellDebugProcess#isReadyForNextCommand} * * @see org.jetbrains.haskell.debugger.HaskellDebugProcess#isReadyForNextCommand */ class HaskellDebugProcess(session: XDebugSession, val executionConsole: ExecutionConsole, val _processHandler: HaskellDebugProcessHandler, val stopAfterTrace: Boolean) : XDebugProcess(session) { //public val historyManager: HistoryManager = HistoryManager(session , this) var exceptionBreakpoint: XBreakpoint<HaskellExceptionBreakpointProperties>? = null private set val debugger: ProcessDebugger private val debugRespondent: DebugRespondent = DefaultRespondent(this) private val contexts: Deque<XSuspendContext> = ArrayDeque() private val debugProcessStateUpdater: DebugProcessStateUpdater private val _editorsProvider: XDebuggerEditorsProvider = HaskellDebuggerEditorsProvider() private val _breakpointHandlers: Array<XBreakpointHandler<*>> = arrayOf(HaskellLineBreakpointHandler(getSession()!!.project, HaskellLineBreakpointType::class.java, this), HaskellExceptionBreakpointHandler(this) ) private val registeredBreakpoints: MutableMap<BreakpointPosition, BreakpointEntry> = hashMapOf() private val BREAK_BY_INDEX_ERROR_MSG = "Only remote debugger supports breakpoint setting by index" init { val debuggerIsGHCi = HaskellDebugSettings.getInstance().state.debuggerType == DebuggerType.GHCI if (debuggerIsGHCi) { debugProcessStateUpdater = GHCiDebugProcessStateUpdater() debugger = GHCiDebugger(debugRespondent, _processHandler, executionConsole as ConsoleView, debugProcessStateUpdater.INPUT_READINESS_PORT) debugProcessStateUpdater.debugger = debugger } else { debugProcessStateUpdater = RemoteDebugProcessStateUpdater() debugger = RemoteDebugger(debugRespondent, _processHandler) debugProcessStateUpdater.debugger = debugger } _processHandler.setDebugProcessListener(debugProcessStateUpdater) } // XDebugProcess methods overriding override fun getEditorsProvider(): XDebuggerEditorsProvider = _editorsProvider override fun getBreakpointHandlers() : Array<XBreakpointHandler<out XBreakpoint<out XBreakpointProperties<*>?>?>> = _breakpointHandlers override fun doGetProcessHandler(): ProcessHandler? = _processHandler override fun createConsole(): ExecutionConsole = executionConsole override fun startStepOver() = debugger.stepOver() override fun startStepInto() = debugger.stepInto() override fun startStepOut() { val msg = "'Step out' not implemented" Notifications.Bus.notify(Notification("", "Debug execution error", msg, NotificationType.WARNING)) session!!.positionReached(session!!.suspendContext!!) } override fun stop() { //historyManager.clean() debugger.close() debugProcessStateUpdater.close() } override fun resume() = debugger.resume() override fun runToPosition(position: XSourcePosition) = debugger.runToPosition( HaskellUtils.getModuleName(session!!.project, position.file), HaskellUtils.zeroBasedToHaskellLineNumber(position.line)) override fun sessionInitialized() { super.sessionInitialized() val currentSession = session currentSession?.addSessionListener(HsDebugSessionListener(currentSession)) debugger.prepareDebugger() if (stopAfterTrace) { debugger.trace(null) } } override fun createTabLayouter(): XDebugTabLayouter = object : XDebugTabLayouter() { override fun registerAdditionalContent(ui: RunnerLayoutUi) { //historyManager.registerContent(ui) } } override fun registerAdditionalActions(leftToolbar: DefaultActionGroup, topToolbar: DefaultActionGroup, settings: DefaultActionGroup) { //temporary code for removal of unused actions from debug panel var stepOut: StepOutAction? = null var forceStepInto: ForceStepIntoAction? = null for (action in topToolbar.childActionsOrStubs) { if (action is StepOutAction) { stepOut = action } if (action is ForceStepIntoAction) { forceStepInto = action } } topToolbar.remove(stepOut) topToolbar.remove(forceStepInto) //historyManager.registerActions(topToolbar) } // Class' own methods fun startTrace(line: String?) { //historyManager.saveState() val context = session!!.suspendContext if (context != null) { contexts.add(context) } // disable actions debugger.trace(line) } fun traceFinished() { /* if (historyManager.hasSavedStates()) { historyManager.loadState() if (!contexts.isEmpty()) { getSession()!!.positionReached(contexts.pollLast()!!) } } else if (stopAfterTrace) { getSession()!!.stop() } else { } */ } fun isReadyForNextCommand(): Boolean = debugger.isReadyForNextCommand() fun addExceptionBreakpoint(breakpoint: XBreakpoint<HaskellExceptionBreakpointProperties>) { exceptionBreakpoint = breakpoint debugger.setExceptionBreakpoint(breakpoint.properties!!.state.exceptionType == HaskellExceptionBreakpointProperties.ExceptionType.ERROR) } fun removeExceptionBreakpoint(breakpoint: XBreakpoint<HaskellExceptionBreakpointProperties>) { assert(breakpoint == exceptionBreakpoint) exceptionBreakpoint = null debugger.removeExceptionBreakpoint() } fun setBreakpointNumberAtLine(breakpointNumber: Int, module: String, line: Int) { val entry = registeredBreakpoints.get(BreakpointPosition(module, line)) if (entry != null) { entry.breakpointNumber = breakpointNumber } } fun getBreakpointAtPosition(module: String, line: Int): XLineBreakpoint<XBreakpointProperties<*>>? = registeredBreakpoints.get(BreakpointPosition(module, line))?.breakpoint fun addBreakpoint(module: String, line: Int, breakpoint: XLineBreakpoint<XBreakpointProperties<*>>) { registeredBreakpoints.put(BreakpointPosition(module, line), BreakpointEntry(null, breakpoint)) debugger.setBreakpoint(module, line) } fun addBreakpointByIndex(module: String, index: Int, breakpoint: XLineBreakpoint<XBreakpointProperties<*>>) { if (HaskellDebugSettings.getInstance().state.debuggerType == DebuggerType.REMOTE) { val line = HaskellUtils.zeroBasedToHaskellLineNumber(breakpoint.line) registeredBreakpoints.put(BreakpointPosition(module, line), BreakpointEntry(index, breakpoint)) val command = SetBreakpointByIndexCommand(module, index, SetBreakpointCommand.Companion.StandardSetBreakpointCallback(module, debugRespondent)) debugger.enqueueCommand(command) } else { throw RuntimeException(BREAK_BY_INDEX_ERROR_MSG) } } fun removeBreakpoint(module: String, line: Int) { val breakpointNumber: Int? = registeredBreakpoints.get(BreakpointPosition(module, line))?.breakpointNumber if (breakpointNumber != null) { registeredBreakpoints.remove(BreakpointPosition(module, line)) debugger.removeBreakpoint(module, breakpointNumber) } } fun forceSetValue(localBinding: LocalBinding) { if (localBinding.name != null) { val syncObject: Lock = ReentrantLock() val bindingValueIsSet: Condition = syncObject.newCondition() val syncLocalBinding: LocalBinding = LocalBinding(localBinding.name, "", null) syncObject.lock() try { debugger.force(localBinding.name!!, ForceCommand.StandardForceCallback(syncLocalBinding, syncObject, bindingValueIsSet, this)) while (syncLocalBinding.value == null) { bindingValueIsSet.await() } if (syncLocalBinding.value?.isNotEmpty() ?: false) { localBinding.value = syncLocalBinding.value } } finally { syncObject.unlock() } } } fun syncBreakListForLine(moduleName: String, lineNumber: Int): ArrayList<BreakInfo> { if (HaskellDebugSettings.getInstance().state.debuggerType == DebuggerType.REMOTE) { val syncObject = SyncObject() val resultArray: ArrayList<BreakInfo> = ArrayList() val callback = BreakpointListCommand.Companion.DefaultCallback(resultArray) val command = BreakpointListCommand(moduleName, lineNumber, syncObject, callback) syncCommand(command, syncObject) return resultArray } return ArrayList() } private class BreakpointPosition(val module: String, val line: Int) { override fun equals(other: Any?): Boolean { if (other == null || other !is BreakpointPosition) { return false } return module.equals(other.module) && line.equals(other.line) } override fun hashCode(): Int = module.hashCode() * 31 + line } private class BreakpointEntry(var breakpointNumber: Int?, val breakpoint: XLineBreakpoint<XBreakpointProperties<*>>) /** * Used to make synchronous requests to debugger. * * @see org.jetbrains.haskell.debugger.utils.SyncObject * @see org.jetbrains.haskell.debugger.HaskellDebugProcess#isReadyForNextCommand */ private fun syncCommand(command: SyncCommand<*>, syncObject: SyncObject) { syncObject.lock() try { debugger.enqueueCommand(command) while (!syncObject.signaled()) { syncObject.await() } } finally { syncObject.unlock() } } }
plugin/src/org/jetbrains/haskell/debugger/HaskellDebugProcess.kt
1042292854
package org.stepic.droid.adaptive.ui.activities import android.view.MenuItem import org.stepic.droid.adaptive.ui.fragments.RecommendationsFragment import org.stepic.droid.base.SingleFragmentActivity import org.stepic.droid.util.AppConstants class AdaptiveCourseActivity : SingleFragmentActivity() { override fun createFragment() = RecommendationsFragment.newInstance(requireNotNull(intent.getParcelableExtra(AppConstants.KEY_COURSE_BUNDLE))) override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } override fun applyTransitionPrev() { //no-op } }
app/src/main/java/org/stepic/droid/adaptive/ui/activities/AdaptiveCourseActivity.kt
932224087
// 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.uast.java import com.intellij.psi.PsiClassInitializer import com.intellij.psi.PsiElement import org.jetbrains.uast.* import org.jetbrains.uast.java.internal.JavaUElementWithComments class JavaUClassInitializer( override val sourcePsi: PsiClassInitializer, uastParent: UElement? ) : JavaAbstractUElement(uastParent), UClassInitializerEx, JavaUElementWithComments, UAnchorOwner, PsiClassInitializer by sourcePsi { @Suppress("OverridingDeprecatedMember") override val psi get() = sourcePsi override val javaPsi: PsiClassInitializer = sourcePsi override val uastAnchor: UIdentifier? get() = null override val uastBody: UExpression by lz { UastFacade.findPlugin(sourcePsi.body)?.convertElement(sourcePsi.body, this, null) as? UExpression ?: UastEmptyExpression(this) } override val uAnnotations: List<JavaUAnnotation> by lz { sourcePsi.annotations.map { JavaUAnnotation(it, this) } } override fun equals(other: Any?): Boolean = this === other override fun hashCode(): Int = sourcePsi.hashCode() override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement }
uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUClassInitializer.kt
1887877836
package com.glodanif.bluetoothchat.data.model import com.glodanif.bluetoothchat.data.database.ChatDatabase import com.glodanif.bluetoothchat.data.entity.Conversation class ConversationsStorageImpl(db: ChatDatabase) : ConversationsStorage { private val dao = db.conversationsDao() override suspend fun getContacts() = dao.getContacts() override suspend fun getConversations() = dao.getAllConversationsWithMessages() override suspend fun getConversationByAddress(address: String) = dao.getConversationByAddress(address) override suspend fun insertConversation(conversation: Conversation) { dao.insert(conversation) } override suspend fun removeConversationByAddress(address: String) { dao.delete(address) } }
app/src/main/kotlin/com/glodanif/bluetoothchat/data/model/ConversationsStorageImpl.kt
2628690499
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.fixtures import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.impl.GuiTestUtilKt import com.intellij.testGuiFramework.impl.actionButton import com.intellij.testGuiFramework.impl.popupMenu import com.intellij.testGuiFramework.util.logInfo import com.intellij.testGuiFramework.util.step import com.intellij.ui.popup.PopupFactoryImpl import org.fest.swing.core.Robot import org.fest.swing.exception.ComponentLookupException import org.fest.swing.fixture.JButtonFixture import org.fest.swing.timing.Pause import javax.swing.JButton import javax.swing.JList /** * @author Artem.Gainanov */ class RunConfigurationListFixture(val myRobot: Robot, val myIde: IdeFrameFixture) { private val EDIT_CONFIGURATIONS: String = "Edit Configurations..." /** * Returns a list of available run configurations * except for "Edit configuration" and "save configuration" */ fun getRunConfigurationList(): List<String> { GuiTestUtilKt.repeatUntil({ GuiTestUtilKt.isComponentShowing(JList::class.java) }, { showPopup() }) val list = myRobot.finder() .find(myIde.target()) { it is JList<*> } as JList<*> val returnList: MutableList<String> = mutableListOf() for (i in 0 until list.model.size) { returnList.add(i, list.model.getElementAt(i).toString()) } //Close popup showPopup() return returnList.filter { it != EDIT_CONFIGURATIONS && !it.contains("Save ") } } /** * Opens up run configuration popup and chooses given RC * @param name */ fun configuration(name: String): RunActionFixture { showPopup() myIde.popupMenu(name, Timeouts.minutes02).clickSearchedItem() return RunActionFixture() } /** * Trying to click on Edit Configurations attempt times. */ fun editConfigurations(attempts: Int = 5) { step("click on 'Edit Configurations...' menu") { try { JButtonFixture(myRobot, addConfigurationButton()).click() } catch (e: ComponentLookupException) { step("initial attempt failed, search again") { for (i in 0 until attempts) { logInfo("attempt #$i") showPopup() Pause.pause(1000) if (getEditConfigurationsState()) { break } //Close popup showPopup() } myIde.popupMenu(EDIT_CONFIGURATIONS, Timeouts.minutes02).clickSearchedItem() } } } } /** * Click on Add Configuration button. * Available if no configurations are available in the RC list */ fun addConfiguration() { JButtonFixture(myRobot, addConfigurationButton()).click() } inner class RunActionFixture { private fun clickActionButton(buttonName: String) { with(myIde) { actionButton(buttonName) }.click() } fun run() { clickActionButton("Run") } fun debug() { clickActionButton("Debug") } fun runWithCoverage() { clickActionButton("Run with Coverage") } fun stop() { clickActionButton("Stop") } } private fun showPopup() { step("show or close popup for list of run/debug configurations") { JButtonFixture(myRobot, getRunConfigurationListButton()).click() } } private fun addConfigurationButton(): JButton { return step("search 'Add Configuration...' button") { val button = myRobot.finder() .find(myIde.target()) { it is JButton && it.text == "Add Configuration..." && it.isShowing } as JButton logInfo("found button '$button'") return@step button } } private fun getRunConfigurationListButton(): JButton { return myRobot.finder() .find(myIde.target()) { it is JButton && it.parent.parent is ActionToolbarImpl && it.text != "" && it.isShowing } as JButton } private fun getEditConfigurationsState(): Boolean { return step("get '$EDIT_CONFIGURATIONS' state") { val list = myRobot.finder() .find(myIde.target()) { it is JList<*> } as JList<*> val actionItem = list.model.getElementAt(0) as PopupFactoryImpl.ActionItem logInfo("item '$EDIT_CONFIGURATIONS' is ${if(actionItem.isEnabled) "" else "NOT "}enabled") return@step actionItem.isEnabled } } }
platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/RunConfigurationListFixture.kt
13327109
// 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.execution.stateExecutionWidget import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.util.registry.Registry import org.jetbrains.annotations.Nls import java.util.function.Predicate import javax.swing.Icon import kotlin.streams.toList interface StateWidgetProcess { companion object { private const val runDebugKey = "ide.new.navbar" private const val runDebugRerunAvailable = "ide.new.navbar.rerun.available" const val STATE_WIDGET_MORE_ACTION_GROUP = "StateWidgetMoreActionGroup" const val STATE_WIDGET_GROUP = "StateWidgetProcessesActionGroup" @JvmStatic fun isAvailable(): Boolean { return Registry.get(runDebugKey).asBoolean() } fun isRerunAvailable(): Boolean { return Registry.get(runDebugRerunAvailable).asBoolean() } val EP_NAME: ExtensionPointName<StateWidgetProcess> = ExtensionPointName("com.intellij.stateWidgetProcess") @JvmStatic fun getProcesses(): List<StateWidgetProcess> = EP_NAME.extensionList @JvmStatic fun getProcessesByExecutorId(executorId: String): List<StateWidgetProcess> { return getProcesses().filter { it.executorId == executorId }.toList() } } val ID: String val executorId: String val name: @Nls String val actionId: String val moreActionGroupName: String val moreActionSubGroupName: String val showInBar: Boolean fun rerunAvailable(): Boolean = false fun getStopIcon(): Icon? = null }
platform/lang-api/src/com/intellij/execution/stateExecutionWidget/StateWidgetProcess.kt
213429834
@file:Suppress("unused") package com.agoda.kakao.text import android.view.View import androidx.test.espresso.DataInteraction import com.agoda.kakao.common.builders.ViewBuilder import com.agoda.kakao.common.views.KBaseView import org.hamcrest.Matcher /** * View with BaseActions and TextViewAssertions * * @see com.agoda.kakao.common.actions.BaseActions * @see TextViewActions * @see TextViewAssertions */ class KTextView : KBaseView<KTextView>, TextViewActions, TextViewAssertions { constructor(function: ViewBuilder.() -> Unit) : super(function) constructor(parent: Matcher<View>, function: ViewBuilder.() -> Unit) : super(parent, function) constructor(parent: DataInteraction, function: ViewBuilder.() -> Unit) : super(parent, function) }
kakao/src/main/kotlin/com/agoda/kakao/text/KTextView.kt
1838812031
package slatekit.data.encoders import slatekit.common.values.Record import slatekit.common.data.DataType import slatekit.common.data.Encoding import slatekit.common.data.Value import slatekit.common.ext.orElse import slatekit.data.Consts /** * Support for encoding to/from kotlin value to a SQL value * The encoders here are all for basic data types ( bool, string, short, int, long, double ) */ /** * @param dataType: This allows for supporting the conversion of bools to integers ( for sqlite ) */ open class BoolEncoder(val dataType: DataType = DataType.DTBool) : SqlEncoder<Boolean> { override fun encode(value: Boolean?): String = value?.let { if (value) "1" else "0" } ?: Consts.NULL override fun decode(record: Record, name: String): Boolean? = record.getBoolOrNull(name) override fun convert(name:String, value: Boolean?): Value { val finalValue = when(dataType){ DataType.DTInt -> value?.let { if(it) 1 else 0 } else -> value } return Value(name, dataType, finalValue, encode(value)) } } open class StringEncoder : SqlEncoder<String> { override fun encode(value: String?): String = value?.let { "'" + Encoding.ensureValue(value.orElse("")) + "'" } ?: Consts.NULL override fun decode(record: Record, name: String): String? = record.getStringOrNull(name) override fun convert(name:String, value: String?): Value = Value(name, DataType.DTString, value, encode(value)) } /** * @param dataType: This allows for supporting the conversion of shorts to integers ( for sqlite ) */ open class ShortEncoder(val dataType: DataType = DataType.DTShort) : SqlEncoder<Short> { override fun encode(value: Short?): String = value?.toString() ?: Consts.NULL override fun decode(record: Record, name: String): Short? = record.getShortOrNull(name) override fun convert(name:String, value: Short?): Value { val finalValue = when(dataType){ DataType.DTLong -> value?.let { it.toInt() } else -> value } return Value(name, dataType, finalValue, encode(value)) } } open class IntEncoder(val dataType: DataType = DataType.DTInt) : SqlEncoder<Int> { override fun encode(value: Int?): String = value?.toString() ?: Consts.NULL override fun decode(record: Record, name: String): Int? = record.getIntOrNull(name) override fun convert(name:String, value: Int?): Value { val finalValue = when(dataType){ DataType.DTLong -> value?.let { it.toLong() } else -> value } return Value(name, dataType, finalValue, encode(value)) } } /** * @param dataType: This allows for supporting the conversion of bools to integers ( for sqlite ) */ open class LongEncoder(val dataType: DataType = DataType.DTLong) : SqlEncoder<Long> { override fun encode(value: Long?): String = value?.toString() ?: Consts.NULL override fun decode(record: Record, name: String): Long? = record.getLongOrNull(name) override fun convert(name:String, value: Long?): Value = Value(name, dataType, value, encode(value)) } /** * @param dataType: This allows for supporting the conversion of bools to integers ( for sqlite ) */ open class FloatEncoder(val dataType: DataType = DataType.DTFloat) : SqlEncoder<Float> { override fun encode(value: Float?): String = value?.toString() ?: Consts.NULL override fun decode(record: Record, name: String): Float? = record.getFloatOrNull(name) override fun convert(name:String, value: Float?): Value { val finalValue = when(dataType){ DataType.DTDouble -> value?.let { it.toDouble() } else -> value } return Value(name, dataType, finalValue, encode(value)) } } open class DoubleEncoder : SqlEncoder<Double> { override fun encode(value: Double?): String = value?.toString() ?: Consts.NULL override fun decode(record: Record, name: String): Double? = record.getDoubleOrNull(name) override fun convert(name:String, value: Double?): Value = Value(name, DataType.DTDouble, value, encode(value)) }
src/lib/kotlin/slatekit-data/src/main/kotlin/slatekit/data/encoders/Basics.kt
832708003
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages import com.intellij.ide.ui.AntialiasingType import com.intellij.ui.JBColor import com.intellij.ui.RelativeFont import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.GraphicsUtil import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaledEmptyBorder import java.awt.Graphics import javax.swing.JLabel @Suppress("MagicNumber") // Thanks Swing class TagComponent(name: String) : JLabel() { init { foreground = JBColor.namedColor("Plugins.tagForeground", JBColor(0x808080, 0x808080)) background = JBColor.namedColor("Plugins.tagBackground", JBColor(0xE8E8E8, 0xE8E8E8)) isOpaque = false border = scaledEmptyBorder(vSize = 1, hSize = 8) RelativeFont.TINY.install(this) text = name toolTipText = PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.tooltip") GraphicsUtil.setAntialiasingType(this, AntialiasingType.getAAHintForSwingComponent()) } @ScaledPixels var tagDiameterPx: Int = 4.scaled() set(value) { require(value >= 0) { "The diameter must be equal to or greater than zero." } field = JBUIScale.scale(value) } override fun paintComponent(g: Graphics) { val config = GraphicsUtil.setupRoundedBorderAntialiasing(g) g.color = background g.fillRoundRect(0, 0, width, height, tagDiameterPx, tagDiameterPx) config.restore() super.paintComponent(g) } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/TagComponent.kt
2044904581
package codegen.innerClass.doubleInner import kotlin.test.* open class Father(val param: String) { abstract inner class InClass { fun work(): String { return param } } inner class Child(p: String) : Father(p) { inner class Child2 : Father.InClass { constructor(): super() } } } fun box(): String { return Father("fail").Child("OK").Child2().work() } @Test fun runTest() { println(box()) }
backend.native/tests/codegen/innerClass/doubleInner.kt
1784392958
// Auto-generated by GeneratePrimitiveVsObjectEqualityTestData. Do not edit! val nx: Any? = 0.toByte() val nn: Any? = null val x: Byte = 0.toByte() val y: Byte = 1.toByte() fun box(): String { val ax: Any? = 0.toByte() val an: Any? = null val bx: Byte = 0.toByte() val by: Byte = 1.toByte() return when { 0.toByte() != nx -> "Fail 0" 1.toByte() == nx -> "Fail 1" !(0.toByte() == nx) -> "Fail 2" !(1.toByte() != nx) -> "Fail 3" x != nx -> "Fail 4" y == nx -> "Fail 5" !(x == nx) -> "Fail 6" !(y != nx) -> "Fail 7" 0.toByte() == nn -> "Fail 8" !(0.toByte() != nn) -> "Fail 9" x == nn -> "Fail 10" !(x != nn) -> "Fail 11" 0.toByte() != ax -> "Fail 12" 1.toByte() == ax -> "Fail 13" !(0.toByte() == ax) -> "Fail 14" !(1.toByte() != ax) -> "Fail 15" x != ax -> "Fail 16" y == ax -> "Fail 17" !(x == ax) -> "Fail 18" !(y != ax) -> "Fail 19" bx != ax -> "Fail 20" by == ax -> "Fail 21" !(bx == ax) -> "Fail 22" !(by != ax) -> "Fail 23" 0.toByte() == an -> "Fail 24" !(0.toByte() != an) -> "Fail 25" x == an -> "Fail 26" !(x != an) -> "Fail 27" bx == an -> "Fail 28" !(bx != an) -> "Fail 29" else -> "OK" } }
backend.native/tests/external/codegen/box/primitiveTypes/equalityWithObject/generated/primitiveEqObjectByte.kt
1462334242
class JsonObject() { } class JsonArray() { } public interface Formatter<in IN: Any, out OUT: Any> { public fun format(source: IN?): OUT } public interface MultiFormatter <in IN: Any, out OUT: Any> { public fun format(source: Collection<IN>): OUT } public class Project() { } public interface JsonFormatter<in IN: Any>: Formatter<IN, JsonObject>, MultiFormatter<IN, JsonArray> { public override fun format(source: Collection<IN>): JsonArray { return JsonArray(); } } public class ProjectJsonFormatter(): JsonFormatter<Project> { public override fun format(source: Project?): JsonObject { return JsonObject() } } fun box(): String { val formatter = ProjectJsonFormatter() return if (formatter.format(Project()) != null) "OK" else "fail" }
backend.native/tests/external/codegen/box/classes/kt2390.kt
4073919843
/* * Copyright © 2017-2021 WireGuard LLC. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package com.wireguard.android.util import android.content.res.Resources import android.os.RemoteException import com.wireguard.android.backend.BackendException import com.wireguard.android.util.RootShell.RootShellException import com.wireguard.config.BadConfigException import com.wireguard.config.InetEndpoint import com.wireguard.config.InetNetwork import com.wireguard.config.ParseException import com.wireguard.crypto.Key import com.wireguard.crypto.KeyFormatException import org.blokada.R import ui.MainApplication import java.net.InetAddress object ErrorMessages { private val BCE_REASON_MAP = mapOf( BadConfigException.Reason.INVALID_KEY to R.string.bad_config_reason_invalid_key, BadConfigException.Reason.INVALID_NUMBER to R.string.bad_config_reason_invalid_number, BadConfigException.Reason.INVALID_VALUE to R.string.bad_config_reason_invalid_value, BadConfigException.Reason.MISSING_ATTRIBUTE to R.string.bad_config_reason_missing_attribute, BadConfigException.Reason.MISSING_SECTION to R.string.bad_config_reason_missing_section, BadConfigException.Reason.SYNTAX_ERROR to R.string.bad_config_reason_syntax_error, BadConfigException.Reason.UNKNOWN_ATTRIBUTE to R.string.bad_config_reason_unknown_attribute, BadConfigException.Reason.UNKNOWN_SECTION to R.string.bad_config_reason_unknown_section ) private val BE_REASON_MAP = mapOf( BackendException.Reason.UNKNOWN_KERNEL_MODULE_NAME to R.string.module_version_error, BackendException.Reason.WG_QUICK_CONFIG_ERROR_CODE to R.string.tunnel_config_error, BackendException.Reason.TUNNEL_MISSING_CONFIG to R.string.no_config_error, BackendException.Reason.VPN_NOT_AUTHORIZED to R.string.vpn_not_authorized_error, BackendException.Reason.UNABLE_TO_START_VPN to R.string.vpn_start_error, BackendException.Reason.TUN_CREATION_ERROR to R.string.tun_create_error, BackendException.Reason.GO_ACTIVATION_ERROR_CODE to R.string.tunnel_on_error, //BackendException.Reason.DNS_RESOLUTION_FAILURE to R.string.tunnel_dns_failure ) private val KFE_FORMAT_MAP = mapOf( Key.Format.BASE64 to R.string.key_length_explanation_base64, Key.Format.BINARY to R.string.key_length_explanation_binary, Key.Format.HEX to R.string.key_length_explanation_hex ) private val KFE_TYPE_MAP = mapOf( KeyFormatException.Type.CONTENTS to R.string.key_contents_error, KeyFormatException.Type.LENGTH to R.string.key_length_error ) private val PE_CLASS_MAP = mapOf( InetAddress::class.java to R.string.parse_error_inet_address, InetEndpoint::class.java to R.string.parse_error_inet_endpoint, InetNetwork::class.java to R.string.parse_error_inet_network, Int::class.java to R.string.parse_error_integer ) private val RSE_REASON_MAP = mapOf( RootShellException.Reason.NO_ROOT_ACCESS to R.string.error_root, RootShellException.Reason.SHELL_MARKER_COUNT_ERROR to R.string.shell_marker_count_error, RootShellException.Reason.SHELL_EXIT_STATUS_READ_ERROR to R.string.shell_exit_status_read_error, RootShellException.Reason.SHELL_START_ERROR to R.string.shell_start_error, RootShellException.Reason.CREATE_BIN_DIR_ERROR to R.string.create_bin_dir_error, RootShellException.Reason.CREATE_TEMP_DIR_ERROR to R.string.create_temp_dir_error ) operator fun get(throwable: Throwable?): String { val resources = MainApplication.get().resources if (throwable == null) return resources.getString(R.string.unknown_error) val rootCause = rootCause(throwable) return when { rootCause is BadConfigException -> { val reason = getBadConfigExceptionReason(resources, rootCause) val context = if (rootCause.location == BadConfigException.Location.TOP_LEVEL) { resources.getString(R.string.bad_config_context_top_level, rootCause.section.getName()) } else { resources.getString(R.string.bad_config_context, rootCause.section.getName(), rootCause.location.getName()) } val explanation = getBadConfigExceptionExplanation(resources, rootCause) resources.getString(R.string.bad_config_error, reason, context) + explanation } rootCause is BackendException -> { resources.getString(BE_REASON_MAP.getValue(rootCause.reason), *rootCause.format) } rootCause is RootShellException -> { resources.getString(RSE_REASON_MAP.getValue(rootCause.reason), *rootCause.format) } // rootCause is Resources.NotFoundException -> { // resources.getString(R.string.error_no_qr_found) // } // rootCause is ChecksumException -> { // resources.getString(R.string.error_qr_checksum) // } rootCause.message != null -> { rootCause.message!! } else -> { val errorType = rootCause.javaClass.simpleName resources.getString(R.string.generic_error, errorType) } } } private fun getBadConfigExceptionExplanation(resources: Resources, bce: BadConfigException): String { if (bce.cause is KeyFormatException) { val kfe = bce.cause as KeyFormatException? if (kfe!!.type == KeyFormatException.Type.LENGTH) return resources.getString(KFE_FORMAT_MAP.getValue(kfe.format)) } else if (bce.cause is ParseException) { val pe = bce.cause as ParseException? if (pe!!.message != null) return ": ${pe.message}" } else if (bce.location == BadConfigException.Location.LISTEN_PORT) { return resources.getString(R.string.bad_config_explanation_udp_port) } else if (bce.location == BadConfigException.Location.MTU) { return resources.getString(R.string.bad_config_explanation_positive_number) } else if (bce.location == BadConfigException.Location.PERSISTENT_KEEPALIVE) { return resources.getString(R.string.bad_config_explanation_pka) } return "" } private fun getBadConfigExceptionReason(resources: Resources, bce: BadConfigException): String { if (bce.cause is KeyFormatException) { val kfe = bce.cause as KeyFormatException? return resources.getString(KFE_TYPE_MAP.getValue(kfe!!.type)) } else if (bce.cause is ParseException) { val pe = bce.cause as ParseException? val type = resources.getString((if (PE_CLASS_MAP.containsKey(pe!!.parsingClass)) PE_CLASS_MAP[pe.parsingClass] else R.string.parse_error_generic)!!) return resources.getString(R.string.parse_error_reason, type, pe.text) } return resources.getString(BCE_REASON_MAP.getValue(bce.reason), bce.text) } private fun rootCause(throwable: Throwable): Throwable { var cause = throwable while (cause.cause != null) { if (cause is BadConfigException || cause is BackendException || cause is RootShellException) break val nextCause = cause.cause!! if (nextCause is RemoteException) break cause = nextCause } return cause } }
android5/app/wireguard-android/ui/src/main/java/com/wireguard/android/util/ErrorMessages.kt
126105134
val c = Unit val d = c fun box(): String { c d return "OK" }
backend.native/tests/external/codegen/box/unit/kt3634.kt
446669157
import kotlin.test.* import kotlin.test.assertTrue import kotlin.test.assertEquals import kotlin.test.assertNotEquals val p = Pair(1, "a") val t = Triple(1, "a", 0.07) fun box() { assertEquals(Pair(1, "a"), p) assertNotEquals(Pair(2, "a"), p) assertNotEquals(Pair(1, "b"), p) assertTrue(!p.equals(null)) assertNotEquals("", (p as Any)) }
backend.native/tests/external/stdlib/TuplesTest/pairEquals.kt
2361575123
package codegen.branching.when8 import kotlin.test.* @Test fun runTest() { when (true) { true -> println("true") false -> println("false") } }
backend.native/tests/codegen/branching/when8.kt
3371834738
import kotlin.test.* import kotlin.comparisons.* fun box() { val coll = listOf("foo", "bar", "abc") assertEquals(emptyList<String>(), coll.takeLastWhile { false }) assertEquals(coll, coll.takeLastWhile { true }) assertEquals(listOf("abc"), coll.takeLastWhile { it.startsWith("a") }) assertEquals(listOf("bar", "abc"), coll.takeLastWhile { it[0] < 'c' }) }
backend.native/tests/external/stdlib/collections/CollectionTest/takeLastWhile.kt
337627658
package com.peterlaurence.trekme.service.event; data class MapDownloadEvent(val status: Status, var progress: Double = 100.0) enum class Status { FINISHED, PENDING, IMPORT_ERROR, STORAGE_ERROR }
app/src/main/java/com/peterlaurence/trekme/service/event/MapDownloadEvent.kt
186658713
package com.intellij.settingsSync import com.intellij.openapi.util.NlsSafe import com.intellij.util.concurrency.annotations.RequiresBackgroundThread /** * Synchronizes data with the remote server: pushes the data there, and receives updates. * Handles only the "transport" level, i.e. doesn't handle errors, doesn't handle the "push rejected" situation, etc. – all these situations * should be processes above. */ internal interface SettingsSyncRemoteCommunicator { @RequiresBackgroundThread fun isUpdateNeeded() : Boolean @RequiresBackgroundThread fun receiveUpdates(): UpdateResult @RequiresBackgroundThread fun push(snapshot: SettingsSnapshot): SettingsSyncPushResult } internal sealed class UpdateResult { class Success(val settingsSnapshot: SettingsSnapshot) : UpdateResult() object NoFileOnServer: UpdateResult() class Error(@NlsSafe val message: String): UpdateResult() }
plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncRemoteCommunicator.kt
627082608
class FooBar fun f(b<caret>pp: Int, c: Char) // ELEMENT_TEXT: bar: FooBar // CHAR: '\t'
plugins/kotlin/completion/tests/testData/handlers/basic/parameterNameAndType/TabReplace2.kt
1314976347
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.codeinsight.inspections import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemsHolder import org.editorconfig.language.codeinsight.quickfixes.EditorConfigRemoveRootDeclarationQuickFix import org.editorconfig.language.codeinsight.quickfixes.EditorConfigReplaceWithValidRootDeclarationQuickFix import org.editorconfig.language.messages.EditorConfigBundle import org.editorconfig.language.psi.EditorConfigRootDeclaration import org.editorconfig.language.psi.EditorConfigVisitor class EditorConfigRootDeclarationCorrectnessInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : EditorConfigVisitor() { override fun visitRootDeclaration(declaration: EditorConfigRootDeclaration) { if (declaration.isValidRootDeclaration) return val message = EditorConfigBundle.get("inspection.root-declaration.correctness.message") holder.registerProblem( declaration, message, EditorConfigReplaceWithValidRootDeclarationQuickFix(), EditorConfigRemoveRootDeclarationQuickFix() ) } } }
plugins/editorconfig/src/org/editorconfig/language/codeinsight/inspections/EditorConfigRootDeclarationCorrectnessInspection.kt
907150614
class A { var something: Int = 10 } fun A.foo(a: A) { print(a.<caret>something) a.<caret>something = 1 a.<caret>something += 1 a.<caret>something++ --a.<caret>something <caret>something++ (<caret>something)++ (<caret>something) = 1 (a.<caret>something) = 1 } // MULTIRESOLVE // REF1: (in A).something // REF2: (in A).something // REF3: (in A).something // REF4: (in A).something // REF5: (in A).something // REF6: (in A).something // REF7: (in A).something // REF8: (in A).something // REF9: (in A).something
plugins/kotlin/idea/tests/testData/resolve/references/KotlinPropertyAssignment.kt
1982842439
// 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.groovy.inspections import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.roots.ProjectRootManager import com.intellij.psi.PsiFile import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.idea.configuration.KOTLIN_GROUP_ID import org.jetbrains.kotlin.idea.extensions.gradle.KotlinGradleFacade import org.jetbrains.kotlin.idea.extensions.gradle.SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS import org.jetbrains.kotlin.idea.groovy.KotlinGroovyBundle import org.jetbrains.kotlin.idea.platform.tooling import org.jetbrains.kotlin.idea.roots.findAll import org.jetbrains.kotlin.idea.roots.findGradleProjectStructure import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.plugins.groovy.codeInspection.BaseInspection import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression class DifferentStdlibGradleVersionInspection : BaseInspection() { override fun buildVisitor(): BaseInspectionVisitor = MyVisitor(KOTLIN_GROUP_ID, JvmIdePlatformKind.tooling.mavenLibraryIds) override fun buildErrorString(vararg args: Any) = KotlinGroovyBundle.message("error.text.different.kotlin.library.version", args[0], args[1]) private abstract class VersionFinder(private val groupId: String, private val libraryIds: List<String>) : KotlinGradleInspectionVisitor() { protected abstract fun onFound(stdlibVersion: String, stdlibStatement: GrCallExpression) override fun visitClosure(closure: GrClosableBlock) { super.visitClosure(closure) val dependenciesCall = closure.getStrictParentOfType<GrMethodCall>() ?: return if (dependenciesCall.invokedExpression.text != "dependencies") return if (dependenciesCall.parent !is PsiFile) return val stdlibStatement = findLibraryStatement(closure, "org.jetbrains.kotlin", libraryIds) ?: return val stdlibVersion = getResolvedLibVersion(closure.containingFile, groupId, libraryIds) ?: return onFound(stdlibVersion, stdlibStatement) } } private inner class MyVisitor(groupId: String, libraryIds: List<String>) : VersionFinder(groupId, libraryIds) { override fun onFound(stdlibVersion: String, stdlibStatement: GrCallExpression) { val gradlePluginVersion = getResolvedKotlinGradleVersion(stdlibStatement.containingFile) if (stdlibVersion != gradlePluginVersion) { registerError(stdlibStatement, gradlePluginVersion, stdlibVersion) } } } companion object { private fun findLibraryStatement( closure: GrClosableBlock, @NonNls libraryGroup: String, libraryIds: List<String> ): GrCallExpression? { return GradleHeuristicHelper.findStatementWithPrefixes(closure, SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS).firstOrNull { statement -> libraryIds.any { val index = statement.text.indexOf(it) // This prevents detecting kotlin-stdlib inside kotlin-stdlib-common, -jdk8, etc. index != -1 && statement.text.getOrNull(index + it.length) != '-' } && statement.text.contains(libraryGroup) } } fun getResolvedLibVersion(file: PsiFile, groupId: String, libraryIds: List<String>): String? { val projectStructureNode = findGradleProjectStructure(file) ?: return null val module = ProjectRootManager.getInstance(file.project).fileIndex.getModuleForFile(file.virtualFile) ?: return null val gradleFacade = KotlinGradleFacade.instance ?: return null for (moduleData in projectStructureNode.findAll(ProjectKeys.MODULE).filter { it.data.internalName == module.name }) { gradleFacade.findLibraryVersionByModuleData(moduleData.node, groupId, libraryIds)?.let { return it } } return null } } }
plugins/kotlin/groovy/src/org/jetbrains/kotlin/idea/groovy/inspections/DifferentStdlibGradleVersionInspection.kt
1371587421
// IS_APPLICABLE: false fun new(x: Int, y: Int): Int { var c = 5 c -= <caret>10 return 1 }
plugins/kotlin/idea/tests/testData/intentions/swapBinaryExpression/minusAssign.kt
3466691449
package ftl.config.ios import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import ftl.args.yml.IYmlKeys import ftl.args.yml.ymlKeys import ftl.config.Config import picocli.CommandLine /** * iOS specific gcloud parameters * * https://cloud.google.com/sdk/gcloud/reference/firebase/test/android/run * https://cloud.google.com/sdk/gcloud/reference/alpha/firebase/test/ios/run */ @JsonIgnoreProperties(ignoreUnknown = true) data class IosGcloudConfig @JsonIgnore constructor( @JsonIgnore override val data: MutableMap<String, Any?> ) : Config { @set:CommandLine.Option( names = ["--test"], description = [ "The path to the test package (a zip file containing the iOS app " + "and XCTest files). The given path may be in the local filesystem or in Google Cloud Storage using a URL " + "beginning with gs://. Note: any .xctestrun file in this zip file will be ignored if --xctestrun-file " + "is specified." ] ) @set:JsonProperty("test") var test: String? by data @set:CommandLine.Option( names = ["--xctestrun-file"], description = [ "The path to an .xctestrun file that will override any " + ".xctestrun file contained in the --test package. Because the .xctestrun file contains environment variables " + "along with test methods to run and/or ignore, this can be useful for customizing or sharding test suites. The " + "given path may be in the local filesystem or in Google Cloud Storage using a URL beginning with gs://." ] ) @set:JsonProperty("xctestrun-file") var xctestrunFile: String? by data @set:CommandLine.Option( names = ["--xcode-version"], description = [ "The version of Xcode that should be used to run an XCTest. " + "Defaults to the latest Xcode version supported in Firebase Test Lab. This Xcode version must be supported by " + "all iOS versions selected in the test matrix." ] ) @set:JsonProperty("xcode-version") var xcodeVersion: String? by data @set:CommandLine.Option( names = ["--additional-ipas"], split = ",", description = [ "List of up to 100 additional IPAs to install, in addition to the one being directly tested. " + "The path may be in the local filesystem or in Google Cloud Storage using gs:// notation." ] ) @set:JsonProperty("additional-ipas") var additionalIpas: List<String>? by data @set:CommandLine.Option( names = ["--app"], description = [ "The path to the application archive (.ipa file) for game-loop testing. " + "The path may be in the local filesystem or in Google Cloud Storage using gs:// notation. " + "This flag is only valid when --type=game-loop is also set" ] ) @set:JsonProperty("app") var app: String? by data @set:CommandLine.Option( names = ["--test-special-entitlements"], description = [ "Enables testing special app entitlements. Re-signs an app having special entitlements with a new" + " application-identifier. This currently supports testing Push Notifications (aps-environment) entitlement " + "for up to one app in a project.\n" + "Note: Because this changes the app's identifier, make sure none of the resources in your zip file contain " + "direct references to the test app's bundle id." ] ) @set:JsonProperty("test-special-entitlements") var testSpecialEntitlements: Boolean? by data constructor() : this(mutableMapOf<String, Any?>().withDefault { null }) companion object : IYmlKeys { override val group = IYmlKeys.Group.GCLOUD override val keys by lazy { IosGcloudConfig::class.ymlKeys } fun default() = IosGcloudConfig().apply { test = null xctestrunFile = null xcodeVersion = null additionalIpas = emptyList() app = null testSpecialEntitlements = false } } }
test_runner/src/main/kotlin/ftl/config/ios/IosGcloudConfig.kt
1635629075
package com.kickstarter.libs.utils import android.content.Context import android.util.Pair import com.kickstarter.KSRobolectricTestCase import com.kickstarter.R import com.kickstarter.libs.KSString import com.kickstarter.libs.utils.RewardUtils.deadlineCountdownDetail import com.kickstarter.libs.utils.RewardUtils.deadlineCountdownUnit import com.kickstarter.libs.utils.RewardUtils.deadlineCountdownValue import com.kickstarter.libs.utils.RewardUtils.hasBackers import com.kickstarter.libs.utils.RewardUtils.hasStarted import com.kickstarter.libs.utils.RewardUtils.isAvailable import com.kickstarter.libs.utils.RewardUtils.isExpired import com.kickstarter.libs.utils.RewardUtils.isItemized import com.kickstarter.libs.utils.RewardUtils.isLimitReached import com.kickstarter.libs.utils.RewardUtils.isLimited import com.kickstarter.libs.utils.RewardUtils.isLocalPickup import com.kickstarter.libs.utils.RewardUtils.isNoReward import com.kickstarter.libs.utils.RewardUtils.isReward import com.kickstarter.libs.utils.RewardUtils.isShippable import com.kickstarter.libs.utils.RewardUtils.isTimeLimitedEnd import com.kickstarter.libs.utils.RewardUtils.isTimeLimitedStart import com.kickstarter.libs.utils.RewardUtils.isValidTimeRange import com.kickstarter.libs.utils.RewardUtils.shippingSummary import com.kickstarter.libs.utils.RewardUtils.timeInSecondsUntilDeadline import com.kickstarter.mock.factories.LocationFactory import com.kickstarter.mock.factories.ProjectFactory import com.kickstarter.mock.factories.RewardFactory import com.kickstarter.models.Project import com.kickstarter.models.Reward import org.joda.time.DateTime import org.joda.time.DateTimeUtils import org.joda.time.MutableDateTime import org.junit.Before import org.junit.Test import java.util.Date class RewardUtilsTest : KSRobolectricTestCase() { private lateinit var context: Context private lateinit var ksString: KSString private lateinit var date: Date private lateinit var currentDate: MutableDateTime private lateinit var reward: Reward private lateinit var noReward: Reward private lateinit var rewardEnded: Reward private lateinit var rewardLimitReached: Reward private lateinit var rewardMultipleShippingLocation: Reward private lateinit var rewardWorldWideShipping: Reward private lateinit var rewardSingleShippingLocation: Reward private lateinit var rewardWithAddons: Reward @Before fun setUpTests() { DateTimeUtils.setCurrentMillisFixed(DateTime().millis) context = context() ksString = ksString() date = DateTime.now().toDate() currentDate = MutableDateTime(date) noReward = RewardFactory.noReward() reward = RewardFactory.reward() rewardEnded = RewardFactory.ended() rewardLimitReached = RewardFactory.limitReached() rewardMultipleShippingLocation = RewardFactory.multipleLocationShipping() rewardWorldWideShipping = RewardFactory.rewardWithShipping() rewardSingleShippingLocation = RewardFactory.singleLocationShipping(LocationFactory.nigeria().displayableName()) rewardWithAddons = RewardFactory.rewardHasAddOns() } @Test fun testIsAvailable() { assertTrue(isAvailable(ProjectFactory.project(), reward)) assertFalse(isAvailable(ProjectFactory.project(), rewardEnded)) assertFalse(isAvailable(ProjectFactory.project(), rewardLimitReached)) assertFalse(isAvailable(ProjectFactory.successfulProject(), reward)) assertFalse(isAvailable(ProjectFactory.successfulProject(), rewardEnded)) assertFalse(isAvailable(ProjectFactory.successfulProject(), rewardLimitReached)) } @Test fun deadlineCountdownDetail_whenDaysLeft_returnsDayToGoString() { currentDate.addDays(31) reward = RewardFactory.reward().toBuilder() .endsAt(currentDate.toDateTime()) .build() assertEquals(deadlineCountdownDetail(reward, context, ksString), DAYS_TO_GO) } @Test fun testEquals() { currentDate.addDays(31) reward = RewardFactory.reward().toBuilder() .endsAt(currentDate.toDateTime()) .build() var reward2 = reward.toBuilder() .id(3L) .build() assertFalse(reward == reward2) reward2 = reward assertTrue(reward == reward2) val reward3 = reward2.toBuilder() .hasAddons(true) .quantity(4) .build() assertTrue(reward3.quantity() == 4) } @Test fun deadlineCountdownDetail_whenHoursLeft_returnsHoursToGoString() { currentDate.addHours(3) reward = RewardFactory.reward().toBuilder() .endsAt(currentDate.toDateTime()) .build() assertEquals(deadlineCountdownDetail(reward, context, ksString), HOURS_TO_GO) } @Test fun deadlineCountdownDetail_whenSecondsLeft_returnsSecondsToGoString() { currentDate.addSeconds(3) reward = RewardFactory.reward().toBuilder() .endsAt(currentDate.toDateTime()) .build() assertEquals(deadlineCountdownDetail(reward, context, ksString), SECS_TO_GO) } @Test fun deadlineCountdownUnit_whenDaysLeft_returnsDays() { currentDate.addDays(31) reward = RewardFactory.reward().toBuilder() .endsAt(currentDate.toDateTime()) .build() assertEquals(deadlineCountdownUnit(reward, context), DAYS) } @Test fun deadlineCountdownUnit_whenHoursLeft_returnsHours() { currentDate.addHours(3) reward = RewardFactory.reward().toBuilder() .endsAt(currentDate.toDateTime()) .build() assertEquals(deadlineCountdownUnit(reward, context), HOURS) } @Test fun deadlineCountdownUnit_whenMinutesLeft_returnsMinutes() { currentDate.addMinutes(3) reward = RewardFactory.reward().toBuilder() .endsAt(currentDate.toDateTime()) .build() assertEquals(deadlineCountdownUnit(reward, context), MINS) } @Test fun deadlineCountdownUnit_whenSecondsLeft_returnsSecs() { currentDate.addSeconds(30) reward = RewardFactory.reward().toBuilder() .endsAt(currentDate.toDateTime()) .build() assertEquals(deadlineCountdownUnit(reward, context), SECS) } @Test fun deadlineCountdownValue_whenMinutesLeft_returnsNumberOfMinutes() { currentDate.addSeconds(300) reward = RewardFactory.reward().toBuilder() .endsAt(currentDate.toDateTime()) .build() assertEquals(deadlineCountdownValue(reward), 5) } @Test fun deadlineCountdownValue_whenHoursLeft_returnsNumberOfHours() { currentDate.addSeconds(3600) reward = RewardFactory.reward().toBuilder() .endsAt(currentDate.toDateTime()) .build() assertEquals(deadlineCountdownValue(reward), 60) } @Test fun deadlineCountdownValue_whenDaysLeft_returnsNumberOfDays() { currentDate.addSeconds(86400) reward = RewardFactory.reward().toBuilder() .endsAt(currentDate.toDateTime()) .build() assertEquals(deadlineCountdownValue(reward), 24) } @Test fun deadlineCountdownValue_whenSecondsLeft_returnsNumberOfSeconds() { currentDate.addSeconds(30) reward = RewardFactory.reward().toBuilder() .endsAt(currentDate.toDateTime()) .build() assertEquals(deadlineCountdownValue(reward), 30) } @Test fun testHasBackers() { assertTrue(hasBackers(RewardFactory.backers())) assertFalse(hasBackers(RewardFactory.noBackers())) } @Test fun isLimited_whenRemainingGreaterThanZeroAndLimitNotNull_returnsTrue() { reward = RewardFactory.reward().toBuilder() .remaining(5) .limit(10) .build() assertTrue(isLimited(reward)) } @Test fun isLimited_whenRemainingZeroAndLimitNotNull_returnFalse() { reward = RewardFactory.reward().toBuilder() .remaining(0) .limit(10) .build() assertFalse(isLimited(reward)) } @Test fun isLimited_whenLimitAndRemainingNull_returnFalse() { reward = RewardFactory.reward().toBuilder() .remaining(null) .limit(null) .build() assertFalse(isLimited(reward)) } @Test fun testIsItemized() { assertFalse(isItemized(reward)) assertTrue(isItemized(RewardFactory.itemized())) assertTrue(isItemized(RewardFactory.itemizedAddOn())) } @Test fun isLimitReached_whenLimitSetAndRemainingIsZero_returnTrue() { reward = RewardFactory.reward().toBuilder() .limit(100) .remaining(0) .build() assertTrue(isLimitReached(reward)) } @Test fun isLimitReached_whenLimitSetButRemainingIsNull_returnFalse() { reward = RewardFactory.reward().toBuilder() .limit(100) .build() assertFalse(isLimitReached(reward)) } @Test fun isLimitReached_whenRemainingIsGreaterThanZero_returnFalse() { reward = RewardFactory.reward().toBuilder() .limit(100) .remaining(50) .build() assertFalse(isLimitReached(reward)) } @Test fun testIsReward() { assertTrue(isReward(reward)) assertFalse(isReward(noReward)) } @Test fun testIsNoReward() { assertTrue(isNoReward(noReward)) assertFalse(isNoReward(reward)) } @Test fun testIsShippable() { val rewardWithNullShipping = RewardFactory.reward() .toBuilder() .shippingType(null) .build() assertFalse(isShippable(rewardWithNullShipping)) assertFalse(isShippable(reward)) assertTrue(isShippable(rewardMultipleShippingLocation)) assertTrue(isShippable(rewardSingleShippingLocation)) assertTrue(isShippable(rewardWorldWideShipping)) } @Test fun isTimeLimited() { assertFalse(isTimeLimitedEnd(reward)) assertTrue(isTimeLimitedEnd(RewardFactory.endingSoon())) } @Test fun isExpired_whenEndsAtPastDate_returnsTrue() { assertFalse(isExpired(reward)) reward = RewardFactory.reward() .toBuilder() .endsAt(DateTime.now().minusDays(2)) .build() assertTrue(isExpired(reward)) } @Test fun isExpired_whenEndsAtFutureDate_returnsFalse() { reward = RewardFactory.reward() .toBuilder() .endsAt(DateTime.now().plusDays(2)) .build() assertFalse(isExpired(reward)) } @Test fun testShippingSummary() { val rewardWithNullShipping = RewardFactory.reward() .toBuilder() .shippingType(null) .build() val rewardWithNullLocation = RewardFactory.reward() .toBuilder() .shippingSingleLocation(null) .shippingType(Reward.SHIPPING_TYPE_SINGLE_LOCATION) .build() assertNull(shippingSummary(rewardWithNullShipping)) assertNull(shippingSummary(reward)) assertEquals(Pair.create(R.string.Limited_shipping, ""), shippingSummary(rewardWithNullLocation)) assertEquals(Pair.create<Int, Any?>(R.string.Limited_shipping, null), shippingSummary(rewardMultipleShippingLocation)) assertEquals(Pair.create(R.string.location_name_only, COUNTRY_NIGERIA), shippingSummary(rewardSingleShippingLocation)) assertEquals(Pair.create<Int, Any?>(R.string.Ships_worldwide, null), shippingSummary(rewardWorldWideShipping)) } @Test fun testRewardTimeLimitedStart_hasStarted() { val isLiveProject: Project = ProjectFactory.project() val rewardLimitedByStart = rewardWithAddons.toBuilder().startsAt(DateTime.now()).build() assertEquals(true, hasStarted(rewardLimitedByStart)) assertEquals(true, isAvailable(isLiveProject, rewardLimitedByStart)) } @Test fun testRewardNotTimeLimitedStart_hasStarted() { // - A reward not limited os starting time should be considered as a reward that has started assertEquals(false, isTimeLimitedStart(rewardWithAddons)) assertEquals(true, hasStarted(rewardWithAddons)) } @Test fun testRewardTimeLimitedStart_hasNotStarted() { val rewardLimitedByStart = rewardWithAddons .toBuilder() .startsAt(DateTime.now().plusDays(1)) .build() assertEquals(true, isTimeLimitedStart(rewardLimitedByStart)) assertEquals(false, hasStarted(rewardLimitedByStart)) } @Test fun testRewardTimeLimitedEnd_hasEnded() { val rewardExpired = rewardWithAddons .toBuilder() .endsAt(DateTime.now().minusDays(1)) .build() assertEquals(true, isExpired(rewardExpired)) assertEquals(false, isValidTimeRange(rewardExpired)) } @Test fun testValidTimeRage_limitedStart_hasNotStarted() { val rewardLimitedByStart = rewardWithAddons .toBuilder() .startsAt(DateTime.now().plusDays(1)) .build() assertEquals(false, isValidTimeRange(rewardLimitedByStart)) } @Test fun testValidTimeRage_limitedStart_hasStarted() { val rewardLimitedByStart = rewardWithAddons.toBuilder().startsAt(DateTime.now()).build() assertEquals(true, isValidTimeRange(rewardLimitedByStart)) } @Test fun testValidTimeRage_limitedEnd_hasNotEnded() { val rewardLimitedByEnd = rewardWithAddons .toBuilder() .endsAt(DateTime.now().plusDays(1)) .build() assertEquals(false, isExpired(rewardLimitedByEnd)) assertEquals(true, isValidTimeRange(rewardLimitedByEnd)) } @Test fun testValidTimeRange_limitedStartEnd_isValid() { val rewardLimitedBoth = rewardWithAddons .toBuilder() .startsAt(DateTime.now()) .endsAt(DateTime.now().plusDays(1)) .build() assertEquals(false, isExpired(rewardLimitedBoth)) assertEquals(true, hasStarted(rewardLimitedBoth)) assertEquals(true, isValidTimeRange(rewardLimitedBoth)) } @Test fun testValidTimeRange_limitedStartEnd_isInvalid() { val rewardLimitedBoth = rewardWithAddons .toBuilder() .startsAt(DateTime.now().plusDays(1)) .endsAt(DateTime.now().plusDays(2)) .build() assertEquals(false, isExpired(rewardLimitedBoth)) assertEquals(false, hasStarted(rewardLimitedBoth)) assertEquals(false, isValidTimeRange(rewardLimitedBoth)) } @Test fun isValidTimeRage_whenNotLimited_isValid() { assertEquals(false, isExpired(rewardWithAddons)) assertEquals(true, hasStarted(rewardWithAddons)) assertEquals(true, isValidTimeRange(rewardWithAddons)) } @Test fun isValidTimeRage_whenStartNotLimited_returnsTrue() { assertEquals(true, isValidTimeRange(rewardWithAddons)) } @Test fun testTimeInSecondsUntilDeadline() { currentDate.addSeconds(120) reward = RewardFactory.reward().toBuilder().endsAt(currentDate.toDateTime()).build() val timeInSecondsUntilDeadline = timeInSecondsUntilDeadline(reward) assertEquals(timeInSecondsUntilDeadline, 120) } @Test fun testIsShippableRewardWithLocalPickupLocation() { val reward = RewardFactory.localReceiptLocation() assertFalse(isShippable(reward)) assertTrue(isLocalPickup(reward)) } companion object { private const val DAYS_TO_GO = "days to go" private const val HOURS_TO_GO = "hours to go" private const val SECS_TO_GO = "secs to go" private const val DAYS = "days" private const val HOURS = "hours" private const val MINS = "mins" private const val SECS = "secs" private const val COUNTRY_NIGERIA = "Nigeria" } }
app/src/test/java/com/kickstarter/libs/utils/RewardUtilsTest.kt
2702309863
package com.kickstarter.ui.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.LayoutRes import com.kickstarter.R import com.kickstarter.databinding.EmptyViewBinding import com.kickstarter.databinding.ItemAddOnPledgeBinding import com.kickstarter.models.Reward import com.kickstarter.models.ShippingRule import com.kickstarter.ui.data.ProjectData import com.kickstarter.ui.viewholders.BackingAddOnViewHolder import com.kickstarter.ui.viewholders.EmptyViewHolder import com.kickstarter.ui.viewholders.KSViewHolder class BackingAddOnsAdapter(private val viewListener: BackingAddOnViewHolder.ViewListener) : KSAdapter() { init { insertSection(SECTION_NO_ADD_ONS_AVAILABLE, emptyList<Boolean>()) insertSection(SECTION_BACKING_ADD_ONS_CARD, emptyList<Reward>()) } override fun layout(sectionRow: SectionRow): Int = when (sectionRow.section()) { SECTION_BACKING_ADD_ONS_CARD -> R.layout.item_add_on_pledge SECTION_NO_ADD_ONS_AVAILABLE -> R.layout.item_empty_add_on else -> 0 } override fun viewHolder(@LayoutRes layout: Int, viewGroup: ViewGroup): KSViewHolder { return when (layout) { R.layout.item_empty_add_on -> EmptyViewHolder(EmptyViewBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)) R.layout.item_add_on_pledge -> BackingAddOnViewHolder(ItemAddOnPledgeBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false), viewListener) else -> EmptyViewHolder(EmptyViewBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)) } } fun populateDataForAddOns(rewards: List<Triple<ProjectData, Reward, ShippingRule>>) { setSection(SECTION_BACKING_ADD_ONS_CARD, rewards) notifyDataSetChanged() } fun showEmptyState(isEmptyState: Boolean) { if (isEmptyState) { setSection(SECTION_NO_ADD_ONS_AVAILABLE, listOf(true)) } else { setSection(SECTION_NO_ADD_ONS_AVAILABLE, emptyList<Boolean>()) } notifyDataSetChanged() } companion object { private const val SECTION_NO_ADD_ONS_AVAILABLE = 0 private const val SECTION_BACKING_ADD_ONS_CARD = 1 } }
app/src/main/java/com/kickstarter/ui/adapters/BackingAddOnsAdapter.kt
355745901
/* * VoIP.ms SMS * Copyright (C) 2018-2021 Michael Kourlas * * 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 net.kourlas.voipms_sms.sms.receivers import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import androidx.core.app.RemoteInput import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import net.kourlas.voipms_sms.R import net.kourlas.voipms_sms.database.Database import net.kourlas.voipms_sms.sms.ConversationId import net.kourlas.voipms_sms.sms.workers.SendMessageWorker import net.kourlas.voipms_sms.utils.getMessageTexts import net.kourlas.voipms_sms.utils.logException /** * Broadcast receiver used to forward send message requests from a notification * PendingIntent to a SendMessageWorker. */ class SendMessageReceiver : BroadcastReceiver() { @OptIn(DelicateCoroutinesApi::class) override fun onReceive(context: Context?, intent: Intent?) { try { // Collect the required state. if (context == null || intent == null) { throw Exception("No context or intent provided") } if (intent.action != context.getString( R.string.send_message_receiver_action ) ) { throw Exception("Unrecognized action " + intent.action) } val did = intent.getStringExtra( context.getString( R.string.send_message_receiver_did ) ) ?: throw Exception( "No DID provided" ) val contact = intent.getStringExtra( context.getString( R.string.send_message_receiver_contact ) ) ?: throw Exception( "No contact provided" ) val remoteInput = RemoteInput.getResultsFromIntent(intent) val messageText = remoteInput?.getCharSequence( context.getString( R.string.notifications_reply_key ) )?.toString() ?: throw Exception("No message text provided") val pendingResult = goAsync() ?: throw Exception("No PendingResult returned") GlobalScope.launch(Dispatchers.Default) { // Insert the messages into the database, then tell the // SendMessageWorker to send them. try { val databaseIds = Database.getInstance(context) .insertConversationMessagesDeliveryInProgress( ConversationId(did, contact), getMessageTexts(context, messageText) ) for (id in databaseIds) { SendMessageWorker.sendMessage( context, id, inlineReplyConversationId = ConversationId( did, contact ) ) } } catch (e: Exception) { logException(e) } finally { pendingResult.finish() } } } catch (e: Exception) { logException(e) } } companion object { /** * Gets an intent which can be used to send a message to the * specified contact and from the specified DID. */ fun getIntent(context: Context, did: String, contact: String): Intent { val intent = Intent() intent.action = context.getString(R.string.send_message_receiver_action) intent.putExtra( context.getString( R.string.send_message_receiver_did ), did ) intent.putExtra( context.getString( R.string.send_message_receiver_contact ), contact ) return intent } } }
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/sms/receivers/SendMessageReceiver.kt
2688906652
package dependency class Dep
plugins/kotlin/idea/tests/testData/editor/optimizeImports/common/basic/UsedConstructor.dependency.kt
506138351
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.changeSignature.ui import com.intellij.openapi.ui.ComboBoxTableRenderer import com.intellij.psi.PsiElement import com.intellij.refactoring.changeSignature.ParameterTableModelItemBase import com.intellij.util.ui.ColumnInfo import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinParameterInfo import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinValVar import javax.swing.DefaultCellEditor import javax.swing.JComboBox import javax.swing.JTable import javax.swing.table.TableCellEditor import javax.swing.table.TableCellRenderer class KotlinPrimaryConstructorParameterTableModel( methodDescriptor: KotlinMethodDescriptor, defaultValueContext: PsiElement ) : KotlinCallableParameterTableModel( methodDescriptor, defaultValueContext, ValVarColumn(), NameColumn<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>>(defaultValueContext.project), TypeColumn<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>>(defaultValueContext.project, KotlinFileType.INSTANCE), DefaultValueColumn<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>>( defaultValueContext.project, KotlinFileType.INSTANCE, ), DefaultParameterColumn(), ) { private class ValVarColumn : ColumnInfoBase<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>, KotlinValVar>( KotlinBundle.message("column.name.val.var") ) { override fun isCellEditable(item: ParameterTableModelItemBase<KotlinParameterInfo>): Boolean { return !item.isEllipsisType && item.parameter.isNewParameter } override fun valueOf(item: ParameterTableModelItemBase<KotlinParameterInfo>): KotlinValVar = item.parameter.valOrVar override fun setValue(item: ParameterTableModelItemBase<KotlinParameterInfo>, value: KotlinValVar) { item.parameter.valOrVar = value } override fun doCreateRenderer(item: ParameterTableModelItemBase<KotlinParameterInfo>): TableCellRenderer { return ComboBoxTableRenderer(KotlinValVar.values()) } override fun doCreateEditor(item: ParameterTableModelItemBase<KotlinParameterInfo>): TableCellEditor { return DefaultCellEditor(JComboBox<ParameterTableModelItemBase<KotlinParameterInfo>>()) } override fun getWidth(table: JTable): Int = table.getFontMetrics(table.font).stringWidth(name) + 8 } companion object { fun isValVarColumn(column: ColumnInfo<*, *>?): Boolean = column is ValVarColumn } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinPrimaryConstructorParameterTableModel.kt
295788858
// 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.stats.completion import com.intellij.codeInsight.lookup.LookupManager import com.intellij.ide.ApplicationInitializedListener import com.intellij.openapi.actionSystem.ex.AnActionListener import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener class CompletionTrackerInitializer : ApplicationInitializedListener { companion object { var isEnabledInTests: Boolean = false } override fun componentsInitialized() { val busConnection = ApplicationManager.getApplication().messageBus.connect() if (CompletionLoggerInitializer.shouldInitialize()) { val actionListener = LookupActionsListener() busConnection.subscribe(AnActionListener.TOPIC, actionListener) busConnection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectOpened(project: Project) { LookupManager.getInstance(project).addPropertyChangeListener(CompletionLoggerInitializer(actionListener), project) } }) } busConnection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectOpened(project: Project) { val lookupManager = LookupManager.getInstance(project) lookupManager.addPropertyChangeListener(CompletionQualityTracker(), project) lookupManager.addPropertyChangeListener(CompletionFactorsInitializer(), project) } }) } }
plugins/stats-collector/src/com/intellij/stats/completion/CompletionTrackerInitializer.kt
2816252706
package org.wycliffeassociates.translationrecorder.login.utils import android.media.MediaCodec import android.media.MediaCodecInfo import android.media.MediaFormat import android.media.MediaMuxer import net.gotev.uploadservice.UploadService.BUFFER_SIZE import org.apache.commons.codec.binary.Hex import org.apache.commons.codec.digest.DigestUtils import java.io.File import java.io.FileInputStream /** * Created by sarabiaj on 5/2/2018. */ const val COMPRESSED_AUDIO_FILE_MIME_TYPE = "audio/mp4a-latm" const val COMPRESSED_AUDIO_FILE_BIT_RATE = 64000 // 64kbps const val SAMPLING_RATE = 44100 const val CODEC_TIMEOUT_IN_MS = 5000 const val BUFFER_SIZE = 44100 fun convertWavToMp4(AUDIO_RECORDING_FILE_NAME: File, COMPRESSED_AUDIO_FILE_NAME: File): String { val inputFile = AUDIO_RECORDING_FILE_NAME val fis = FileInputStream(inputFile) val outputFile = COMPRESSED_AUDIO_FILE_NAME if (outputFile.exists()) outputFile.delete() val mux = MediaMuxer(outputFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4) var outputFormat = MediaFormat.createAudioFormat(COMPRESSED_AUDIO_FILE_MIME_TYPE, SAMPLING_RATE, 1) outputFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC) outputFormat.setInteger(MediaFormat.KEY_BIT_RATE, COMPRESSED_AUDIO_FILE_BIT_RATE) val codec = MediaCodec.createEncoderByType(COMPRESSED_AUDIO_FILE_MIME_TYPE) codec.configure(outputFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) codec.start() val codecInputBuffers = codec.inputBuffers // Note: Array of buffers val codecOutputBuffers = codec.outputBuffers val outBuffInfo = MediaCodec.BufferInfo() val tempBuffer = ByteArray(BUFFER_SIZE) var hasMoreData = true var presentationTimeUs = 0.0 var audioTrackIdx = 0 var totalBytesRead = 0 do { var inputBufIndex = 0 while (inputBufIndex != -1 && hasMoreData) { inputBufIndex = codec.dequeueInputBuffer(CODEC_TIMEOUT_IN_MS.toLong()) if (inputBufIndex >= 0) { val dstBuf = codecInputBuffers[inputBufIndex] dstBuf.clear() val bytesRead = fis.read(tempBuffer, 0, dstBuf.limit()) if (bytesRead == -1) { // -1 implies EOS hasMoreData = false codec.queueInputBuffer(inputBufIndex, 0, 0, presentationTimeUs.toLong(), MediaCodec.BUFFER_FLAG_END_OF_STREAM) } else { totalBytesRead += bytesRead dstBuf.put(tempBuffer, 0, bytesRead) codec.queueInputBuffer(inputBufIndex, 0, bytesRead, presentationTimeUs.toLong(), 0) presentationTimeUs = (1000000L * (totalBytesRead / 2) / SAMPLING_RATE).toDouble() } } } // Drain audio var outputBufIndex = 0 while (outputBufIndex != MediaCodec.INFO_TRY_AGAIN_LATER) { outputBufIndex = codec.dequeueOutputBuffer(outBuffInfo, CODEC_TIMEOUT_IN_MS.toLong()) if (outputBufIndex >= 0) { val encodedData = codecOutputBuffers[outputBufIndex] encodedData.position(outBuffInfo.offset) encodedData.limit(outBuffInfo.offset + outBuffInfo.size) if (outBuffInfo.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0 && outBuffInfo.size != 0) { codec.releaseOutputBuffer(outputBufIndex, false) } else { mux.writeSampleData(audioTrackIdx, codecOutputBuffers[outputBufIndex], outBuffInfo) codec.releaseOutputBuffer(outputBufIndex, false) } } else if (outputBufIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { outputFormat = codec.outputFormat audioTrackIdx = mux.addTrack(outputFormat) mux.start() } else if (outputBufIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { } else if (outputBufIndex == MediaCodec.INFO_TRY_AGAIN_LATER) { } else { } } } while (outBuffInfo.flags != MediaCodec.BUFFER_FLAG_END_OF_STREAM) fis.close() mux.stop() mux.release() return getHash(COMPRESSED_AUDIO_FILE_NAME) } private fun getHash(file: File): String { return String(Hex.encodeHex(DigestUtils.md5(FileInputStream(file)))) }
translationRecorder/app/src/main/java/org/wycliffeassociates/translationrecorder/login/utils/ConvertAudio.kt
142943129
// SET_TRUE: ALIGN_MULTILINE_EXTENDS_LIST interface A1 class A { class Simpleclass() : A1, <caret> } // WITHOUT_CUSTOM_LINE_INDENT_PROVIDER
plugins/kotlin/idea/tests/testData/indentationOnNewline/InDelegationListAfterComma.after.kt
427883510
// WITH_RUNTIME fun main(args: Array<String>) { var a: String? = "A" doSomething(a<caret>!!) } fun doSomething(a: Any){}
plugins/kotlin/idea/tests/testData/intentions/branched/doubleBangToIfThen/localVar.kt
1491730522
var x : Int <caret>by Baz() interface Foo { fun getValue(p1: Any?, p2: Any?): Int = 1 } interface Bar { fun getValue(p1: Any?, p2: Any?): Int } interface Zoo { fun setValue(p1: Any?, p2: Any?, p3: Any?) } class Baz: Foo, Bar, Zoo // MULTIRESOLVE // REF: (in Bar).getValue(Any?, Any?) // REF: (in Foo).getValue(Any?, Any?) // REF: (in Zoo).setValue(Any?, Any?, Any?)
plugins/kotlin/idea/tests/testData/resolve/references/delegatedPropertyAccessors/inSource/getMultipleDeclarations.kt
2343408793
package com.jetbrains.packagesearch.intellij.plugin.extensions.maven import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyOperationMetadata import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleOperationProvider import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleType import com.intellij.buildsystem.model.OperationFailure import com.intellij.buildsystem.model.OperationItem import com.intellij.buildsystem.model.OperationType import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository import com.intellij.externalSystem.DependencyModifierService import com.intellij.openapi.module.ModuleUtilCore import com.jetbrains.packagesearch.intellij.plugin.extensibility.AbstractProjectModuleOperationProvider import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.utils.MavenUtil class MavenProjectModuleOperationProvider : AbstractProjectModuleOperationProvider() { override fun hasSupportFor(projectModuleType: ProjectModuleType): Boolean = projectModuleType is MavenProjectModuleType override fun hasSupportFor(project: Project, psiFile: PsiFile?) = MavenUtil.isPomFile(project, psiFile?.virtualFile) override fun refreshProject(project: Project, virtualFile: VirtualFile) { if (!PackageSearchGeneralConfiguration.getInstance(project).refreshProject) return val projectsManager = MavenProjectsManager.getInstance(project) if (projectsManager.importingSettings.isImportAutomatically) return ProjectRefreshingListener.doOnNextChange(projectsManager) { projectsManager.forceUpdateProjects(projectsManager.projects) } } } private object ProjectRefreshingListener : MavenProjectsManager.Listener { private val runOnNextChange = AtomicReference<(() -> Unit)?>() private val needsRegistering = AtomicBoolean(true) fun doOnNextChange(mavenProjectsManager: MavenProjectsManager, action: () -> Unit) { registerIfNeeded(mavenProjectsManager) runOnNextChange.set(action) } private fun registerIfNeeded(mavenProjectsManager: MavenProjectsManager) { if (needsRegistering.getAndSet(false)) { mavenProjectsManager.addManagerListener(this) } } override fun projectsScheduled() { runOnNextChange.getAndSet(null)?.invoke() } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensions/maven/MavenProjectModuleOperationProvider.kt
3154265503
package org.thoughtcrime.securesms.components.settings import android.content.Context import android.text.SpannableStringBuilder import androidx.annotation.ColorInt import androidx.annotation.StringRes import androidx.annotation.StyleRes import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.util.SpanUtil sealed class DSLSettingsText { protected abstract val modifiers: List<Modifier> private data class FromResource( @StringRes private val stringId: Int, override val modifiers: List<Modifier> ) : DSLSettingsText() { override fun getCharSequence(context: Context): CharSequence { return context.getString(stringId) } } private data class FromCharSequence( private val charSequence: CharSequence, override val modifiers: List<Modifier> ) : DSLSettingsText() { override fun getCharSequence(context: Context): CharSequence = charSequence } protected abstract fun getCharSequence(context: Context): CharSequence fun resolve(context: Context): CharSequence { val text: CharSequence = getCharSequence(context) return modifiers.fold(text) { t, m -> m.modify(context, t) } } companion object { fun from(@StringRes stringId: Int, @ColorInt textColor: Int): DSLSettingsText = FromResource(stringId, listOf(ColorModifier(textColor))) fun from(@StringRes stringId: Int, vararg modifiers: Modifier): DSLSettingsText = FromResource(stringId, modifiers.toList()) fun from(charSequence: CharSequence, vararg modifiers: Modifier): DSLSettingsText = FromCharSequence(charSequence, modifiers.toList()) } interface Modifier { fun modify(context: Context, charSequence: CharSequence): CharSequence } class ColorModifier(@ColorInt private val textColor: Int) : Modifier { override fun modify(context: Context, charSequence: CharSequence): CharSequence { return SpanUtil.color(textColor, charSequence) } override fun equals(other: Any?): Boolean = textColor == (other as? ColorModifier)?.textColor override fun hashCode(): Int = textColor } object CenterModifier : Modifier { override fun modify(context: Context, charSequence: CharSequence): CharSequence { return SpanUtil.center(charSequence) } } object TitleLargeModifier : TextAppearanceModifier(R.style.Signal_Text_TitleLarge) object TitleMediumModifier : TextAppearanceModifier(R.style.Signal_Text_TitleMedium) object BodyLargeModifier : TextAppearanceModifier(R.style.Signal_Text_BodyLarge) open class TextAppearanceModifier(@StyleRes private val textAppearance: Int) : Modifier { override fun modify(context: Context, charSequence: CharSequence): CharSequence { return SpanUtil.textAppearance(context, textAppearance, charSequence) } override fun equals(other: Any?): Boolean = textAppearance == (other as? TextAppearanceModifier)?.textAppearance override fun hashCode(): Int = textAppearance } object BoldModifier : Modifier { override fun modify(context: Context, charSequence: CharSequence): CharSequence { return SpanUtil.bold(charSequence) } } class LearnMoreModifier( @ColorInt private val learnMoreColor: Int, val onClick: () -> Unit ) : Modifier { override fun modify(context: Context, charSequence: CharSequence): CharSequence { return SpannableStringBuilder(charSequence).append(" ").append( SpanUtil.learnMore(context, learnMoreColor) { onClick() } ) } } }
app/src/main/java/org/thoughtcrime/securesms/components/settings/DSLSettingsText.kt
3424337838
/* * 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.window.layout.adapter.sidecar import android.app.Activity import android.graphics.Rect import androidx.annotation.GuardedBy import androidx.window.core.Bounds import androidx.window.layout.FoldingFeature import androidx.window.layout.adapter.sidecar.ExtensionInterfaceCompat.ExtensionCallbackInterface import androidx.window.layout.FoldingFeature.State import androidx.window.layout.FoldingFeature.State.Companion.FLAT import androidx.window.layout.FoldingFeature.State.Companion.HALF_OPENED import androidx.window.layout.HardwareFoldingFeature import androidx.window.layout.HardwareFoldingFeature.Type.Companion.HINGE import androidx.window.layout.WindowLayoutInfo import java.util.concurrent.locks.Lock import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock /** * An implementation of [ExtensionInterfaceCompat] that switches the state when a consumer * is unregistered. Useful for testing consumers when they go through a cycle of register then * unregister then register again. */ internal class SwitchOnUnregisterExtensionInterfaceCompat : ExtensionInterfaceCompat { private val lock: Lock = ReentrantLock() private val foldBounds = Rect(0, 100, 200, 100) @GuardedBy("mLock") private var callback: ExtensionCallbackInterface = EmptyExtensionCallbackInterface() @GuardedBy("mLock") private var state = FLAT override fun validateExtensionInterface(): Boolean { return true } override fun setExtensionCallback(extensionCallback: ExtensionCallbackInterface) { lock.withLock { callback = extensionCallback } } override fun onWindowLayoutChangeListenerAdded(activity: Activity) { lock.withLock { callback.onWindowLayoutChanged(activity, currentWindowLayoutInfo()) } } override fun onWindowLayoutChangeListenerRemoved(activity: Activity) { lock.withLock { state = toggleState(state) } } fun currentWindowLayoutInfo(): WindowLayoutInfo { return WindowLayoutInfo(listOf(currentFoldingFeature())) } fun currentFoldingFeature(): FoldingFeature { return HardwareFoldingFeature(Bounds(foldBounds), HINGE, state) } internal companion object { fun toggleState(currentState: State): State { return if (currentState == FLAT) { HALF_OPENED } else { FLAT } } } }
window/window/src/testUtil/java/androidx/window/layout/adapter/sidecar/SwitchOnUnregisterExtensionInterfaceCompat.kt
3998409734
/* * Copyright 2017 Lloyd Ramey <[email protected]> * * 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.lloydramey.cfn.scripting import com.lloydramey.cfn.model.Mapping import com.lloydramey.cfn.model.Output import com.lloydramey.cfn.model.Parameter import com.lloydramey.cfn.model.ParameterType import com.lloydramey.cfn.model.Template import com.lloydramey.cfn.model.functions.Condition import com.lloydramey.cfn.model.functions.ConditionFunction import com.lloydramey.cfn.model.resources.Resource import com.lloydramey.cfn.model.resources.ResourceProperties import com.lloydramey.cfn.model.resources.attributes.ConditionalOn import com.lloydramey.cfn.model.resources.attributes.ResourceDefinitionAttribute import com.lloydramey.cfn.scripting.helpers.ConditionDelegate import com.lloydramey.cfn.scripting.helpers.MappingDefinition import com.lloydramey.cfn.scripting.helpers.MappingDelegate import com.lloydramey.cfn.scripting.helpers.MetadataDelegate import com.lloydramey.cfn.scripting.helpers.OutputDefinition import com.lloydramey.cfn.scripting.helpers.OutputDelegate import com.lloydramey.cfn.scripting.helpers.ParameterDefinition import com.lloydramey.cfn.scripting.helpers.ParameterDelegate import com.lloydramey.cfn.scripting.helpers.ResourceDelegate import com.lloydramey.cfn.scripting.helpers.TemplateMetadata import org.jetbrains.kotlin.script.ScriptTemplateDefinition import kotlin.reflect.KClass import kotlin.reflect.full.isSubtypeOf import kotlin.reflect.full.memberProperties import kotlin.reflect.full.primaryConstructor import kotlin.reflect.full.starProjectedType typealias MappingInitializer = MappingDefinition.() -> Unit typealias ParameterInitializer = ParameterDefinition.() -> Unit typealias LazyCondition = () -> ConditionFunction typealias PropertyInitializer<T> = T.() -> Unit typealias OutputInitializer = OutputDefinition.() -> Unit @Suppress("unused") @ScriptTemplateDefinition( resolver = CfnTemplateDependencyResolver::class, scriptFilePattern = ".*\\.template\\.kts" ) abstract class CfnTemplateScript { protected var description: String = "" protected fun metadata(value: Any) = MetadataDelegate(value) protected fun mapping(init: MappingInitializer) = MappingDelegate(init) protected fun parameter(type: ParameterType, init: ParameterInitializer) = ParameterDelegate(type, init) protected fun condition(func: LazyCondition) = ConditionDelegate(func) protected inline fun <reified T : ResourceProperties> resource( vararg attributes: ResourceDefinitionAttribute, init: PropertyInitializer<T> ): ResourceDelegate<T> { val clazz = T::class requireDefaultNoArgConstructor(clazz) val properties = clazz.primaryConstructor!!.call() properties.init() properties.validate() return ResourceDelegate(properties, attributes.asList()) } protected fun output(condition: ConditionalOn? = null, init: OutputInitializer) = OutputDelegate(condition, init) internal fun toTemplate() = Template( description = description, parameters = parameters, metadata = metadata, mappings = mappings, conditions = conditions, resources = resources, outputs = outputs ) private val outputs: Map<String, Output> get() = getPropertiesOfAType<Output>().associateBy { it.id } private val resources: Map<String, Resource<ResourceProperties>> get() = getPropertiesOfAType<Resource<ResourceProperties>>().associateBy { it.id } private val conditions: Map<String, ConditionFunction> get() = getPropertiesOfAType<Condition>().associate { it.id to it.condition } private val parameters: Map<String, Parameter> get() = getPropertiesOfAType<Parameter>().associateBy { it.id } private val metadata: Map<String, Any> get() = getPropertiesOfAType<TemplateMetadata>().associate { it.name to it.value } private val mappings: Map<String, Mapping> get() = getPropertiesOfAType<Mapping>().associateBy { it.id } private inline fun <reified T : Any> getPropertiesOfAType(): List<T> { return this::class.memberProperties .filter { it.returnType.isSubtypeOf(T::class.starProjectedType) } .flatMap { listOf(it.call(this) as T?).filterNotNull() } } } fun requireDefaultNoArgConstructor(clazz: KClass<out ResourceProperties>) { if (clazz.primaryConstructor == null) { throw IllegalStateException("${clazz.qualifiedName} must declare a primary constructor") } if (!clazz.primaryConstructor!!.parameters.all { it.isOptional }) { throw IllegalStateException("${clazz.qualifiedName} must not have any required parameters in it's primary constructor") } }
plugin/src/main/kotlin/com/lloydramey/cfn/scripting/CfnTemplateScript.kt
2735067479
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.util.PsiUtilCore import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ConvertToStringTemplateInspection : IntentionBasedInspection<KtBinaryExpression>( ConvertToStringTemplateIntention::class, ConvertToStringTemplateIntention::shouldSuggestToConvert, problemText = KotlinBundle.message("convert.concatenation.to.template.before.text") ) open class ConvertToStringTemplateIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>( KtBinaryExpression::class.java, KotlinBundle.lazyMessage("convert.concatenation.to.template") ) { override fun isApplicableTo(element: KtBinaryExpression): Boolean { if (!isApplicableToNoParentCheck(element)) return false val parent = element.parent if (parent is KtBinaryExpression && isApplicableToNoParentCheck(parent)) return false return true } override fun applyTo(element: KtBinaryExpression, editor: Editor?) { val replacement = buildReplacement(element) runWriteActionIfPhysical(element) { element.replaced(replacement) } } companion object { fun shouldSuggestToConvert(expression: KtBinaryExpression): Boolean { val entries = buildReplacement(expression).entries return entries.none { it is KtBlockStringTemplateEntry } && !entries.all { it is KtLiteralStringTemplateEntry || it is KtEscapeStringTemplateEntry } && entries.count { it is KtLiteralStringTemplateEntry } >= 1 && !expression.textContains('\n') } @JvmStatic fun buildReplacement(expression: KtBinaryExpression): KtStringTemplateExpression { val rightText = buildText(expression.right, false) return fold(expression.left, rightText, KtPsiFactory(expression)) } private fun fold(left: KtExpression?, right: String, factory: KtPsiFactory): KtStringTemplateExpression { val forceBraces = right.isNotEmpty() && right.first() != '$' && right.first().isJavaIdentifierPart() return if (left is KtBinaryExpression && isApplicableToNoParentCheck(left)) { val leftRight = buildText(left.right, forceBraces) fold(left.left, leftRight + right, factory) } else { val leftText = buildText(left, forceBraces) factory.createExpression("\"$leftText$right\"") as KtStringTemplateExpression } } fun buildText(expr: KtExpression?, forceBraces: Boolean): String { if (expr == null) return "" val expression = KtPsiUtil.safeDeparenthesize(expr).let { when { (it as? KtDotQualifiedExpression)?.isToString() == true && it.receiverExpression !is KtSuperExpression -> it.receiverExpression it is KtLambdaExpression && it.parent is KtLabeledExpression -> expr else -> it } } val expressionText = expression.text when (expression) { is KtConstantExpression -> { val bindingContext = expression.analyze(BodyResolveMode.PARTIAL) val type = bindingContext.getType(expression)!! val constant = ConstantExpressionEvaluator.getConstant(expression, bindingContext) if (constant != null) { val stringValue = constant.getValue(type).toString() if (KotlinBuiltIns.isChar(type) || stringValue == expressionText) { return buildString { StringUtil.escapeStringCharacters(stringValue.length, stringValue, if (forceBraces) "\"$" else "\"", this) } } } } is KtStringTemplateExpression -> { val base = if (expressionText.startsWith("\"\"\"") && expressionText.endsWith("\"\"\"")) { val unquoted = expressionText.substring(3, expressionText.length - 3) StringUtil.escapeStringCharacters(unquoted) } else { StringUtil.unquoteString(expressionText) } if (forceBraces) { if (base.endsWith('$')) { return base.dropLast(1) + "\\$" } else { val lastPart = expression.children.lastOrNull() if (lastPart is KtSimpleNameStringTemplateEntry) { return base.dropLast(lastPart.textLength) + "\${" + lastPart.text.drop(1) + "}" } } } return base } is KtNameReferenceExpression -> return "$" + (if (forceBraces) "{$expressionText}" else expressionText) is KtThisExpression -> return "$" + (if (forceBraces || expression.labelQualifier != null) "{$expressionText}" else expressionText) } return "\${$expressionText}" } private fun isApplicableToNoParentCheck(expression: KtBinaryExpression): Boolean { if (expression.operationToken != KtTokens.PLUS) return false val expressionType = expression.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL).getType(expression) if (!KotlinBuiltIns.isString(expressionType)) return false return isSuitable(expression) } private fun isSuitable(expression: KtExpression): Boolean { if (expression is KtBinaryExpression && expression.operationToken == KtTokens.PLUS) { return isSuitable(expression.left ?: return false) && isSuitable(expression.right ?: return false) } if (PsiUtilCore.hasErrorElementChild(expression)) return false if (expression.textContains('\n')) return false return true } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToStringTemplateIntention.kt
2532156761
// WITH_STDLIB package test import kotlinx.parcelize.* import android.os.Parcelable @Parcelize class A(val firstName: String) : Parcelable { val <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">secondName</warning>: String = "" val <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">delegated</warning> by lazy { "" } lateinit var <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">lateinit</warning>: String val customGetter: String get() = "" var customSetter: String get() = "" set(<warning descr="[UNUSED_PARAMETER] Parameter 'v' is never used">v</warning>) {} } @Parcelize @Suppress("WRONG_ANNOTATION_TARGET_WITH_USE_SITE_TARGET") class B(<warning descr="[INAPPLICABLE_IGNORED_ON_PARCEL_CONSTRUCTOR_PROPERTY] '@IgnoredOnParcel' is inapplicable to properties without default value declared in the primary constructor">@IgnoredOnParcel</warning> val firstName: String) : Parcelable { @IgnoredOnParcel var a: String = "" @field:IgnoredOnParcel var <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">b</warning>: String = "" @get:IgnoredOnParcel var c: String = "" @set:IgnoredOnParcel var <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">d</warning>: String = "" }
plugins/kotlin/compiler-plugins/parcelize/tests/testData/checker/properties.kt
3799922409
package com.onyx.endpoint import com.fasterxml.jackson.databind.ObjectMapper import com.onyx.exception.EntityClassNotFoundException import com.onyx.exception.OnyxException import com.onyx.extension.* import com.onyx.extension.common.* import com.onyx.interactors.classfinder.ApplicationClassFinder import com.onyx.persistence.IManagedEntity import com.onyx.persistence.context.SchemaContext import com.onyx.persistence.manager.PersistenceManager import com.onyx.persistence.query.Query import com.onyx.request.pojo.* import java.io.IOException /** * Created by timothy.osborn on 4/8/15. * * This class handles JSON serialization for a persistence web service */ class WebPersistenceEndpoint(private val persistenceManager: PersistenceManager, private val objectMapper: ObjectMapper, private val context: SchemaContext) { /** * Save Entity * * @param request Entity Request Body * @return Managed entity after save with populated id */ fun save(request: EntityRequestBody): IManagedEntity { val clazz = ApplicationClassFinder.forName(request.type!!, context) val entity = objectMapper.convertValue(request.entity, clazz) persistenceManager.saveEntity(entity as IManagedEntity) return entity } /** * Find Entity * * @param request Entity Request Body * @return Hydrated entity */ operator fun get(request: EntityRequestBody): IManagedEntity { val clazz = ApplicationClassFinder.forName(request.type, context) var entity: IManagedEntity entity = if (request.entity == null) clazz.instance() else objectMapper.convertValue(request.entity, clazz) as IManagedEntity if (request.id != null) { val descriptor = entity.descriptor(context) entity[context, descriptor, descriptor.identifier!!.name] = request.id.castTo(descriptor.identifier!!.type) } entity = persistenceManager.find(entity) return entity } /** * Find an entity by id and partition value */ fun find(request: EntityFindRequest): IManagedEntity? { val clazz = ApplicationClassFinder.forName(request.type, context) return persistenceManager.findByIdInPartition(clazz, request.id!!, request.partitionValue ?: "") } /** * Delete Entity * * @param request Entity Request Body * @return Whether the entity was deleted or not */ fun delete(request: EntityRequestBody): Boolean { val clazz = ApplicationClassFinder.forName(request.type, context) val entity: IManagedEntity entity = objectMapper.convertValue(request.entity, clazz) as IManagedEntity return persistenceManager.deleteEntity(entity) } /** * Execute Query * * @param query Query Body * @return Query Result body */ fun executeQuery(query: Query): QueryResultResponseBody { val results = persistenceManager.executeQuery<Any>(query) return QueryResultResponseBody(query.resultsCount, results.toMutableList()) } /** * Initialize Relationship. Called upon a to many relationship * * @param request Initialize Body Error * @return List of relationship objects */ fun initialize(request: EntityInitializeBody): Any? { val clazz = ApplicationClassFinder.forName(request.entityType, context) val entity = clazz.getDeclaredConstructor().newInstance() as IManagedEntity if (request.entityId != null) { val descriptor = entity.descriptor(context) entity[context, descriptor, descriptor.identifier!!.name] = request.entityId.castTo(descriptor.identifier!!.type) } if (request.partitionId != null && request.partitionId != "") { val descriptor = entity.descriptor(context) entity[context, descriptor, descriptor.partition!!.field.name] = request.partitionId.castTo(descriptor.partition!!.field.type) } persistenceManager.initialize(entity, request.attribute!!) return entity.getObject(context.getDescriptorForEntity(entity).relationships[request.attribute!!]!!.field) } /** * Batch Save * * @param request List of entity body */ fun saveEntities(request: EntityListRequestBody) { val clazz = ApplicationClassFinder.forName(request.type, context) val javaType = objectMapper.typeFactory.constructCollectionType(List::class.java, clazz) val entities: List<IManagedEntity> entities = try { objectMapper.convertValue(request.entities, javaType) } catch (e: IOException) { throw EntityClassNotFoundException(OnyxException.UNKNOWN_EXCEPTION) } persistenceManager.saveEntities(entities) } /** * Batch Delete * * @param request Entity List body */ fun deleteEntities(request: EntityListRequestBody) { val clazz = ApplicationClassFinder.forName(request.type, context) val javaType = objectMapper.typeFactory.constructCollectionType(List::class.java, clazz) val entities: List<IManagedEntity> entities = try { objectMapper.convertValue(request.entities, javaType) } catch (e: IOException) { throw EntityClassNotFoundException(OnyxException.UNKNOWN_EXCEPTION) } persistenceManager.deleteEntities(entities) } /** * Execute Update * * @param query Entity Query Body * @return Query Result body */ fun executeUpdate(query: Query): Int = persistenceManager.executeUpdate(query) /** * Execute Delete * * @param query Entity Query Body * @return Query Result body */ fun executeDelete(query: Query): Int = persistenceManager.executeDelete(query) /** * Exists * * @param body Entity Request Body * @return Whether the entity exists or not */ fun existsWithId(body: EntityFindRequest): Boolean = find(body) != null /** * Save Deferred Relationships * * @param request Save Relationship Request Body */ fun saveRelationshipsForEntity(request: SaveRelationshipRequestBody) { val clazz = ApplicationClassFinder.forName(request.type, context) val entity = objectMapper.convertValue(request.entity, clazz) as IManagedEntity persistenceManager.saveRelationshipsForEntity(entity, request.relationship!!, request.identifiers!!) } /** * Returns the number of items matching the query criteria * * @param query Query request body * @return long value of number of items matching criteria * @since 1.3.0 Added as enhancement for git issue #71 */ fun countForQuery(query: Query): Long = persistenceManager.countForQuery(query) }
onyx-web-database/src/main/kotlin/com/onyx/endpoint/WebPersistenceEndpoint.kt
2192344574
package sample expect interface <!LINE_MARKER("descr='Has actuals in jvm module'"), LINE_MARKER("descr='Is subclassed by B Click or press ... to navigate'")!>A<!><T : A<T>> { fun <!LINE_MARKER("descr='Has actuals in jvm module'")!>foo<!>(): T } interface B : A<B> fun test(a: A<*>) { a.foo() a.foo().foo() } fun test(b: B) { b.foo() b.foo().foo() }
plugins/kotlin/idea/tests/testData/multiplatform/recursiveTypes/common/common.kt
1446936801
package com.intellij.codeInspection.tests import com.intellij.refactoring.migration.MigrationMap import com.intellij.refactoring.migration.MigrationMapEntry import com.intellij.refactoring.migration.MigrationProcessor import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase import junit.framework.TestCase abstract class MigrationTestBase : LightJavaCodeInsightFixtureTestCase() { fun migrationTest(lang: ULanguage, before: String, after: String, vararg migrations: MigrationMapEntry) { val migrationMap = MigrationMap(migrations) myFixture.configureByText("UnderTest${lang.ext}", before) MigrationProcessor(project, migrationMap).run() TestCase.assertEquals(after, myFixture.file.text) } }
jvm/jvm-analysis-tests/src/com/intellij/codeInspection/tests/MigrationTestBase.kt
174734353
// 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.credentialStore.kdbx import com.intellij.configurationStore.JbXmlOutputter import com.intellij.credentialStore.OneTimeString import org.bouncycastle.crypto.SkippingStreamCipher import org.jdom.Element import org.jdom.Text import java.io.Writer import java.util.* internal interface SecureString { fun get(clearable: Boolean = true): OneTimeString } internal class ProtectedValue(private var encryptedValue: ByteArray, private var position: Int, private var streamCipher: SkippingStreamCipher) : Text(), SecureString { @Synchronized override fun get(clearable: Boolean): OneTimeString { val output = ByteArray(encryptedValue.size) decryptInto(output) return OneTimeString(output, clearable = clearable) } @Synchronized fun setNewStreamCipher(newStreamCipher: SkippingStreamCipher) { val value = encryptedValue decryptInto(value) synchronized(newStreamCipher) { position = newStreamCipher.position.toInt() newStreamCipher.processBytes(value, 0, value.size, value, 0) } streamCipher = newStreamCipher } @Synchronized private fun decryptInto(out: ByteArray) { synchronized(streamCipher) { streamCipher.seekTo(position.toLong()) streamCipher.processBytes(encryptedValue, 0, encryptedValue.size, out, 0) } } override fun getText() = throw IllegalStateException("encodeToBase64 must be used for serialization") fun encodeToBase64(): String { return when { encryptedValue.isEmpty() -> "" else -> Base64.getEncoder().encodeToString(encryptedValue) } } } internal class UnsavedProtectedValue(val secureString: StringProtectedByStreamCipher) : Text(), SecureString by secureString { override fun getText() = throw IllegalStateException("Must be converted to ProtectedValue for serialization") } internal class ProtectedXmlWriter(private val streamCipher: SkippingStreamCipher) : JbXmlOutputter(isForbidSensitiveData = false) { override fun writeContent(out: Writer, element: Element, level: Int): Boolean { if (element.name != KdbxEntryElementNames.value) { return super.writeContent(out, element, level) } val value = element.content.firstOrNull() if (value is SecureString) { val protectedValue: ProtectedValue if (value is ProtectedValue) { value.setNewStreamCipher(streamCipher) protectedValue = value } else { val bytes = (value as UnsavedProtectedValue).secureString.getAsByteArray() synchronized(streamCipher) { val position = streamCipher.position.toInt() streamCipher.processBytes(bytes, 0, bytes.size, bytes, 0) protectedValue = ProtectedValue(bytes, position, streamCipher) } element.setContent(protectedValue) } out.write('>'.code) out.write(escapeElementEntities(protectedValue.encodeToBase64())) return true } return super.writeContent(out, element, level) } } internal fun isValueProtected(valueElement: Element): Boolean { return valueElement.getAttributeValue(KdbxAttributeNames.protected).equals("true", ignoreCase = true) } internal class XmlProtectedValueTransformer(private val streamCipher: SkippingStreamCipher) { private var position = 0 fun processEntries(parentElement: Element) { // we must process in exact order for (element in parentElement.content) { if (element !is Element) { continue } if (element.name == KdbxDbElementNames.group) { processEntries(element) } else if (element.name == KdbxDbElementNames.entry) { for (container in element.getChildren(KdbxEntryElementNames.string)) { val valueElement = container.getChild(KdbxEntryElementNames.value) ?: continue if (isValueProtected(valueElement)) { val value = Base64.getDecoder().decode(valueElement.text) valueElement.setContent(ProtectedValue(value, position, streamCipher)) position += value.size } } } } } }
platform/credential-store/src/kdbx/ProtectedValue.kt
2384755603
// 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.openapi.externalSystem.service.project import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.module.Module import com.intellij.openapi.project.isExternalStorageEnabled import com.intellij.openapi.roots.ExternalProjectSystemRegistry import com.intellij.openapi.roots.ProjectModelElement import com.intellij.openapi.roots.ProjectModelExternalSource import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Transient import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty val EMPTY_STATE: ExternalStateComponent = ExternalStateComponent() /** * This class isn't used in the new implementation of project model, which is based on [Workspace Model][com.intellij.workspaceModel.ide]. * It shouldn't be used directly, its interface [ExternalSystemModulePropertyManager] should be used instead. */ @State(name = "ExternalSystem") class ExternalSystemModulePropertyManagerImpl(private val module: Module) : ExternalSystemModulePropertyManager(), PersistentStateComponent<ExternalStateComponent>, ProjectModelElement { override fun getExternalSource(): ProjectModelExternalSource? = store.externalSystem?.let { ExternalProjectSystemRegistry.getInstance().getSourceById(it) } private var store = if (module.project.isExternalStorageEnabled) ExternalStateComponent() else ExternalStateModule(module) override fun getState(): ExternalStateComponent = store as? ExternalStateComponent ?: EMPTY_STATE override fun loadState(state: ExternalStateComponent) { store = state } override fun getExternalSystemId(): String? = store.externalSystem override fun getExternalModuleType(): String? = store.externalSystemModuleType override fun getExternalModuleVersion(): String? = store.externalSystemModuleVersion override fun getExternalModuleGroup(): String? = store.externalSystemModuleGroup override fun getLinkedProjectId(): String? = store.linkedProjectId override fun getRootProjectPath(): String? = store.rootProjectPath override fun getLinkedProjectPath(): String? = store.linkedProjectPath override fun isMavenized(): Boolean = store.isMavenized override fun setMavenized(mavenized: Boolean) { if (mavenized) { // clear external system API options // see com.intellij.openapi.externalSystem.service.project.manage.ModuleDataService#setModuleOptions unlinkExternalOptions() } // must be after unlinkExternalOptions store.isMavenized = mavenized } override fun swapStore() { val oldStore = store val isMaven = oldStore.isMavenized if (oldStore is ExternalStateModule) { store = ExternalStateComponent() } else { store = ExternalStateModule(module) } store.externalSystem = if (store is ExternalStateModule && isMaven) null else oldStore.externalSystem if (store !is ExternalStateComponent) { // do not set isMavenized for ExternalStateComponent it just set externalSystem store.isMavenized = isMaven } store.linkedProjectId = oldStore.linkedProjectId store.linkedProjectPath = oldStore.linkedProjectPath store.rootProjectPath = oldStore.rootProjectPath store.externalSystemModuleGroup = oldStore.externalSystemModuleGroup store.externalSystemModuleVersion = oldStore.externalSystemModuleVersion if (oldStore is ExternalStateModule) { oldStore.isMavenized = false oldStore.unlinkExternalOptions() } } override fun unlinkExternalOptions() { store.unlinkExternalOptions() } override fun setExternalOptions(id: ProjectSystemId, moduleData: ModuleData, projectData: ProjectData?) { // clear maven option, must be first store.isMavenized = false store.externalSystem = id.toString() store.linkedProjectId = moduleData.id store.linkedProjectPath = moduleData.linkedExternalProjectPath store.rootProjectPath = projectData?.linkedExternalProjectPath ?: "" store.externalSystemModuleGroup = moduleData.group store.externalSystemModuleVersion = moduleData.version } override fun setExternalId(id: ProjectSystemId) { store.externalSystem = id.id } override fun setLinkedProjectPath(path: String?) { store.linkedProjectPath = path } override fun setRootProjectPath(path: String?) { store.rootProjectPath = path } override fun setExternalModuleType(type: String?) { store.externalSystemModuleType = type } } private interface ExternalOptionState { var externalSystem: String? var externalSystemModuleVersion: String? var linkedProjectPath: String? var linkedProjectId: String? var rootProjectPath: String? var externalSystemModuleGroup: String? var externalSystemModuleType: String? var isMavenized: Boolean } private fun ExternalOptionState.unlinkExternalOptions() { externalSystem = null linkedProjectId = null linkedProjectPath = null rootProjectPath = null externalSystemModuleGroup = null externalSystemModuleVersion = null } @Suppress("DEPRECATION") private class ModuleOptionDelegate(private val key: String) : ReadWriteProperty<ExternalStateModule, String?> { override operator fun getValue(thisRef: ExternalStateModule, property: KProperty<*>) = thisRef.module.getOptionValue(key) override operator fun setValue(thisRef: ExternalStateModule, property: KProperty<*>, value: String?) { thisRef.module.setOption(key, value) } } @Suppress("DEPRECATION") private class ExternalStateModule(internal val module: Module) : ExternalOptionState { override var externalSystem by ModuleOptionDelegate(ExternalProjectSystemRegistry.EXTERNAL_SYSTEM_ID_KEY) override var externalSystemModuleVersion by ModuleOptionDelegate("external.system.module.version") override var externalSystemModuleGroup by ModuleOptionDelegate("external.system.module.group") override var externalSystemModuleType by ModuleOptionDelegate("external.system.module.type") override var linkedProjectPath by ModuleOptionDelegate("external.linked.project.path") override var linkedProjectId by ModuleOptionDelegate("external.linked.project.id") override var rootProjectPath by ModuleOptionDelegate("external.root.project.path") override var isMavenized: Boolean get() = "true" == module.getOptionValue(ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY) set(value) { module.setOption(ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY, if (value) "true" else null) } } class ExternalStateComponent : ExternalOptionState { @get:Attribute override var externalSystem: String? = null @get:Attribute override var externalSystemModuleVersion: String? = null @get:Attribute override var externalSystemModuleGroup: String? = null @get:Attribute override var externalSystemModuleType: String? = null @get:Attribute override var linkedProjectPath: String? = null @get:Attribute override var linkedProjectId: String? = null @get:Attribute override var rootProjectPath: String? = null @get:Transient override var isMavenized: Boolean get() = externalSystem == ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID set(value) { externalSystem = if (value) ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID else null } }
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ExternalSystemModulePropertyManagerImpl.kt
3623301092
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository.git import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import org.eclipse.jgit.lib.NullProgressMonitor import org.eclipse.jgit.lib.ProgressMonitor fun ProgressIndicator?.asProgressMonitor() = if (this == null || this is EmptyProgressIndicator) NullProgressMonitor.INSTANCE else JGitProgressMonitor(this) private class JGitProgressMonitor(private val indicator: ProgressIndicator) : ProgressMonitor { override fun start(totalTasks: Int) { } override fun beginTask(title: String, totalWork: Int) { indicator.text2 = title } override fun update(completed: Int) { // todo } override fun endTask() { indicator.text2 = "" } override fun isCancelled() = indicator.isCanceled }
plugins/settings-repository/src/git/JGitProgressMonitor.kt
2519748256
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.refactoring.suggested import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.psi.util.hasErrorElementInRange import com.intellij.refactoring.suggested.* import com.jetbrains.python.PyNames import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.psi.PyElement import com.jetbrains.python.psi.PyFunction import com.jetbrains.python.psi.PyParameter import com.jetbrains.python.psi.PyParameterList import com.jetbrains.python.psi.types.TypeEvalContext import com.jetbrains.python.pyi.PyiUtil class PySuggestedRefactoringSupport : SuggestedRefactoringSupport { companion object { internal fun isAvailableForChangeSignature(element: PsiElement): Boolean { return element is PyFunction && element.name.let { it != null && PyNames.isIdentifier(it) } && element.property == null && !shouldBeSuppressed(element) } internal fun defaultValue(parameter: SuggestedRefactoringSupport.Parameter): String? { return (parameter.additionalData as? ParameterData)?.defaultValue } internal fun isAvailableForRename(element: PsiElement): Boolean { return element is PsiNameIdentifierOwner && element.name.let { it != null && PyNames.isIdentifier(it) } && (element !is PyParameter || containingFunction(element).let { it != null && !isAvailableForChangeSignature(it) }) && !shouldBeSuppressed(element) } internal fun shouldSuppressRefactoringForDeclaration(state: SuggestedRefactoringState): Boolean { // don't merge with `shouldBeSuppressed` because `shouldBeSuppressed` could be invoked in EDT and resolve below could slow down it val element = state.restoredDeclarationCopy() return PyiUtil.isOverload(element, TypeEvalContext.codeAnalysis(element.project, element.containingFile)) } private fun shouldBeSuppressed(element: PsiElement): Boolean { if (PyiUtil.isInsideStub(element)) return true if (element is PyElement && PyiUtil.getPythonStub(element) != null) return true return false } private fun containingFunction(parameter: PyParameter): PyFunction? { return (parameter.parent as? PyParameterList)?.containingFunction } } override fun isDeclaration(psiElement: PsiElement): Boolean = findSupport(psiElement) != null override fun signatureRange(declaration: PsiElement): TextRange? = findSupport(declaration)?.signatureRange(declaration)?.takeIf { !declaration.containingFile.hasErrorElementInRange(it) } override fun importsRange(psiFile: PsiFile): TextRange? = null override fun nameRange(declaration: PsiElement): TextRange? = (declaration as? PsiNameIdentifierOwner)?.nameIdentifier?.textRange override fun isIdentifierStart(c: Char): Boolean = c == '_' || Character.isLetter(c) override fun isIdentifierPart(c: Char): Boolean = isIdentifierStart(c) || Character.isDigit(c) override val stateChanges: SuggestedRefactoringStateChanges = PySuggestedRefactoringStateChanges(this) override val availability: SuggestedRefactoringAvailability = PySuggestedRefactoringAvailability(this) override val ui: SuggestedRefactoringUI = PySuggestedRefactoringUI override val execution: SuggestedRefactoringExecution = PySuggestedRefactoringExecution(this) internal data class ParameterData(val defaultValue: String?) : SuggestedRefactoringSupport.ParameterAdditionalData private fun findSupport(declaration: PsiElement): SupportInternal? { return sequenceOf(ChangeSignatureSupport, RenameSupport(this)).firstOrNull { it.isApplicable(declaration) } } private interface SupportInternal { fun isApplicable(element: PsiElement): Boolean fun signatureRange(declaration: PsiElement): TextRange? } private object ChangeSignatureSupport : SupportInternal { override fun isApplicable(element: PsiElement): Boolean = isAvailableForChangeSignature(element) override fun signatureRange(declaration: PsiElement): TextRange? { declaration as PyFunction val name = declaration.nameIdentifier ?: return null val colon = declaration.node.findChildByType(PyTokenTypes.COLON) ?: return null return TextRange.create(name.startOffset, colon.startOffset) } } private class RenameSupport(private val mainSupport: PySuggestedRefactoringSupport) : SupportInternal { override fun isApplicable(element: PsiElement): Boolean = isAvailableForRename(element) override fun signatureRange(declaration: PsiElement): TextRange? = mainSupport.nameRange(declaration) } }
python/src/com/jetbrains/python/refactoring/suggested/PySuggestedRefactoringSupport.kt
2033749859
object O { constr<caret> } // NUMBER: 0
plugins/kotlin/completion/tests/testData/keywords/NoConstructorInObject.kt
4225249534
package com.ebanx.library import android.view.GestureDetector import android.view.MotionEvent import android.view.View class GestureListener internal constructor(private val animator: GestureListener.GestureAnimator, private val menuContainer: View, private val contentContainer: View, private val endOffSet: Int, val screenSize: Int, private val expandedContentHeight: Int, private val collapsedContentHeight: Int) : GestureDetector.SimpleOnGestureListener() { var isExpanded: Boolean = false var isScrolling: Boolean = false var isOnFling: Boolean = false var isAnimating: Boolean = false private val rightEdge: Float private val leftEdge: Float init { isExpanded = false rightEdge = screenSize * RIGHT_TRIGGER_MULTIPLICATOR leftEdge = screenSize * LEFT_TRIGGER_MULTIPLICATOR } override fun onDown(e: MotionEvent): Boolean { return true } override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { val diffY = e2.y - e1.y val diffX = e2.x - e1.x if (!isScrolling && Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 30) { isScrolling = true } if (!isScrolling) { return false } if (!isExpanded && diffX > 0 && isScrolling && e1.x < leftEdge) { contentContainer.x = diffX // menuContainer.setX(diffX - contentContainer.getWidth()); val layoutParams = contentContainer.layoutParams layoutParams.height = (expandedContentHeight - 0.15 * expandedContentHeight.toDouble() * contentContainer.x.toDouble() / screenSize).toInt() contentContainer.layoutParams = layoutParams return false } else if (isExpanded && diffX < 0 && isScrolling && e1.x > rightEdge) { contentContainer.x = diffX + contentContainer.width // menuContainer.setX(diffX); val layoutParams = contentContainer.layoutParams layoutParams.height = (expandedContentHeight - 0.15 * expandedContentHeight.toDouble() * contentContainer.x.toDouble() / screenSize).toInt() contentContainer.layoutParams = layoutParams return false } return false } override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { if (!isScrolling && (Math.abs(velocityX) < FLING_TRIGGER_VELOCITY || Math.abs(velocityX) < Math.abs(velocityY))) { return true } val diffX = e2.x - e1.x isOnFling = true if (diffX > 40 && e1.x < leftEdge) { animator.flingWidthAnimation(contentContainer.x, (screenSize - endOffSet).toFloat(), expandedContentHeight, collapsedContentHeight, contentContainer, menuContainer) return true } if (diffX < -40 && e1.x > rightEdge) { animator.flingWidthAnimation(contentContainer.x, 0f, collapsedContentHeight, expandedContentHeight, contentContainer, menuContainer) return true } return false } internal interface GestureAnimator { fun flingWidthAnimation(initialX: Float, finalX: Float, initialHeight: Int, finalHeight: Int, slideView: View, expandView: View) } companion object { private val RIGHT_TRIGGER_MULTIPLICATOR = 9f / 10f private val LEFT_TRIGGER_MULTIPLICATOR = 1 / 10f private val FLING_TRIGGER_VELOCITY = 2000f } }
library/src/main/java/com/ebanx/library/GestureListener.kt
514616712
package com.apkfuns.class3 import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getTargetContext() assertEquals("com.apkfuns.class3", appContext.packageName) } }
HenCoderSample/class3/src/androidTest/java/com/apkfuns/class3/ExampleInstrumentedTest.kt
879356701
/* * 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. */ package org.jetbrains.kotlin.native.interop.gen import org.jetbrains.kotlin.konan.library.KonanLibrary import org.jetbrains.kotlin.native.interop.indexer.* interface Imports { fun getPackage(location: Location): String? } class PackageInfo(val name: String, val library: KonanLibrary) class ImportsImpl(internal val headerIdToPackage: Map<HeaderId, PackageInfo>) : Imports { override fun getPackage(location: Location): String? { val packageInfo = headerIdToPackage[location.headerId] ?: return null accessedLibraries += packageInfo.library return packageInfo.name } private val accessedLibraries = mutableSetOf<KonanLibrary>() val requiredLibraries: Set<KonanLibrary> get() = accessedLibraries.toSet() } class HeaderInclusionPolicyImpl(private val nameGlobs: List<String>) : HeaderInclusionPolicy { override fun excludeUnused(headerName: String?): Boolean { if (nameGlobs.isEmpty()) { return false } if (headerName == null) { // Builtins; included only if no globs are specified: return true } return nameGlobs.all { !headerName.matchesToGlob(it) } } } class HeaderExclusionPolicyImpl( private val importsImpl: ImportsImpl ) : HeaderExclusionPolicy { override fun excludeAll(headerId: HeaderId): Boolean { return headerId in importsImpl.headerIdToPackage } } private fun String.matchesToGlob(glob: String): Boolean = java.nio.file.FileSystems.getDefault() .getPathMatcher("glob:$glob").matches(java.nio.file.Paths.get(this))
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/Imports.kt
868868933
// 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.devkit.uiDesigner import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.EditorTextFieldWithBrowseButton import com.intellij.ui.layout.* import javax.swing.JComponent class ConvertFormDialog(val project: Project, var className: String) : DialogWrapper(project) { enum class FormBaseClass { None, Configurable } var boundInstanceType: String = "" var boundInstanceExpression: String = "" var generateDescriptors = false var baseClass = FormBaseClass.None init { init() title = DevKitUIDesignerBundle.message("convert.form.dialog.title") } override fun createCenterPanel(): JComponent? { return panel { row(DevKitUIDesignerBundle.message("convert.form.dialog.label.target.class.name")) { textField(::className, columns = 40).focused() } row(DevKitUIDesignerBundle.message("convert.form.dialog.label.bound.instance.type")) { EditorTextFieldWithBrowseButton(project, true)() .withBinding(EditorTextFieldWithBrowseButton::getText, EditorTextFieldWithBrowseButton::setText, ::boundInstanceType.toBinding()) } row(DevKitUIDesignerBundle.message("convert.form.dialog.label.bound.instance.expression")) { textField(::boundInstanceExpression) } titledRow(DevKitUIDesignerBundle.message("convert.form.dialog.base.class.separator")) { buttonGroup(::baseClass) { row { radioButton(DevKitUIDesignerBundle.message("convert.form.dialog.base.class.none"), FormBaseClass.None) } row { radioButton(DevKitUIDesignerBundle.message("convert.form.dialog.base.class.configurable"), FormBaseClass.Configurable) row { checkBox(DevKitUIDesignerBundle.message("convert.form.dialog.label.checkbox.generate.descriptors.for.search.everywhere"), ::generateDescriptors) } } } } } } }
plugins/devkit/intellij.devkit.uiDesigner/src/ConvertFormDialog.kt
3481788130
// "Create parameter 'foo'" "false" // ACTION: Create local variable 'foo' // ACTION: Create property 'foo' // ACTION: Do not show return expression hints // ACTION: Rename reference // ERROR: Unresolved reference: foo class A { companion object { val test: Int get() { return <caret>foo } } }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createVariable/parameter/inAccessorInClassObject.kt
686219241
// 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 git4idea.ui.branch.dashboard import com.intellij.dvcs.DvcsUtil import com.intellij.dvcs.branch.GroupingKey import com.intellij.dvcs.ui.RepositoryChangesBrowserNode.Companion.getColorManager import com.intellij.dvcs.ui.RepositoryChangesBrowserNode.Companion.getRepositoryIcon import com.intellij.icons.AllIcons import com.intellij.ide.dnd.TransferableList import com.intellij.ide.dnd.aware.DnDAwareTree import com.intellij.ide.util.treeView.TreeState import com.intellij.openapi.Disposable import com.intellij.openapi.application.runInEdt import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.codeStyle.FixingLayoutMatcher import com.intellij.psi.codeStyle.MinusculeMatcher import com.intellij.psi.codeStyle.NameUtil import com.intellij.ui.* import com.intellij.ui.hover.TreeHoverListener import com.intellij.ui.speedSearch.SpeedSearch import com.intellij.ui.speedSearch.SpeedSearchSupply import com.intellij.util.EditSourceOnDoubleClickHandler.isToggleEvent import com.intellij.util.PlatformIcons import com.intellij.util.ThreeState import com.intellij.util.ui.UIUtil import com.intellij.util.ui.tree.TreeUtil import com.intellij.vcs.branch.BranchData import com.intellij.vcs.branch.BranchPresentation import com.intellij.vcs.branch.LinkedBranchDataImpl import com.intellij.vcs.log.util.VcsLogUtil import com.intellij.vcsUtil.VcsImplUtil import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.ui.branch.GitBranchManager import git4idea.ui.branch.GitBranchPopupActions.LocalBranchActions.constructIncomingOutgoingTooltip import git4idea.ui.branch.dashboard.BranchesDashboardActions.BranchesTreeActionGroup import icons.DvcsImplIcons import org.jetbrains.annotations.NonNls import java.awt.Graphics import java.awt.GraphicsEnvironment import java.awt.datatransfer.Transferable import java.awt.event.MouseEvent import java.util.* import javax.swing.Icon import javax.swing.JComponent import javax.swing.JTree import javax.swing.TransferHandler import javax.swing.event.TreeExpansionEvent import javax.swing.event.TreeExpansionListener import javax.swing.tree.TreePath internal class BranchesTreeComponent(project: Project) : DnDAwareTree() { var doubleClickHandler: (BranchTreeNode) -> Unit = {} var searchField: SearchTextField? = null init { putClientProperty(AUTO_SELECT_ON_MOUSE_PRESSED, false) setCellRenderer(BranchTreeCellRenderer(project)) isRootVisible = false setShowsRootHandles(true) isOpaque = false isHorizontalAutoScrollingEnabled = false installDoubleClickHandler() SmartExpander.installOn(this) TreeHoverListener.DEFAULT.addTo(this) initDnD() } private inner class BranchTreeCellRenderer(project: Project) : ColoredTreeCellRenderer() { private val repositoryManager = GitRepositoryManager.getInstance(project) private val colorManager = getColorManager(project) private val branchManager = project.service<GitBranchManager>() private var incomingOutgoingIcon: NodeIcon? = null override fun customizeCellRenderer(tree: JTree, value: Any?, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean) { if (value !is BranchTreeNode) return val descriptor = value.getNodeDescriptor() val branchInfo = descriptor.branchInfo val isBranchNode = descriptor.type == NodeType.BRANCH val isGroupNode = descriptor.type == NodeType.GROUP_NODE val isRepositoryNode = descriptor.type == NodeType.GROUP_REPOSITORY_NODE icon = when { isBranchNode && branchInfo != null && branchInfo.isCurrent && branchInfo.isFavorite -> DvcsImplIcons.CurrentBranchFavoriteLabel isBranchNode && branchInfo != null && branchInfo.isCurrent -> DvcsImplIcons.CurrentBranchLabel isBranchNode && branchInfo != null && branchInfo.isFavorite -> AllIcons.Nodes.Favorite isBranchNode -> AllIcons.Vcs.BranchNode isGroupNode -> PlatformIcons.FOLDER_ICON isRepositoryNode -> getRepositoryIcon(descriptor.repository!!, colorManager) else -> null } toolTipText = if (branchInfo != null && branchInfo.isLocal) BranchPresentation.getTooltip(getBranchesTooltipData(branchInfo.branchName, getSelectedRepositories(descriptor))) else null append(value.getTextRepresentation(), SimpleTextAttributes.REGULAR_ATTRIBUTES, true) val repositoryGrouping = branchManager.isGroupingEnabled(GroupingKey.GROUPING_BY_REPOSITORY) if (!repositoryGrouping && branchInfo != null && branchInfo.repositories.size < repositoryManager.repositories.size) { append(" (${DvcsUtil.getShortNames(branchInfo.repositories)})", SimpleTextAttributes.GRAYED_ATTRIBUTES) } val incomingOutgoingState = branchInfo?.incomingOutgoingState incomingOutgoingIcon = incomingOutgoingState?.icon?.let { NodeIcon(it, preferredSize.width + tree.insets.left) } tree.toolTipText = incomingOutgoingState?.run { constructIncomingOutgoingTooltip(hasIncoming(), hasOutgoing()) } } override fun calcFocusedState() = super.calcFocusedState() || searchField?.textEditor?.hasFocus() ?: false private fun getBranchesTooltipData(branchName: String, repositories: Collection<GitRepository>): List<BranchData> { return repositories.map { repo -> val trackedBranchName = repo.branches.findLocalBranch(branchName)?.findTrackedBranch(repo)?.name val presentableRootName = VcsImplUtil.getShortVcsRootName(repo.project, repo.root) LinkedBranchDataImpl(presentableRootName, branchName, trackedBranchName) } } override fun paint(g: Graphics) { super.paint(g) incomingOutgoingIcon?.let { (icon, locationX) -> icon.paintIcon(this@BranchTreeCellRenderer, g, locationX, (size.height - icon.iconHeight) / 2) } } } private data class NodeIcon(val icon: Icon, val locationX: Int) override fun hasFocus() = super.hasFocus() || searchField?.textEditor?.hasFocus() ?: false private fun installDoubleClickHandler() { object : DoubleClickListener() { override fun onDoubleClick(e: MouseEvent): Boolean { val clickPath = getClosestPathForLocation(e.x, e.y) ?: return false val selectionPath = selectionPath if (selectionPath == null || clickPath != selectionPath) return false val node = (selectionPath.lastPathComponent as? BranchTreeNode) ?: return false if (isToggleEvent(this@BranchesTreeComponent, e)) return false doubleClickHandler(node) return true } }.installOn(this) } private fun initDnD() { if (!GraphicsEnvironment.isHeadless()) { transferHandler = BRANCH_TREE_TRANSFER_HANDLER } } fun getSelectedBranches(): List<BranchInfo> { return getSelectedNodes() .mapNotNull { it.getNodeDescriptor().branchInfo } .toList() } fun getSelectedNodes(): Sequence<BranchTreeNode> { val paths = selectionPaths ?: return emptySequence() return paths.asSequence() .map(TreePath::getLastPathComponent) .mapNotNull { it as? BranchTreeNode } } fun getSelectedRemotes(): Set<RemoteInfo> { val paths = selectionPaths ?: return emptySet() return paths.asSequence() .map(TreePath::getLastPathComponent) .mapNotNull { it as? BranchTreeNode } .filter { it.getNodeDescriptor().displayName != null && it.getNodeDescriptor().type == NodeType.GROUP_NODE && (it.getNodeDescriptor().parent?.type == NodeType.REMOTE_ROOT || it.getNodeDescriptor().parent?.repository != null) } .mapNotNull { with(it.getNodeDescriptor()) { RemoteInfo(displayName!!, parent?.repository) } } .toSet() } fun getSelectedRepositories(descriptor: BranchNodeDescriptor): List<GitRepository> { var parent = descriptor.parent while (parent != null) { val repository = parent.repository if (repository != null) return listOf(repository) parent = parent.parent } return descriptor.branchInfo?.repositories ?: emptyList() } fun getSelectedRepositories(branchInfo: BranchInfo): Set<GitRepository> { val paths = selectionPaths ?: return emptySet() return paths.asSequence() .filter { val lastPathComponent = it.lastPathComponent lastPathComponent is BranchTreeNode && lastPathComponent.getNodeDescriptor().branchInfo == branchInfo } .mapNotNull { findNodeDescriptorInPath(it) { descriptor -> Objects.nonNull(descriptor.repository) } } .mapNotNull(BranchNodeDescriptor::repository) .toSet() } private fun findNodeDescriptorInPath(path: TreePath, condition: (BranchNodeDescriptor) -> Boolean): BranchNodeDescriptor? { var curPath: TreePath? = path while (curPath != null) { val node = curPath.lastPathComponent as? BranchTreeNode if (node != null && condition(node.getNodeDescriptor())) return node.getNodeDescriptor() curPath = curPath.parentPath } return null } } internal class FilteringBranchesTree( val project: Project, val component: BranchesTreeComponent, private val uiController: BranchesDashboardController, rootNode: BranchTreeNode = BranchTreeNode(BranchNodeDescriptor(NodeType.ROOT)), place: @NonNls String, disposable: Disposable ) : FilteringTree<BranchTreeNode, BranchNodeDescriptor>(component, rootNode) { private val expandedPaths = HashSet<TreePath>() private val localBranchesNode = BranchTreeNode(BranchNodeDescriptor(NodeType.LOCAL_ROOT)) private val remoteBranchesNode = BranchTreeNode(BranchNodeDescriptor(NodeType.REMOTE_ROOT)) private val headBranchesNode = BranchTreeNode(BranchNodeDescriptor(NodeType.HEAD_NODE)) private val branchFilter: (BranchInfo) -> Boolean = { branch -> !uiController.showOnlyMy || branch.isMy == ThreeState.YES } private val nodeDescriptorsModel = NodeDescriptorsModel(localBranchesNode.getNodeDescriptor(), remoteBranchesNode.getNodeDescriptor()) private var localNodeExist = false private var remoteNodeExist = false private val treeStateProvider = BranchesTreeStateProvider(this, disposable) private val treeStateHolder: BranchesTreeStateHolder get() = project.service() private val groupingConfig: MutableMap<GroupingKey, Boolean> = with(project.service<GitBranchManager>()) { hashMapOf( GroupingKey.GROUPING_BY_DIRECTORY to isGroupingEnabled(GroupingKey.GROUPING_BY_DIRECTORY), GroupingKey.GROUPING_BY_REPOSITORY to isGroupingEnabled(GroupingKey.GROUPING_BY_REPOSITORY) ) } fun toggleGrouping(key: GroupingKey, state: Boolean) { groupingConfig[key] = state refreshTree() } fun isGroupingEnabled(key: GroupingKey) = groupingConfig[key] == true init { runInEdt { PopupHandler.installPopupMenu(component, BranchesTreeActionGroup(project, this), place) setupTreeListeners() } } override fun createSpeedSearch(searchTextField: SearchTextField): SpeedSearchSupply = object : FilteringSpeedSearch(searchTextField) { private val customWordMatchers = hashSetOf<MinusculeMatcher>() override fun matchingFragments(text: String): Iterable<TextRange?>? { val allTextRanges = super.matchingFragments(text) if (customWordMatchers.isEmpty()) return allTextRanges val wordRanges = arrayListOf<TextRange>() for (wordMatcher in customWordMatchers) { wordMatcher.matchingFragments(text)?.let(wordRanges::addAll) } return when { allTextRanges != null -> allTextRanges + wordRanges wordRanges.isNotEmpty() -> wordRanges else -> null } } override fun updatePattern(string: String?) { super.updatePattern(string) onUpdatePattern(string) } override fun onUpdatePattern(text: String?) { customWordMatchers.clear() customWordMatchers.addAll(buildCustomWordMatchers(text)) } private fun buildCustomWordMatchers(text: String?): Set<MinusculeMatcher> { if (text == null) return emptySet() val wordMatchers = hashSetOf<MinusculeMatcher>() for (word in StringUtil.split(text, " ")) { wordMatchers.add( FixingLayoutMatcher("*$word", NameUtil.MatchingCaseSensitivity.NONE, "")) } return wordMatchers } } override fun installSearchField(): SearchTextField { val searchField = super.installSearchField() component.searchField = searchField return searchField } private fun setupTreeListeners() { component.addTreeExpansionListener(object : TreeExpansionListener { override fun treeExpanded(event: TreeExpansionEvent) { expandedPaths.add(event.path) treeStateHolder.setStateProvider(treeStateProvider) } override fun treeCollapsed(event: TreeExpansionEvent) { expandedPaths.remove(event.path) treeStateHolder.setStateProvider(treeStateProvider) } }) component.addTreeSelectionListener { treeStateHolder.setStateProvider(treeStateProvider) } } fun getSelectedRepositories(branchInfo: BranchInfo): List<GitRepository> { val selectedRepositories = component.getSelectedRepositories(branchInfo) return if (selectedRepositories.isNotEmpty()) selectedRepositories.toList() else branchInfo.repositories } fun getSelectedBranches() = component.getSelectedBranches() fun getSelectedBranchFilters(): List<String> { return component.getSelectedNodes() .mapNotNull { with(it.getNodeDescriptor()) { if (type == NodeType.HEAD_NODE) VcsLogUtil.HEAD else branchInfo?.branchName } } .toList() } fun getSelectedRemotes() = component.getSelectedRemotes() fun getSelectedBranchNodes() = component.getSelectedNodes().map(BranchTreeNode::getNodeDescriptor).toSet() private fun restorePreviouslyExpandedPaths() { TreeUtil.restoreExpandedPaths(component, expandedPaths.toList()) } override fun expandTreeOnSearchUpdateComplete(pattern: String?) { restorePreviouslyExpandedPaths() } override fun onSpeedSearchUpdateComplete(pattern: String?) { updateSpeedSearchBackground() } override fun useIdentityHashing(): Boolean = false private fun updateSpeedSearchBackground() { val speedSearch = searchModel.speedSearch as? SpeedSearch ?: return val textEditor = component.searchField?.textEditor ?: return if (isEmptyModel()) { textEditor.isOpaque = true speedSearch.noHits() } else { textEditor.isOpaque = false textEditor.background = UIUtil.getTextFieldBackground() } } private fun isEmptyModel() = searchModel.isLeaf(localBranchesNode) && searchModel.isLeaf(remoteBranchesNode) override fun getNodeClass() = BranchTreeNode::class.java override fun createNode(nodeDescriptor: BranchNodeDescriptor) = when (nodeDescriptor.type) { NodeType.LOCAL_ROOT -> localBranchesNode NodeType.REMOTE_ROOT -> remoteBranchesNode NodeType.HEAD_NODE -> headBranchesNode else -> BranchTreeNode(nodeDescriptor) } override fun getChildren(nodeDescriptor: BranchNodeDescriptor) = when (nodeDescriptor.type) { NodeType.ROOT -> getRootNodeDescriptors() NodeType.LOCAL_ROOT -> localBranchesNode.getNodeDescriptor().getDirectChildren() NodeType.REMOTE_ROOT -> remoteBranchesNode.getNodeDescriptor().getDirectChildren() NodeType.GROUP_NODE -> nodeDescriptor.getDirectChildren() NodeType.GROUP_REPOSITORY_NODE -> nodeDescriptor.getDirectChildren() else -> emptyList() //leaf branch node } private fun BranchNodeDescriptor.getDirectChildren() = nodeDescriptorsModel.getChildrenForParent(this) fun update(initial: Boolean) { val branchesReloaded = uiController.reloadBranches() runPreservingTreeState(initial) { searchModel.updateStructure() } if (branchesReloaded) { tree.revalidate() tree.repaint() } } private fun runPreservingTreeState(loadSaved: Boolean, runnable: () -> Unit) { if (Registry.`is`("git.branches.panel.persist.tree.state")) { val treeState = if (loadSaved) treeStateHolder.getInitialTreeState() else TreeState.createOn(tree, root) runnable() if (treeState != null) { treeState.applyTo(tree) } else { initDefaultTreeExpandState() } } else { runnable() if (loadSaved) { initDefaultTreeExpandState() } } } private fun initDefaultTreeExpandState() { // expanding lots of nodes is a slow operation (and result is not very useful) if (TreeUtil.hasManyNodes(tree, 30000)) { TreeUtil.collapseAll(tree, 1) } else { TreeUtil.expandAll(tree) } } fun refreshTree() { runPreservingTreeState(false) { tree.selectionModel.clearSelection() refreshNodeDescriptorsModel() searchModel.updateStructure() } } fun refreshNodeDescriptorsModel() { with(uiController) { nodeDescriptorsModel.clear() localNodeExist = localBranches.isNotEmpty() remoteNodeExist = remoteBranches.isNotEmpty() nodeDescriptorsModel.populateFrom((localBranches.asSequence() + remoteBranches.asSequence()).filter(branchFilter), groupingConfig) } } override fun getText(nodeDescriptor: BranchNodeDescriptor?) = nodeDescriptor?.branchInfo?.branchName ?: nodeDescriptor?.displayName private fun getRootNodeDescriptors() = mutableListOf<BranchNodeDescriptor>().apply { if (localNodeExist || remoteNodeExist) add(headBranchesNode.getNodeDescriptor()) if (localNodeExist) add(localBranchesNode.getNodeDescriptor()) if (remoteNodeExist) add(remoteBranchesNode.getNodeDescriptor()) } } private val BRANCH_TREE_TRANSFER_HANDLER = object : TransferHandler() { override fun createTransferable(tree: JComponent): Transferable? { if (tree is BranchesTreeComponent) { val branches = tree.getSelectedBranches() if (branches.isEmpty()) return null return object : TransferableList<BranchInfo>(branches.toList()) { override fun toString(branch: BranchInfo) = branch.toString() } } return null } override fun getSourceActions(c: JComponent) = COPY_OR_MOVE } @State(name = "BranchesTreeState", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)], reportStatistic = false) @Service(Service.Level.PROJECT) internal class BranchesTreeStateHolder : PersistentStateComponent<TreeState> { private var treeStateProvider: BranchesTreeStateProvider? = null private var _treeState: TreeState? = null fun getInitialTreeState(): TreeState? = state override fun getState(): TreeState? { return treeStateProvider?.getState() ?: _treeState } override fun loadState(state: TreeState) { _treeState = state } fun setStateProvider(provider: BranchesTreeStateProvider) { treeStateProvider = provider } } internal class BranchesTreeStateProvider(tree: FilteringBranchesTree, disposable: Disposable) { private var tree: FilteringBranchesTree? = tree private var state: TreeState? = null init { Disposer.register(disposable) { persistTreeState() this.tree = null } } fun getState(): TreeState? { persistTreeState() return state } private fun persistTreeState() { if (Registry.`is`("git.branches.panel.persist.tree.state")) { tree?.let { state = TreeState.createOn(it.tree, it.root) } } } }
plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesTree.kt
1698469059
// 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.refactoring.safeDelete import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteReferenceSimpleDeleteUsageInfo import org.jetbrains.kotlin.idea.core.deleteElementAndCleanParent import org.jetbrains.kotlin.psi.KtTypeParameter import org.jetbrains.kotlin.psi.KtTypeProjection class SafeDeleteTypeArgumentListUsageInfo( typeProjection: KtTypeProjection, parameter: KtTypeParameter ) : SafeDeleteReferenceSimpleDeleteUsageInfo(typeProjection, parameter, true) { override fun deleteElement() { element?.deleteElementAndCleanParent() } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteTypeArgumentListUsageInfo.kt
30723225
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.replaceWith import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeInliner.UsageReplacementStrategy import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.CleanupFix import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import com.intellij.openapi.application.runWriteAction import org.jetbrains.kotlin.psi.KtReferenceExpression import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny class DeprecatedSymbolUsageFix( element: KtReferenceExpression, replaceWith: ReplaceWithData ) : DeprecatedSymbolUsageFixBase(element, replaceWith), CleanupFix, HighPriorityAction { override fun getFamilyName() = KotlinBundle.message("replace.deprecated.symbol.usage") override fun getText() = KotlinBundle.message("replace.with.0", replaceWith.pattern) override fun invoke(replacementStrategy: UsageReplacementStrategy, project: Project, editor: Editor?) { val element = element ?: return val replacer = replacementStrategy.createReplacer(element) ?: return val result = replacer() ?: return if (editor != null) { val offset = (result.getCalleeExpressionIfAny() ?: result).textOffset editor.moveCaret(offset) } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val (referenceExpression, replacement) = extractDataFromDiagnostic(diagnostic, false) ?: return null return DeprecatedSymbolUsageFix(referenceExpression, replacement).takeIf { it.isAvailable } } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/DeprecatedSymbolUsageFix.kt
2721011876
// IS_APPLICABLE: false class A class AFabric { lateinit var instance: A fun init(config: Unit) { instance = A() } } val fabric = AFabric() class V { val a: A<caret> constructor() { val config = getConfig() fabric.init(config) a = fabric.instance } fun getConfig() = Unit }
plugins/kotlin/idea/tests/testData/intentions/joinDeclarationAndAssignment/notFirstSecondaryConstructorLine.kt
3901648976
// 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 org.jetbrains.plugins.gradle.dsl import com.android.tools.idea.gradle.dsl.api.repositories.RepositoryModel.RepositoryType import java.net.URI enum class RepositoriesWithShorthandMethods( val methodName: String, val dslRepositoryType: RepositoryType, val repositoryId: String? = null, val urls: Set<URI> ) { JCENTER(methodName = "jcenter", dslRepositoryType = RepositoryType.MAVEN, urls = setOf(URI.create("https://jcenter.bintray.com"))), MAVEN_CENTRAL(methodName = "mavenCentral", dslRepositoryType = RepositoryType.MAVEN_CENTRAL, repositoryId = "maven_central", urls = setOf(URI.create("https://repo.maven.apache.org/maven2/"), URI.create("https://repo1.maven.org/maven2"), URI.create("https://maven-central.storage-download.googleapis.com/maven2"))), GOOGLE_MAVEN(methodName = "gmaven", dslRepositoryType = RepositoryType.GOOGLE_DEFAULT, repositoryId = "google", urls = setOf(URI.create("https://maven.google.com"))); companion object { fun findByUrlLenient(url: String): RepositoriesWithShorthandMethods? = values().find { repo -> repo.urls.any { it.isEquivalentLenientTo(url) } } fun findByRepoType(repoType: RepositoryType): RepositoriesWithShorthandMethods? = values().find { repo -> repo.dslRepositoryType == repoType } private fun URI.isEquivalentLenientTo(url: String?): Boolean { if (url == null) return false val otherUriNormalized = URI(url.trim().trimEnd('/', '?', '#')).normalize() val thisUriNormalized = URI(toASCIIString().trim().trimEnd('/', '?', '#')).normalize() return thisUriNormalized == otherUriNormalized } } }
plugins/gradle/gradle-dependency-updater/src/org/jetbrains/plugins/gradle/dsl/RepositoriesWithShorthandMethods.kt
3835850455
class MainTest : junit.framework.TestCase() { fun testFoo() { <warning descr="junit.framework.AssertionFailedError:">assertEquals</warning>() assertEquals() } fun assertEquals() {} }
jvm/jvm-analysis-kotlin-tests/testData/codeInspection/testfailedline/MainTest.kt
3465482267
// 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.bookmark.ui import com.intellij.ide.actions.ToggleToolbarAction.isToolbarVisible import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Splittable import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.openapi.wm.ex.ToolWindowManagerListener import java.util.concurrent.atomic.AtomicBoolean internal class BookmarksViewFactory : DumbAware, ToolWindowFactory, ToolWindowManagerListener { private val orientation = AtomicBoolean(true) override fun createToolWindowContent(project: Project, window: ToolWindow) { val manager = window.contentManager val panel = BookmarksView(project, isToolbarVisible(window, project)).also { it.orientation = orientation.get() } manager.addContent(manager.factory.createContent(panel, null, false).apply { isCloseable = false }) project.messageBus.connect(manager).subscribe(ToolWindowManagerListener.TOPIC, this) window.helpId = "bookmarks.tool.window.help" window.setTitleActions(listOfNotNull(ActionUtil.getAction("Bookmarks.ToolWindow.TitleActions"))) if (window is ToolWindowEx) window.setAdditionalGearActions(ActionUtil.getActionGroup("Bookmarks.ToolWindow.GearActions")) } override fun stateChanged(manager: ToolWindowManager) { val window = manager.getToolWindow(ToolWindowId.BOOKMARKS) ?: return if (window.isDisposed) return val vertical = !window.anchor.isHorizontal if (vertical != orientation.getAndSet(vertical)) { for (content in window.contentManager.contents) { val splittable = content?.component as? Splittable splittable?.orientation = vertical } } } }
platform/lang-impl/src/com/intellij/ide/bookmark/ui/BookmarksViewFactory.kt
2577867077
package test public interface NullableToNotNull { public interface Super { public fun foo(p0: String?) public fun dummy() // to avoid loading as SAM interface } public interface Sub: Super { override fun foo(p0: String?) } }
plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/fromLoadJava/kotlinSignature/propagation/parameter/NullableToNotNull.kt
3438403915
// API_VERSION: 1.3 // WITH_STDLIB val x = listOf("a" to 1, "c" to 3, "b" to 2).<caret>sortedBy { it.second }.firstOrNull()
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/sortedByFirstOrNull.kt
2886686739
fun KotlinInterface.test() { this("") }
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/members/interfaceDefault/invoke/Implicit.kt
3964206330
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.SmartPsiElementPointer import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.refactoring.getThisLabelName import org.jetbrains.kotlin.idea.refactoring.rename.KotlinVariableInplaceRenameHandler import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.getReceiverTargetDescriptor import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getOrCreateParameterList import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingContext.FUNCTION import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.resolve.scopes.utils.collectDescriptorsFiltered import org.jetbrains.kotlin.resolve.scopes.utils.findVariable import org.jetbrains.kotlin.types.KotlinType private val counterpartNames = mapOf( "apply" to "also", "run" to "let", "also" to "apply", "let" to "run" ) class ScopeFunctionConversionInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return callExpressionVisitor { expression -> val counterpartName = getCounterpart(expression) if (counterpartName != null) { holder.registerProblem( expression.calleeExpression!!, KotlinBundle.message("call.is.replaceable.with.another.scope.function"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, if (counterpartName == "also" || counterpartName == "let") ConvertScopeFunctionToParameter(counterpartName) else ConvertScopeFunctionToReceiver(counterpartName) ) } } } } private fun getCounterpart(expression: KtCallExpression): String? { val callee = expression.calleeExpression as? KtNameReferenceExpression ?: return null val calleeName = callee.getReferencedName() val counterpartName = counterpartNames[calleeName] val lambdaExpression = expression.lambdaArguments.singleOrNull()?.getLambdaExpression() if (counterpartName != null && lambdaExpression != null) { if (lambdaExpression.valueParameters.isNotEmpty()) { return null } val bindingContext = callee.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val resolvedCall = callee.getResolvedCall(bindingContext) ?: return null val descriptor = resolvedCall.resultingDescriptor if (descriptor.dispatchReceiverParameter == null && descriptor.extensionReceiverParameter == null) return null if (descriptor.fqNameSafe.asString() == "kotlin.$calleeName" && nameResolvesToStdlib(expression, bindingContext, counterpartName)) { return counterpartName } } return null } private fun nameResolvesToStdlib(expression: KtCallExpression, bindingContext: BindingContext, name: String): Boolean { val scope = expression.getResolutionScope(bindingContext) ?: return true val descriptors = scope.collectDescriptorsFiltered(nameFilter = { it.asString() == name }) return descriptors.isNotEmpty() && descriptors.all { it.fqNameSafe.asString() == "kotlin.$name" } } class Replacement<T : PsiElement> private constructor( private val elementPointer: SmartPsiElementPointer<T>, private val replacementFactory: KtPsiFactory.(T) -> PsiElement ) { companion object { fun <T : PsiElement> create(element: T, replacementFactory: KtPsiFactory.(T) -> PsiElement): Replacement<T> { return Replacement(element.createSmartPointer(), replacementFactory) } } fun apply(factory: KtPsiFactory) { elementPointer.element?.let { it.replace(factory.replacementFactory(it)) } } val endOffset get() = elementPointer.element!!.endOffset } class ReplacementCollection(private val project: Project) { private val replacements = mutableListOf<Replacement<out PsiElement>>() var createParameter: KtPsiFactory.() -> PsiElement? = { null } var elementToRename: PsiElement? = null fun <T : PsiElement> add(element: T, replacementFactory: KtPsiFactory.(T) -> PsiElement) { replacements.add(Replacement.create(element, replacementFactory)) } fun apply() { val factory = KtPsiFactory(project) elementToRename = factory.createParameter() // Calls need to be processed in outside-in order replacements.sortBy { it.endOffset } for (replacement in replacements) { replacement.apply(factory) } } fun isNotEmpty() = replacements.isNotEmpty() } abstract class ConvertScopeFunctionFix(private val counterpartName: String) : LocalQuickFix { override fun getFamilyName() = KotlinBundle.message("convert.scope.function.fix.family.name", counterpartName) override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) { val callee = problemDescriptor.psiElement as KtNameReferenceExpression val callExpression = callee.parent as? KtCallExpression ?: return val bindingContext = callExpression.analyze() val lambda = callExpression.lambdaArguments.firstOrNull() ?: return val functionLiteral = lambda.getLambdaExpression()?.functionLiteral ?: return val lambdaDescriptor = bindingContext[FUNCTION, functionLiteral] ?: return functionLiteral.valueParameterList?.delete() functionLiteral.arrow?.delete() val replacements = ReplacementCollection(project) analyzeLambda(bindingContext, lambda, lambdaDescriptor, replacements) callee.replace(KtPsiFactory(project).createExpression(counterpartName) as KtNameReferenceExpression) replacements.apply() postprocessLambda(lambda) if (replacements.isNotEmpty() && replacements.elementToRename != null && !isUnitTestMode()) { replacements.elementToRename!!.startInPlaceRename() } } protected abstract fun postprocessLambda(lambda: KtLambdaArgument) protected abstract fun analyzeLambda( bindingContext: BindingContext, lambda: KtLambdaArgument, lambdaDescriptor: SimpleFunctionDescriptor, replacements: ReplacementCollection ) } class ConvertScopeFunctionToParameter(counterpartName: String) : ConvertScopeFunctionFix(counterpartName) { override fun analyzeLambda( bindingContext: BindingContext, lambda: KtLambdaArgument, lambdaDescriptor: SimpleFunctionDescriptor, replacements: ReplacementCollection ) { val project = lambda.project val factory = KtPsiFactory(project) val functionLiteral = lambda.getLambdaExpression()?.functionLiteral val lambdaExtensionReceiver = lambdaDescriptor.extensionReceiverParameter val lambdaDispatchReceiver = lambdaDescriptor.dispatchReceiverParameter var parameterName = "it" val scopes = mutableSetOf<LexicalScope>() if (functionLiteral != null && needUniqueNameForParameter(lambda, scopes)) { val parameterType = lambdaExtensionReceiver?.type ?: lambdaDispatchReceiver?.type parameterName = findUniqueParameterName(parameterType, scopes) replacements.createParameter = { val lambdaParameterList = functionLiteral.getOrCreateParameterList() val parameterToAdd = createLambdaParameterList(parameterName).parameters.first() lambdaParameterList.addParameterBefore(parameterToAdd, lambdaParameterList.parameters.firstOrNull()) } } lambda.accept(object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { super.visitSimpleNameExpression(expression) if (expression is KtOperationReferenceExpression) return val resolvedCall = expression.getResolvedCall(bindingContext) ?: return val dispatchReceiverTarget = resolvedCall.dispatchReceiver?.getReceiverTargetDescriptor(bindingContext) val extensionReceiverTarget = resolvedCall.extensionReceiver?.getReceiverTargetDescriptor(bindingContext) if (dispatchReceiverTarget == lambdaDescriptor || extensionReceiverTarget == lambdaDescriptor) { val parent = expression.parent if (parent is KtCallExpression && expression == parent.calleeExpression) { if ((parent.parent as? KtQualifiedExpression)?.receiverExpression !is KtThisExpression) { replacements.add(parent) { element -> factory.createExpressionByPattern("$0.$1", parameterName, element) } } } else if (parent is KtQualifiedExpression && parent.receiverExpression is KtThisExpression) { // do nothing } else { val referencedName = expression.getReferencedName() replacements.add(expression) { createExpression("$parameterName.$referencedName") } } } } override fun visitThisExpression(expression: KtThisExpression) { val resolvedCall = expression.getResolvedCall(bindingContext) ?: return if (resolvedCall.resultingDescriptor == lambdaDispatchReceiver || resolvedCall.resultingDescriptor == lambdaExtensionReceiver ) { replacements.add(expression) { createExpression(parameterName) } } } }) } override fun postprocessLambda(lambda: KtLambdaArgument) { val filter = { element: PsiElement -> if (element is KtThisExpression && element.getLabelName() != null) ShortenReferences.FilterResult.PROCESS else ShortenReferences.FilterResult.GO_INSIDE } ShortenReferences{ ShortenReferences.Options(removeThisLabels = true) }.process(lambda, filter) } private fun needUniqueNameForParameter( lambdaArgument: KtLambdaArgument, scopes: MutableSet<LexicalScope> ): Boolean { val resolutionScope = lambdaArgument.getResolutionScope() scopes.add(resolutionScope) var needUniqueName = false if (resolutionScope.findVariable(Name.identifier("it"), NoLookupLocation.FROM_IDE) != null) { needUniqueName = true // Don't return here - we still need to gather the list of nested scopes } lambdaArgument.accept(object : KtTreeVisitorVoid() { override fun visitDeclaration(dcl: KtDeclaration) { super.visitDeclaration(dcl) checkNeedUniqueName(dcl) } override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) { super.visitLambdaExpression(lambdaExpression) lambdaExpression.bodyExpression?.statements?.firstOrNull()?.let { checkNeedUniqueName(it) } } private fun checkNeedUniqueName(dcl: KtElement) { val nestedResolutionScope = dcl.getResolutionScope() scopes.add(nestedResolutionScope) if (nestedResolutionScope.findVariable(Name.identifier("it"), NoLookupLocation.FROM_IDE) != null) { needUniqueName = true } } }) return needUniqueName } private fun findUniqueParameterName( parameterType: KotlinType?, resolutionScopes: Collection<LexicalScope> ): String { fun isNameUnique(parameterName: String): Boolean { return resolutionScopes.none { it.findVariable(Name.identifier(parameterName), NoLookupLocation.FROM_IDE) != null } } return if (parameterType != null) KotlinNameSuggester.suggestNamesByType(parameterType, ::isNameUnique).first() else { KotlinNameSuggester.suggestNameByName("p", ::isNameUnique) } } } class ConvertScopeFunctionToReceiver(counterpartName: String) : ConvertScopeFunctionFix(counterpartName) { override fun analyzeLambda( bindingContext: BindingContext, lambda: KtLambdaArgument, lambdaDescriptor: SimpleFunctionDescriptor, replacements: ReplacementCollection ) { lambda.accept(object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { super.visitSimpleNameExpression(expression) if (expression.getReferencedName() == "it") { val result = expression.resolveMainReferenceToDescriptors().singleOrNull() if (result is ValueParameterDescriptor && result.containingDeclaration == lambdaDescriptor) { replacements.add(expression) { createThisExpression() } } } else { val resolvedCall = expression.getResolvedCall(bindingContext) ?: return val dispatchReceiver = resolvedCall.dispatchReceiver if (dispatchReceiver is ImplicitReceiver) { val parent = expression.parent val thisLabelName = dispatchReceiver.declarationDescriptor.getThisLabelName() if (parent is KtCallExpression && expression == parent.calleeExpression) { replacements.add(parent) { element -> createExpressionByPattern("this@$0.$1", thisLabelName, element) } } else { val referencedName = expression.getReferencedName() replacements.add(expression) { createExpression("this@$thisLabelName.$referencedName") } } } } } override fun visitThisExpression(expression: KtThisExpression) { val resolvedCall = expression.getResolvedCall(bindingContext) ?: return val qualifierName = resolvedCall.resultingDescriptor.containingDeclaration.name replacements.add(expression) { createThisExpression(qualifierName.asString()) } } }) } override fun postprocessLambda(lambda: KtLambdaArgument) { val filter = { element: PsiElement -> if (element is KtThisExpression && element.getLabelName() != null) ShortenReferences.FilterResult.PROCESS else if (element is KtQualifiedExpression && element.receiverExpression is KtThisExpression) ShortenReferences.FilterResult.PROCESS else ShortenReferences.FilterResult.GO_INSIDE } ShortenReferences { ShortenReferences.Options(removeThis = true, removeThisLabels = true) }.process(lambda, filter) } } private fun PsiElement.startInPlaceRename() { val project = project val document = containingFile.viewProvider.document ?: return val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return if (editor.document == document) { PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) editor.caretModel.moveToOffset(startOffset) KotlinVariableInplaceRenameHandler().doRename(this, editor, null) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ScopeFunctionConversionInspection.kt
315400984
// 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.ui.cloneDialog import com.intellij.ui.SimpleTextAttributes import org.jetbrains.annotations.Nls import java.awt.event.ActionListener data class VcsCloneDialogExtensionStatusLine(@Nls val text: String, val attribute: SimpleTextAttributes, val actionListener: ActionListener? = null) { companion object { fun greyText(@Nls text: String): VcsCloneDialogExtensionStatusLine { return VcsCloneDialogExtensionStatusLine(text, SimpleTextAttributes.GRAY_ATTRIBUTES) } } }
platform/vcs-api/src/com/intellij/openapi/vcs/ui/cloneDialog/VcsCloneDialogExtensionStatusLine.kt
2823541596
// PROBLEM: none class Foo { override fun <caret>equals(other: Any?): Boolean { return true } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/covariantEquals/overrideAnyEquals.kt
3472680693
// "Add parameter to function 'foo'" "true" // DISABLE-ERRORS fun foo(x: Int) { foo(); foo(1); foo(1, 4<caret>); foo(2, 3, sdsd); }
plugins/kotlin/idea/tests/testData/quickfix/changeSignature/addFunctionParameter.kt
3749592671
/* * 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.notebooks.visualization.r.inlays.components import com.intellij.util.ui.ImageUtil import java.awt.Color import java.awt.GraphicsConfiguration import java.awt.image.BufferedImage import java.awt.image.IndexColorModel import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import javax.imageio.ImageIO import kotlin.math.max import kotlin.math.min class ImageInverter(foreground: Color, background: Color, private val graphicsConfiguration: GraphicsConfiguration? = null) { private val rgb = FloatArray(3) private val hsl = FloatArray(3) private val whiteHsl = FloatArray(3) private val blackHsl = FloatArray(3) init { foreground.getRGBColorComponents(rgb) convertRGBtoHSL(rgb, whiteHsl) background.getRGBColorComponents(rgb) convertRGBtoHSL(rgb, blackHsl) } /** * Check if [image] should be inverted in dark themes. * * @param brightnessThreshold images with average brightness exceeding the threshold will be recommended for inversion * * @return true if it's recommended to invert the image */ fun shouldInvert(image: BufferedImage, brightnessThreshold: Double = 0.7): Boolean { val colors = getImageSample(image) val numberOfColorsInComplexImage = 5000 val numberOfPixels = colors.size val numberOfColorsThreshold = min(numberOfPixels / 3, numberOfColorsInComplexImage) val hasAlpha = image.colorModel.hasAlpha() val averageBrightness = colors.map { getBrightness(it, hasAlpha) }.sum() / numberOfPixels val numberOfColors = colors.toSet() return (averageBrightness > brightnessThreshold && numberOfColors.size < numberOfColorsThreshold) || hasLightBackground(colors, hasAlpha, brightnessThreshold) == true } /** * Get part of image for color analysis. * * For narrow/low images all image pixels are returned. * For regular images the result is a concatenation of areas in image corners and at the central area. */ private fun getImageSample(image: BufferedImage): IntArray { if (image.height < 10 || image.width < 10) { val colors = IntArray(image.height * image.width) image.getRGB(0, 0, image.width, image.height, colors, 0, image.width) return colors } val defaultSpotSize = min(max(image.height / 10, image.width / 10), min(image.height, image.width)) val spotHeight = min(image.height, defaultSpotSize) val spotWidth = min(image.width, defaultSpotSize) val spotSize = spotHeight * spotWidth val colors = IntArray(spotSize * 5) image.getRGB(0, 0, spotWidth, spotHeight, colors, 0, spotWidth) image.getRGB(image.width - spotWidth, 0, spotWidth, spotHeight, colors, spotSize, spotWidth) image.getRGB(0, image.height - spotHeight, spotWidth, spotHeight, colors, 2 * spotSize, spotWidth) image.getRGB(image.width - spotWidth, image.height - spotHeight, spotWidth, spotHeight, colors, 3 * spotSize, spotWidth) // We operate on integers so dividing and multiplication with the same number is not trivial operation val centralSpotX = image.width / spotWidth / 2 * spotWidth val centralSpotY = image.height / spotHeight / 2 * spotHeight image.getRGB(centralSpotX, centralSpotY, spotWidth, spotHeight, colors, 4 * spotSize, spotWidth) return colors } private fun getBrightness(argb: Int, hasAlpha: Boolean): Float { val color = Color(argb, hasAlpha) val hsb = FloatArray(3) Color.RGBtoHSB(color.red, color.green, color.blue, hsb) return hsb[2] } /** * Try to guess whether the image has light background. * * The background is defined as a large fraction of pixels with the same color. */ private fun hasLightBackground(colors: IntArray, hasAlpha: Boolean, brightnessThreshold: Double): Boolean? { val dominantColorPair = colors.groupBy { it }.maxByOrNull { it.value.size } ?: return null val dominantColor = dominantColorPair.key val dominantPixels = dominantColorPair.value return dominantPixels.size.toDouble() / colors.size > 0.5 && getBrightness(dominantColor, hasAlpha) > brightnessThreshold } fun invert(color: Color): Color { val alpha = invert(color.rgb) val argb = convertHSLtoRGB(hsl, alpha) return Color(argb, true) } fun invert(image: BufferedImage): BufferedImage { val width = ImageUtil.getUserWidth(image) val height = ImageUtil.getUserHeight(image) return ImageUtil.createImage(width, height, BufferedImage.TYPE_INT_ARGB).also { outputImage -> invertInPlace(image, outputImage) } } fun invert(content: ByteArray): ByteArray { val image = ImageIO.read(ByteArrayInputStream(content)) ?: return content val outputImage = createImageWithInvertedPalette(image) invertInPlace(image, outputImage) return ByteArrayOutputStream().use { outputStream -> ImageIO.write(outputImage, "png", outputStream) outputStream.flush() outputStream.toByteArray() } } private fun invertInPlace(image: BufferedImage, outputImage: BufferedImage) { val rgbArray = image.getRGB(0, 0, image.width, image.height, null, 0, image.width) if (rgbArray.isEmpty()) return // Usually graph data contains regions with same color. Previous converted color may be reused. var prevArgb = rgbArray[0] var prevConverted = convertHSLtoRGB(hsl, invert(prevArgb)) for (i in rgbArray.indices) { val argb = rgbArray[i] if (argb != prevArgb) { prevArgb = argb prevConverted = convertHSLtoRGB(hsl, invert(argb)) } rgbArray[i] = prevConverted } outputImage.setRGB(0, 0, image.width, image.height, rgbArray, 0, image.width) } private fun createImageWithInvertedPalette(image: BufferedImage): BufferedImage { val model = image.colorModel if (model !is IndexColorModel) { return image } val palette = IntArray(model.mapSize) model.getRGBs(palette) for ((index, argb) in palette.withIndex()) { val alpha = invert(argb) palette[index] = convertHSLtoRGB(hsl, alpha) } return ImageUtil.createImage(graphicsConfiguration, image.width, image.height, BufferedImage.TYPE_BYTE_INDEXED) } // Note: returns alpha, resulting color resides in `hsl` private fun invert(argb: Int): Float { val alpha = ((argb shr 24) and 255) / 255f rgb[R] = ((argb shr 16) and 255) / 255f rgb[G] = ((argb shr 8) and 255) / 255f rgb[B] = ((argb) and 255) / 255f convertRGBtoHSL(rgb, hsl) hsl[SATURATION] = hsl[SATURATION] * (50.0f + whiteHsl[SATURATION]) / 1.5f / 100f hsl[LUMINANCE] = (100 - hsl[LUMINANCE]) * (whiteHsl[LUMINANCE] - blackHsl[LUMINANCE]) / 100f + blackHsl[LUMINANCE] return alpha } companion object { private const val SATURATION = 1 private const val LUMINANCE = 2 private const val R = 0 private const val G = 1 private const val B = 2 } }
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/components/ImageInverter.kt
3557757534