content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.accompanist.swiperefresh import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.pow /** * A utility function that calculates various aspects of 'slingshot' behavior. * Adapted from SwipeRefreshLayout#moveSpinner method. * * TODO: Investigate replacing this with a spring. * * @param offsetY The current y offset. * @param maxOffsetY The max y offset. * @param height The height of the item to slingshot. */ @Composable internal fun rememberUpdatedSlingshot( offsetY: Float, maxOffsetY: Float, height: Int ): Slingshot { val offsetPercent = min(1f, offsetY / maxOffsetY) val adjustedPercent = max(offsetPercent - 0.4f, 0f) * 5 / 3 val extraOffset = abs(offsetY) - maxOffsetY // Can accommodate custom start and slingshot distance here val slingshotDistance = maxOffsetY val tensionSlingshotPercent = max( 0f, min(extraOffset, slingshotDistance * 2) / slingshotDistance ) val tensionPercent = ( (tensionSlingshotPercent / 4) - (tensionSlingshotPercent / 4).pow(2) ) * 2 val extraMove = slingshotDistance * tensionPercent * 2 val targetY = height + ((slingshotDistance * offsetPercent) + extraMove).toInt() val offset = targetY - height val strokeStart = adjustedPercent * 0.8f val startTrim = 0f val endTrim = strokeStart.coerceAtMost(MaxProgressArc) val rotation = (-0.25f + 0.4f * adjustedPercent + tensionPercent * 2) * 0.5f val arrowScale = min(1f, adjustedPercent) return remember { Slingshot() }.apply { this.offset = offset this.startTrim = startTrim this.endTrim = endTrim this.rotation = rotation this.arrowScale = arrowScale } } @Stable internal class Slingshot { var offset: Int by mutableStateOf(0) var startTrim: Float by mutableStateOf(0f) var endTrim: Float by mutableStateOf(0f) var rotation: Float by mutableStateOf(0f) var arrowScale: Float by mutableStateOf(0f) } internal const val MaxProgressArc = 0.8f
swiperefresh/src/main/java/com/google/accompanist/swiperefresh/Slingshot.kt
2219777560
package lt.markmerkk.widgets.network import okhttp3.ResponseBody import retrofit2.http.* import rx.Single interface Api { @GET("master/CHANGELOG.md") fun changelog(): Single<ResponseBody> }
app/src/main/java/lt/markmerkk/widgets/network/Api.kt
3462279411
package lt.markmerkk /** * Thin layer to get the available view * Ex.1 Useful when presenter is initialized, when view is not available yet * The view is passed through lambda, thus functions only trigger when view is available */ abstract class ViewProvider<T> { abstract fun get(): T? /** * It is easy to get the view from Kotlin and do a null check. * This is not the case on Java. * This convenience function will trigger function *only when view is available* */ fun invoke(block: T.() -> Unit) { val view: T? = get() if (view != null) { block.invoke(view) } } /** * More java-like lambda consumable function * Successor of [invoke] */ fun invokeJ(block: OnViewAvailableListener<T>) { val view: T? = get() if (view != null) { block.invokeOnView(view) } } } class ViewProviderEmpty<T> : ViewProvider<T>() { override fun get(): T? = null } @FunctionalInterface interface OnViewAvailableListener<T> { fun invokeOnView(view: T) }
components/src/main/java/lt/markmerkk/ViewProvider.kt
896707497
//TODO: seems to corespond to datatype token_node in pats_lexing.sats, // a more stable solution might be to generate this from the ATS compiler source, // in theory the lexer could be implemented that way // now that abstract datatypes are finally a thing in Java land //TODO: these Int's are likely infinite precision, //TODO: handle the "bad char" // TODO: transpose the comments into "javadoc" style comments package com.atslangplugin.experimantal import com.atslangplugin.ATSLanguage import com.intellij.psi.tree.IElementType import org.jetbrains.annotations.NonNls //TODO: object //from pats_basics.sats sealed class Fxtykind { class FXK_infix() : Fxtykind() class FXK_infixl() : Fxtykind() class FXK_infixr() : Fxtykind() class FXK_prefix() : Fxtykind() class FXK_postfix() : Fxtykind() } sealed class Caskind { /** case */ class CK_case() : Caskind() /** case+ */ class CK_case_pos : Caskind() /** case- */ class CK_case_neg : Caskind() } sealed class Funkind { //TODO: javadoc // nonrec fun class FK_fn() : Funkind() // tailrec fun class FK_fnx() : Funkind() // recursive fun class FK_fun() : Funkind() // nonrec proof fun class FK_prfn() : Funkind() // recursive proof fun class FK_prfun() : Funkind() // proof axiom class FK_praxi() : Funkind() // casting fun class FK_castfn() : Funkind() } //TODO: rename to be consistent with sata sealed class ATSTokenType(@NonNls debugName: String) : IElementType(debugName, ATSLanguage) { //TODO: needed? override fun toString(): String { return "ATSTokenType." + super.toString() } /** // dummy */ class T_NONE() : ATSTokenType("T_NONE") /** // @ */ class T_AT() : ATSTokenType("T_AT") /** // | */ class T_BAR() : ATSTokenType("T_BAR") /** // ! */ class T_BANG() : ATSTokenType("T_BANG") /** // ` */ class T_BQUOTE() : ATSTokenType("T_BQUOTE") /** // \ */ class T_BACKSLASH() : ATSTokenType("T_BACKSLASH") /** // : */ class T_COLON() : ATSTokenType("T_COLON") /** // :< */ class T_COLONLT() : ATSTokenType("T_COLONLT") /** // $ */ class T_DOLLAR() : ATSTokenType("T_DOLLAR") /** // . */ class T_DOT() : ATSTokenType("T_DOT") /** // .. */ class T_DOTDOT() : ATSTokenType("T_DOTDOT") /** // ... */ class T_DOTDOTDOT() : ATSTokenType("T_DOTDOTDOT") /** .[0-9]+ */ class T_DOTINT(val i: Int) : ATSTokenType("T_DOTINT") /** // = */ class T_EQ() : ATSTokenType("T_EQ") /** // => */ class T_EQGT() : ATSTokenType("T_EQGT") /** // =< */ class T_EQLT() : ATSTokenType("T_EQLT") /** // =<> */ class T_EQLTGT() : ATSTokenType("T_EQLTGT") /** // =/=> */ class T_EQSLASHEQGT() : ATSTokenType("T_EQSLASHEQGT") /** // =>> */ class T_EQGTGT() : ATSTokenType("T_EQGTGT") /** // =/=>> */ class T_EQSLASHEQGTGT() : ATSTokenType("T_EQSLASHEQGTGT") /** // # */ class T_HASH() : ATSTokenType("T_HASH") /** // < // for opening a tmparg */ class T_LT() : ATSTokenType("T_LT") /** // > // for closing a tmparg */ class T_GT() : ATSTokenType("T_GT") /** // <> */ class T_GTLT() : ATSTokenType("T_GTLT") /** // .< // opening termetric */ class T_DOTLT() : ATSTokenType("T_DOTLT") /** // >. // closing termetric */ class T_GTDOT() : ATSTokenType("T_GTDOT") /** // .<>. // for empty termetric */ class T_DOTLTGTDOT() : ATSTokenType("T_DOTLTGTDOT") /** // -> */ class T_MINUSGT() : ATSTokenType("T_MINUSGT") /** // -< */ class T_MINUSLT() : ATSTokenType("T_MINUSLT") /** // -<> */ class T_MINUSLTGT() : ATSTokenType("T_MINUSLTGT") /** // ~ // often for 'not', 'free', etc. */ class T_TILDE() : ATSTokenType("T_TILDE") // HX: for absprop, abstype, abst@ype; /** absview, absvtype, absvt@ype*/ class T_ABSTYPE(val i: Int) : ATSTokenType("T_ABSTYPE") /** // for implementing abstypes */ class T_ASSUME() : ATSTokenType("T_ASSUME") /** // for re-assuming abstypes */ class T_REASSUME() : ATSTokenType("T_REASSUME") /** // as // for refas-pattern */ class T_AS() : ATSTokenType("T_AS") /** // and */ class T_AND() : ATSTokenType("T_AND") /** // begin // initiating a sequence */ class T_BEGIN() : ATSTokenType("T_BEGIN") /** case, case-, case+, prcase */ class T_CASE(val caskind: Caskind) : ATSTokenType("T_CASE") /** // classdec */ class T_CLASSDEC() : ATSTokenType("T_CLASSDEC") /** // datasort */ class T_DATASORT() : ATSTokenType("T_DATASORT") /** datatype, dataprop, dataview, dataviewtype */ class T_DATATYPE(val i: Int) : ATSTokenType("T_DATATYPE") /** // [do] */ class T_DO() : ATSTokenType("T_DO") /** // [else] */ class T_ELSE() : ATSTokenType("T_ELSE") /** // the [end] keyword */ class T_END() : ATSTokenType("T_END") /** // [exception] */ class T_EXCEPTION() : ATSTokenType("T_EXCEPTION") /** // extern */ class T_EXTERN() : ATSTokenType("T_EXTERN") /** // externally named type */ class T_EXTYPE() : ATSTokenType("T_EXTYPE") /** // externally named variable */ class T_EXTVAR() : ATSTokenType("T_EXTVAR") /** fix and fix@ */ class T_FIX(val i: Int) : ATSTokenType("T_FIX") /** infix, infixl, infixr, prefix, postfix */ class T_FIXITY(fxtykind: Fxtykind) : ATSTokenType("T_FIXITY") /** // for */ class T_FOR() : ATSTokenType("T_FOR") /** // for* */ class T_FORSTAR() : ATSTokenType("T_FORSTAR") /** fn, fnx, fun, prfn and prfun */ class T_FUN(valfunkind: Funkind) : ATSTokenType("T_FUN") /** // (dynamic) if */ class T_IF() : ATSTokenType("T_IF") /** // (dynamic) ifcase */ class T_IFCASE() : ATSTokenType("T_IFCASE") /** */ class T_IMPLEMENT(val i: Int) // 0/1/2: implmnt/implement/primplmnt :ATSTokenType("T_IMPLEMENT") /** // import (for packages) */ class T_IMPORT() : ATSTokenType("T_IMPORT") /** // in */ class T_IN() : ATSTokenType("T_IN") /** lam, llam (linear lam) and lam@ (flat lam) */ class T_LAM(val i: Int) : ATSTokenType("T_LAM") /** // let */ class T_LET() : ATSTokenType("T_LET") /** // local */ class T_LOCAL() : ATSTokenType("T_LOCAL") /** 0/1: macdef/macrodef */ class T_MACDEF(val i: Int) : ATSTokenType("T_MACDEF") /** // nonfix */ class T_NONFIX() : ATSTokenType("T_NONFIX") /** // overload */ class T_OVERLOAD() : ATSTokenType("T_OVERLOAD") /** // of */ class T_OF() : ATSTokenType("T_OF") /** // op // HX: taken from ML */ class T_OP() : ATSTokenType("T_OP") /** // rec */ class T_REC() : ATSTokenType("T_REC") /** // static if */ class T_SIF() : ATSTokenType("T_SIF") /** // static case */ class T_SCASE() : ATSTokenType("T_SCASE") /** // stacst */ class T_STACST() : ATSTokenType("T_STACST") /** // stadef */ class T_STADEF() : ATSTokenType("T_STADEF") /** // static */ class T_STATIC() : ATSTokenType("T_STATIC") /** // sortdef */ class T_SORTDEF() : ATSTokenType("T_SORTDEF") /** // symelim // symbol elimination */ class T_SYMELIM() : ATSTokenType("T_SYMELIM") /** // symintr // symbol introduction */ class T_SYMINTR() : ATSTokenType("T_SYMINTR") /** // the [then] keyword */ class T_THEN() : ATSTokenType("T_THEN") /** // tkindef // for introducting tkinds */ class T_TKINDEF() : ATSTokenType("T_TKINDEF") /** // try */ class T_TRY() : ATSTokenType("T_TRY") /** type, type+, type- */ class T_TYPE(val i: Int) : ATSTokenType("T_TYPE") /** typedef, propdef, viewdef, viewtypedef */ class T_TYPEDEF(val i: Int) : ATSTokenType("T_TYPEDEF") //TODO: and so on... // /** val, val+, val-, prval */ // class T_VAL(valkind) : ATSTokenType("T_VAL") // // //TODO:Mark: why not bool? // /** knd = 0/1: var/prvar*/ // class T_VAR(val knd: Int) : ATSTokenType("T_VAR") // // /** // when */ // class T_WHEN() : ATSTokenType("T_WHEN") // // /** // where */ // class T_WHERE() : ATSTokenType("T_WHERE") // // /** // while */ // class T_WHILE() : ATSTokenType("T_WHILE") // // /** // while* */ // class T_WHILESTAR() : ATSTokenType("T_WHILESTAR") // // /** // with */ // class T_WITH() : ATSTokenType("T_WITH") // // /** */ // class T_WITHTYPE(int) // withtype, withprop, withview, withviewtype :ATSTokenType("T_WITHTYPE") // // end of [T_WITHTYPE] // HX: it is from DML and now rarely used // // /** // addr@ */ // class T_ADDRAT() : ATSTokenType("T_ADDRAT") // // /** // fold@ */ // class T_FOLDAT() : ATSTokenType("T_FOLDAT") // // /** // free@ */ // class T_FREEAT() : ATSTokenType("T_FREEAT") // // /** // view@ */ // class T_VIEWAT() : ATSTokenType("T_VIEWAT") // // /** */ class T_DLRDELAY (int(*lin*)) // $delay/$ldelay :ATSTokenType("T_DLRDELAY") // // /** // $arrpsz/$arrptrsize */ class T_DLRARRPSZ () :ATSTokenType("T_DLRARRPSZ") // // /** // $tyrep(SomeType) */ class T_DLRTYREP () :ATSTokenType("T_DLRTYREP") // /** // $d2ctype(foo/foo<...>) */ class T_DLRD2CTYPE () :ATSTokenType("T_DLRD2CTYPE") // // /** // $effmask */ class T_DLREFFMASK () :ATSTokenType("T_DLREFFMASK") // /** */ class T_DLREFFMASK_ARG (int) // ntm(0), exn(1), ref(2), wrt(3), all(4) :ATSTokenType("T_DLREFFMASK_ARG") // // /** // $extern */ class T_DLREXTERN () :ATSTokenType("T_DLREXTERN") // /** // externally named type */ class T_DLREXTYPE () :ATSTokenType("T_DLREXTYPE") // /** // $extkind */ class T_DLREXTKIND () :ATSTokenType("T_DLREXTKIND") // /** // externally named struct */ class T_DLREXTYPE_STRUCT () :ATSTokenType("T_DLREXTYPE_STRUCT") // // /** // externally named value */ class T_DLREXTVAL () :ATSTokenType("T_DLREXTVAL") // /** // externally named fun-call */ class T_DLREXTFCALL () :ATSTokenType("T_DLREXTFCALL") // /** // externally named method-call */ class T_DLREXTMCALL () :ATSTokenType("T_DLREXTMCALL") // // /** // $literal */ class T_DLRLITERAL () :ATSTokenType("T_DLRLITERAL") // // /** // $myfilename */ class T_DLRMYFILENAME () :ATSTokenType("T_DLRMYFILENAME") // /** // $mylocation */ class T_DLRMYLOCATION () :ATSTokenType("T_DLRMYLOCATION") // /** // $myfunction */ class T_DLRMYFUNCTION () :ATSTokenType("T_DLRMYFUNCTION") // // /** */ class T_DLRLST int // $lst and $lst_t and $lst_vt :ATSTokenType("T_DLRLST") // /** */ class T_DLRREC int // $rec and $rec_t and $rec_vt :ATSTokenType("T_DLRREC") // /** */ class T_DLRTUP int // $tup and $tup_t and $tup_vt :ATSTokenType("T_DLRTUP") // // /** // $break */ class T_DLRBREAK () :ATSTokenType("T_DLRBREAK") // /** // $continue */ class T_DLRCONTINUE () :ATSTokenType("T_DLRCONTINUE") // // /** // $raise // raising exceptions */ class T_DLRRAISE () :ATSTokenType("T_DLRRAISE") // // /** // $showtype // for debugging purpose */ class T_DLRSHOWTYPE () :ATSTokenType("T_DLRSHOWTYPE") // // /** */ class T_DLRVCOPYENV (int) // $vcopyenv_v(v)/$vcopyenv_vt(vt) :ATSTokenType("T_DLRVCOPYENV") // // /** // $tempenver // for adding environvar */ class T_DLRTEMPENVER () :ATSTokenType("T_DLRTEMPENVER") // // /** // $solver_assert // assert(d2e_prf) */ class T_DLRSOLASSERT () :ATSTokenType("T_DLRSOLASSERT") // /** // $solver_verify // verify(s2e_prop) */ class T_DLRSOLVERIFY () :ATSTokenType("T_DLRSOLVERIFY") // // /** // #if */ class T_SRPIF () :ATSTokenType("T_SRPIF") // /** // #ifdef */ class T_SRPIFDEF () :ATSTokenType("T_SRPIFDEF") // /** // #ifndef */ class T_SRPIFNDEF () :ATSTokenType("T_SRPIFNDEF") // // /** // #then */ class T_SRPTHEN () :ATSTokenType("T_SRPTHEN") // // /** // #elif */ class T_SRPELIF () :ATSTokenType("T_SRPELIF") // /** // #elifdef */ class T_SRPELIFDEF () :ATSTokenType("T_SRPELIFDEF") // /** // #elifndef */ class T_SRPELIFNDEF () :ATSTokenType("T_SRPELIFNDEF") // /** // #else */ class T_SRPELSE () :ATSTokenType("T_SRPELSE") // // /** // #endif */ class T_SRPENDIF () :ATSTokenType("T_SRPENDIF") // // /** // #error */ class T_SRPERROR () :ATSTokenType("T_SRPERROR") // /** // #prerr */ class T_SRPPRERR () :ATSTokenType("T_SRPPRERR") // /** // #print */ class T_SRPPRINT () :ATSTokenType("T_SRPPRINT") // // /** // #assert */ class T_SRPASSERT () :ATSTokenType("T_SRPASSERT") // // /** // #undef */ class T_SRPUNDEF () :ATSTokenType("T_SRPUNDEF") // /** // #define */ class T_SRPDEFINE () :ATSTokenType("T_SRPDEFINE") // // /** // #include */ class T_SRPINCLUDE () :ATSTokenType("T_SRPINCLUDE") // // /** // #staload */ class T_SRPSTALOAD () :ATSTokenType("T_SRPSTALOAD") // /** // #dynload */ class T_SRPDYNLOAD () :ATSTokenType("T_SRPDYNLOAD") // // /** // #require */ class T_SRPREQUIRE () :ATSTokenType("T_SRPREQUIRE") // // /** // #pragma */ class T_SRPPRAGMA () :ATSTokenType("T_SRPPRAGMA") // /** // #codegen2 */ class T_SRPCODEGEN2 () :ATSTokenType("T_SRPCODEGEN2") // /** // #codegen3 */ class T_SRPCODEGEN3 () :ATSTokenType("T_SRPCODEGEN3") // // /** */ class T_IDENT_alp string // alnum :ATSTokenType("T_IDENT_alp") // /** */ class T_IDENT_sym string // symbol :ATSTokenType("T_IDENT_sym") // /** */ class T_IDENT_arr string // A[...] :ATSTokenType("T_IDENT_arr") // /** */ class T_IDENT_tmp string // A<...> :ATSTokenType("T_IDENT_tmp") // /** */ class T_IDENT_dlr string // $alnum :ATSTokenType("T_IDENT_dlr") // /** */ class T_IDENT_srp string // #alnum :ATSTokenType("T_IDENT_srp") // /** */ class T_IDENT_ext string // alnum! :ATSTokenType("T_IDENT_ext") // // /** */ class T_INT (int(*base*), string(*rep*), uint(*suffix*)) :ATSTokenType("T_INT") // // /** */ class T_CHAR char (* character *) :ATSTokenType("T_CHAR") // // /** */ class T_FLOAT (int(*base*), string(*rep*), uint(*suffix*)) :ATSTokenType("T_FLOAT") // // /** */ class {n:int} T_CDATA (arrayref(char, n), size_t(n)) // for binaries :ATSTokenType("{n:int} T_CDATA") // /** */ class T_STRING (string) :ATSTokenType("T_STRING") // // /** // , */ class T_COMMA () :ATSTokenType("T_COMMA") // /** // ; */ class T_SEMICOLON () :ATSTokenType("T_SEMICOLON") // // /** // ( */ class T_LPAREN () :ATSTokenType("T_LPAREN") // /** // ) */ class T_RPAREN () :ATSTokenType("T_RPAREN") // /** // [ */ class T_LBRACKET () :ATSTokenType("T_LBRACKET") // /** // ] */ class T_RBRACKET () :ATSTokenType("T_RBRACKET") // /** // { */ class T_LBRACE () :ATSTokenType("T_LBRACE") // /** // } */ class T_RBRACE () :ATSTokenType("T_RBRACE") // // /** */ class T_ATLPAREN () // @( :ATSTokenType("T_ATLPAREN") // /** // '( */ class T_QUOTELPAREN () :ATSTokenType("T_QUOTELPAREN") // /** // @[ */ class T_ATLBRACKET () :ATSTokenType("T_ATLBRACKET") // /** // '[ */ class T_QUOTELBRACKET () :ATSTokenType("T_QUOTELBRACKET") // /** // #[ */ class T_HASHLBRACKET () :ATSTokenType("T_HASHLBRACKET") // /** // @{ */ class T_ATLBRACE () :ATSTokenType("T_ATLBRACE") // /** // '{ */ class T_QUOTELBRACE () :ATSTokenType("T_QUOTELBRACE") // // /** // `( // macro syntax */ class T_BQUOTELPAREN () :ATSTokenType("T_BQUOTELPAREN") // /** */ class T_COMMALPAREN () // ,( // macro syntax :ATSTokenType("T_COMMALPAREN") // /** // %( // macro syntax */ class T_PERCENTLPAREN () :ATSTokenType("T_PERCENTLPAREN") // // /** */ class T_EXTCODE (int(*kind*), string) // external code :ATSTokenType("T_EXTCODE") // // /** // line comment */ class T_COMMENT_line () :ATSTokenType("T_COMMENT_line") // /** // block comment */ class T_COMMENT_block () :ATSTokenType("T_COMMENT_block") // /** // rest-of-file comment */ class T_COMMENT_rest () :ATSTokenType("T_COMMENT_rest") // // /** // for errors */ class T_ERR () :ATSTokenType("T_ERR") // // /** // end-of-file */ class T_EOF () :ATSTokenType("T_EOF") } sealed class CreateSubscriptionResult { /** asd */ class Success(val subscription: Int) : CreateSubscriptionResult() class Failure(val errors: List<String>) : CreateSubscriptionResult() }
src/main/kotlin/com/atslangplugin/experimantal/ATSTokenTypes.kt
1326472989
package com.darrenatherton.droidcommunity.data.reddit.service import android.util.Log import com.darrenatherton.droidcommunity.data.reddit.RedditObject import com.darrenatherton.droidcommunity.data.reddit.RedditObjectWrapper import com.google.gson.* import java.lang.reflect.Type class RedditObjectDeserializer : JsonDeserializer<RedditObject> { val TAG: String = RedditObjectDeserializer::class.java.simpleName override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): RedditObject? { if (!json.isJsonObject) { return null } try { val wrapper: RedditObjectWrapper = Gson().fromJson(json, RedditObjectWrapper::class.java) return context.deserialize(wrapper.data, wrapper.kind.derivedClass) } catch (e: JsonParseException) { Log.e(TAG, "Failed to deserialize", e) return null } } }
app/src/main/kotlin/com/darrenatherton/droidcommunity/data/reddit/service/RedditObjectDeserializer.kt
626930494
/* * Copyright (C) 2020 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.hilt.android.simpleKotlin import javax.inject.Qualifier /** Qualifies bindings relating to [android.os.Build.MODEL]. */ @Qualifier @Retention(AnnotationRetention.RUNTIME) internal annotation class Model
javatests/artifacts/hilt-android/simpleKotlin/app/src/main/java/dagger/hilt/android/simpleKotlin/Model.kt
4288728572
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opencl.templates import org.lwjgl.generator.* import opencl.* val khr_initialize_memory = "KHRInitializeMemory".nativeClassCL("khr_initialize_memory", KHR) { documentation = """ Native bindings to the $extensionName extension. This extension adds support for initializing local and private memory before a kernel begins execution. Memory is allocated in various forms in OpenCL both explicitly (global memory) or implicitly (local, private memory). This allocation so far does not provide a straightforward mechanism to initialize the memory on allocation. In other words what is lacking is the equivalent of calloc for the currently supported malloc like capability. This functionality is useful for a variety of reasons including ease of debugging, application controlled limiting of visibility to previous contents of memory and in some cases, optimization. """ IntConstant( """ Accepted as a property name in the {@code properties} parameter of #CreateContext(). Describes which memory types for the context must be initialized. This is a bit-field, where the following values are currently supported: ${ul( // TODO: Find these values "{@code CL_CONTEXT_MEMORY_INITIALIZE_LOCAL_KHR} &ndash; Initialize local memory to zeros.", "{@code CL_CONTEXT_MEMORY_INITIALIZE_PRIVATE_KHR} &ndash; Initialize private memory to zeros." )} """, "CONTEXT_MEMORY_INITIALIZE_KHR"..0x200E ) }
modules/lwjgl/opencl/src/templates/kotlin/opencl/templates/khr_initialize_memory.kt
3436840434
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.ui.common import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.google.android.ground.MainViewModel import com.google.android.ground.ui.datacollection.DataCollectionViewModel import com.google.android.ground.ui.editsubmission.* import com.google.android.ground.ui.home.HomeScreenViewModel import com.google.android.ground.ui.home.locationofinterestdetails.LocationOfInterestDetailsViewModel import com.google.android.ground.ui.home.locationofinterestdetails.SubmissionListItemViewModel import com.google.android.ground.ui.home.locationofinterestdetails.SubmissionListViewModel import com.google.android.ground.ui.home.locationofinterestselector.LocationOfInterestSelectorViewModel import com.google.android.ground.ui.home.mapcontainer.LocationOfInterestRepositionViewModel import com.google.android.ground.ui.home.mapcontainer.MapContainerViewModel import com.google.android.ground.ui.home.mapcontainer.PolygonDrawingViewModel import com.google.android.ground.ui.offlinebasemap.OfflineAreasViewModel import com.google.android.ground.ui.offlinebasemap.selector.OfflineAreaSelectorViewModel import com.google.android.ground.ui.offlinebasemap.viewer.OfflineAreaViewerViewModel import com.google.android.ground.ui.signin.SignInViewModel import com.google.android.ground.ui.submissiondetails.SubmissionDetailsViewModel import com.google.android.ground.ui.surveyselector.SurveySelectorViewModel import com.google.android.ground.ui.syncstatus.SyncStatusViewModel import com.google.android.ground.ui.tos.TermsOfServiceViewModel import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import dagger.multibindings.IntoMap @InstallIn(SingletonComponent::class) @Module abstract class ViewModelModule { @Binds @IntoMap @ViewModelKey(LocationOfInterestRepositionViewModel::class) abstract fun bindLocationOfInterestRepositionViewModel( viewModel: LocationOfInterestRepositionViewModel ): ViewModel @Binds @IntoMap @ViewModelKey(PolygonDrawingViewModel::class) abstract fun bindPolygonDrawingViewModel(viewModel: PolygonDrawingViewModel): ViewModel @Binds @IntoMap @ViewModelKey(MapContainerViewModel::class) abstract fun bindMapContainerViewModel(viewModel: MapContainerViewModel): ViewModel @Binds @IntoMap @ViewModelKey(OfflineAreaSelectorViewModel::class) abstract fun bindOfflineAreaSelectorViewModel(viewModel: OfflineAreaSelectorViewModel): ViewModel @Binds @IntoMap @ViewModelKey(SyncStatusViewModel::class) abstract fun bindSyncStatusViewModel(viewModel: SyncStatusViewModel): ViewModel @Binds @IntoMap @ViewModelKey(DataCollectionViewModel::class) abstract fun bindDataCollectionViewModel(viewModel: DataCollectionViewModel): ViewModel @Binds @IntoMap @ViewModelKey(OfflineAreasViewModel::class) abstract fun bindOfflineAreasViewModel(viewModel: OfflineAreasViewModel): ViewModel @Binds @IntoMap @ViewModelKey(OfflineAreaViewerViewModel::class) abstract fun bindOfflineAreaViewerViewModel(viewModel: OfflineAreaViewerViewModel): ViewModel @Binds @IntoMap @ViewModelKey(MainViewModel::class) abstract fun bindMainViewModel(viewModel: MainViewModel): ViewModel @Binds @IntoMap @ViewModelKey(SignInViewModel::class) abstract fun bindSignInVideModel(viewModel: SignInViewModel): ViewModel @Binds @IntoMap @ViewModelKey(TermsOfServiceViewModel::class) abstract fun bindTermsViewModel(viewModel: TermsOfServiceViewModel): ViewModel @Binds @IntoMap @ViewModelKey(HomeScreenViewModel::class) abstract fun bindHomeScreenViewModel(viewModel: HomeScreenViewModel): ViewModel @Binds @IntoMap @ViewModelKey(LocationOfInterestDetailsViewModel::class) abstract fun bindLocationOfInterestDetailsViewModel( viewModel: LocationOfInterestDetailsViewModel ): ViewModel @Binds @IntoMap @ViewModelKey(SurveySelectorViewModel::class) abstract fun bindSurveySelectorViewModel(viewModel: SurveySelectorViewModel): ViewModel @Binds @IntoMap @ViewModelKey(SubmissionListItemViewModel::class) abstract fun bindSubmissionListItemViewModel(viewModel: SubmissionListItemViewModel): ViewModel @Binds @IntoMap @ViewModelKey(SubmissionListViewModel::class) abstract fun bindSubmissionListViewModel(viewModel: SubmissionListViewModel): ViewModel @Binds @IntoMap @ViewModelKey(SubmissionDetailsViewModel::class) abstract fun bindSubmissionDetailsViewModel(viewModel: SubmissionDetailsViewModel): ViewModel @Binds @IntoMap @ViewModelKey(EditSubmissionViewModel::class) abstract fun bindEditSubmissionViewModel(viewModel: EditSubmissionViewModel): ViewModel @Binds @IntoMap @ViewModelKey(PhotoTaskViewModel::class) abstract fun bindPhotoTaskViewModel(viewModel: PhotoTaskViewModel): ViewModel @Binds @IntoMap @ViewModelKey(MultipleChoiceTaskViewModel::class) abstract fun bindMultipleChoiceTaskViewModel(viewModel: MultipleChoiceTaskViewModel): ViewModel @Binds @IntoMap @ViewModelKey(TextTaskViewModel::class) abstract fun bindTextTaskViewModel(viewModel: TextTaskViewModel): ViewModel @Binds @IntoMap @ViewModelKey(NumberTaskViewModel::class) abstract fun bindNumberTaskViewModel(viewModel: NumberTaskViewModel): ViewModel @Binds @IntoMap @ViewModelKey(DateTaskViewModel::class) abstract fun bindDateTaskViewModel(viewModel: DateTaskViewModel): ViewModel @Binds @IntoMap @ViewModelKey(TimeTaskViewModel::class) abstract fun bindTimeTaskViewModel(viewModel: TimeTaskViewModel): ViewModel @Binds @IntoMap @ViewModelKey(LocationOfInterestSelectorViewModel::class) abstract fun bindLocationOfInterestSelectorViewModel( viewModel: LocationOfInterestSelectorViewModel ): ViewModel @Binds abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory }
ground/src/main/java/com/google/android/ground/ui/common/ViewModelModule.kt
3090196126
/* * 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.internal import dagger.Reusable import io.reactivex.Observable import javax.inject.Inject import org.hisp.dhis.android.core.arch.call.D2Progress import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance import org.hisp.dhis.android.core.tracker.TrackerPostParentCallHelper import org.hisp.dhis.android.core.tracker.importer.internal.TrackerImporterPostCall @Reusable internal class TrackedEntityInstancePostParentCall @Inject internal constructor( private val oldTrackerImporterCall: OldTrackerImporterPostCall, private val trackerImporterCall: TrackerImporterPostCall, private val trackerParentCallHelper: TrackerPostParentCallHelper ) { fun uploadTrackedEntityInstances(trackedEntityInstances: List<TrackedEntityInstance>): Observable<D2Progress> { return if (trackedEntityInstances.isEmpty()) { Observable.empty<D2Progress>() } else { if (trackerParentCallHelper.useNewTrackerImporter()) { trackerImporterCall.uploadTrackedEntityInstances(trackedEntityInstances) } else { oldTrackerImporterCall.uploadTrackedEntityInstances(trackedEntityInstances) } } } }
core/src/main/java/org/hisp/dhis/android/core/trackedentity/internal/TrackedEntityInstancePostParentCall.kt
2224816540
/* * 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.commands interface Command { fun run() }
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/commands/Command.kt
809029076
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToOneChild import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ParentEntityImpl: ParentEntity, WorkspaceEntityBase() { companion object { internal val CHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentEntity::class.java, ChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) val connections = listOf<ConnectionId>( CHILD_CONNECTION_ID, ) } @JvmField var _parentData: String? = null override val parentData: String get() = _parentData!! override val child: ChildEntity get() = snapshot.extractOneToOneChild(CHILD_CONNECTION_ID, this)!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ParentEntityData?): ModifiableWorkspaceEntityBase<ParentEntity>(), ParentEntity.Builder { constructor(): this(ParentEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ParentEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isParentDataInitialized()) { error("Field ParentEntity#parentData should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field ParentEntity#entitySource should be initialized") } if (_diff != null) { if (_diff.extractOneToOneChild<WorkspaceEntityBase>(CHILD_CONNECTION_ID, this) == null) { error("Field ParentEntity#child should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] == null) { error("Field ParentEntity#child should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } override var parentData: String get() = getEntityData().parentData set(value) { checkModificationAllowed() getEntityData().parentData = value changedProperty.add("parentData") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var child: ChildEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(CHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)]!! as ChildEntity } else { this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)]!! as ChildEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(CHILD_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] = value } changedProperty.add("child") } override fun getEntityData(): ParentEntityData = result ?: super.getEntityData() as ParentEntityData override fun getEntityClass(): Class<ParentEntity> = ParentEntity::class.java } } class ParentEntityData : WorkspaceEntityData<ParentEntity>() { lateinit var parentData: String fun isParentDataInitialized(): Boolean = ::parentData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ParentEntity> { val modifiable = ParentEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ParentEntity { val entity = ParentEntityImpl() entity._parentData = parentData entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ParentEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ParentEntityData if (this.parentData != other.parentData) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ParentEntityData if (this.parentData != other.parentData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + parentData.hashCode() return result } }
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentEntityImpl.kt
470770643
// 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.github.pullrequest.action import com.intellij.collaboration.async.CompletableFutureUtil.errorOnEdt import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt import com.intellij.collaboration.ui.codereview.InlineIconButton import com.intellij.icons.AllIcons import com.intellij.ide.ui.laf.darcula.ui.DarculaButtonUI import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.actions.IncrementalFindAction import com.intellij.openapi.fileTypes.FileTypes import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.ui.ComponentContainer import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.EditorTextField import com.intellij.ui.IdeBorderFactory import com.intellij.ui.SideBorder import com.intellij.ui.components.panels.HorizontalBox import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import com.intellij.util.ui.JButtonAction import com.intellij.util.ui.UIUtil import icons.CollaborationToolsIcons import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import org.jetbrains.plugins.github.api.data.GHPullRequestReviewEvent import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestPendingReview import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRReviewDataProvider import org.jetbrains.plugins.github.ui.component.GHHtmlErrorPanel import org.jetbrains.plugins.github.ui.component.GHSimpleErrorPanelModel import java.awt.FlowLayout import java.awt.Font import java.awt.event.ActionListener import javax.swing.* class GHPRReviewSubmitAction : JButtonAction(StringUtil.ELLIPSIS, GithubBundle.message("pull.request.review.submit.action.description")) { override fun update(e: AnActionEvent) { val dataProvider = e.getData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER) if (dataProvider == null) { e.presentation.isEnabledAndVisible = false return } val reviewData = dataProvider.reviewData val details = dataProvider.detailsData.loadedDetails e.presentation.isVisible = true val pendingReviewFuture = reviewData.loadPendingReview() e.presentation.isEnabled = pendingReviewFuture.isDone && details != null e.presentation.putClientProperty(PROP_PREFIX, getPrefix(e.place)) if (e.presentation.isEnabledAndVisible) { val review = try { pendingReviewFuture.getNow(null) } catch (e: Exception) { null } val pendingReview = review != null val comments = review?.comments?.totalCount e.presentation.text = getText(comments) e.presentation.putClientProperty(DarculaButtonUI.DEFAULT_STYLE_KEY, pendingReview) } } private fun getPrefix(place: String) = if (place == ActionPlaces.DIFF_TOOLBAR) GithubBundle.message("pull.request.review.submit") else GithubBundle.message("pull.request.review.submit.review") @NlsSafe private fun getText(pendingComments: Int?): String { val builder = StringBuilder() if (pendingComments != null) builder.append(" ($pendingComments)") builder.append(StringUtil.ELLIPSIS) return builder.toString() } override fun actionPerformed(e: AnActionEvent) { val dataProvider = e.getRequiredData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER) val details = dataProvider.detailsData.loadedDetails ?: return val reviewDataProvider = dataProvider.reviewData val pendingReviewFuture = reviewDataProvider.loadPendingReview() if (!pendingReviewFuture.isDone) return val pendingReview = try { pendingReviewFuture.getNow(null) } catch (e: Exception) { null } val parentComponent = e.presentation.getClientProperty(CustomComponentAction.COMPONENT_KEY) ?: return var cancelRunnable: (() -> Unit)? = null val cancelActionListener = ActionListener { cancelRunnable?.invoke() } val container = createPopupComponent(reviewDataProvider, reviewDataProvider.submitReviewCommentDocument, cancelActionListener, pendingReview, details.viewerDidAuthor) val popup = JBPopupFactory.getInstance() .createComponentPopupBuilder(container.component, container.preferredFocusableComponent) .setFocusable(true) .setRequestFocus(true) .setResizable(true) .createPopup() cancelRunnable = { popup.cancel() } popup.showUnderneathOf(parentComponent) } private fun createPopupComponent(reviewDataProvider: GHPRReviewDataProvider, document: Document, cancelActionListener: ActionListener, pendingReview: GHPullRequestPendingReview?, viewerIsAuthor: Boolean): ComponentContainer { return object : ComponentContainer { private val editor = createEditor(document) private val errorModel = GHSimpleErrorPanelModel(GithubBundle.message("pull.request.review.submit.error")) private val approveButton = if (!viewerIsAuthor) JButton(GithubBundle.message("pull.request.review.submit.approve.button")).apply { addActionListener(createSubmitButtonActionListener(GHPullRequestReviewEvent.APPROVE)) } else null private val rejectButton = if (!viewerIsAuthor) JButton(GithubBundle.message("pull.request.review.submit.request.changes")).apply { addActionListener(createSubmitButtonActionListener(GHPullRequestReviewEvent.REQUEST_CHANGES)) } else null private val commentButton = JButton(GithubBundle.message("pull.request.review.submit.comment.button")).apply { toolTipText = GithubBundle.message("pull.request.review.submit.comment.description") addActionListener(createSubmitButtonActionListener(GHPullRequestReviewEvent.COMMENT)) } private fun createSubmitButtonActionListener(event: GHPullRequestReviewEvent): ActionListener = ActionListener { e -> editor.isEnabled = false approveButton?.isEnabled = false rejectButton?.isEnabled = false commentButton.isEnabled = false discardButton?.isEnabled = false val reviewId = pendingReview?.id if (reviewId == null) { reviewDataProvider.createReview(EmptyProgressIndicator(), event, editor.text) } else { reviewDataProvider.submitReview(EmptyProgressIndicator(), reviewId, event, editor.text) }.successOnEdt { cancelActionListener.actionPerformed(e) runWriteAction { document.setText("") } }.errorOnEdt { errorModel.error = it editor.isEnabled = true approveButton?.isEnabled = true rejectButton?.isEnabled = true commentButton.isEnabled = true discardButton?.isEnabled = true } } private val discardButton: InlineIconButton? init { discardButton = pendingReview?.let { review -> val button = InlineIconButton(icon = CollaborationToolsIcons.Delete, hoveredIcon = CollaborationToolsIcons.DeleteHovered, tooltip = GithubBundle.message("pull.request.discard.pending.comments")) button.actionListener = ActionListener { if (MessageDialogBuilder.yesNo(GithubBundle.message("pull.request.discard.pending.comments.dialog.title"), GithubBundle.message("pull.request.discard.pending.comments.dialog.msg")).ask(button)) { reviewDataProvider.deleteReview(EmptyProgressIndicator(), review.id) } } button } } override fun getComponent(): JComponent { val titleLabel = JLabel(GithubBundle.message("pull.request.review.submit.review")).apply { font = font.deriveFont(font.style or Font.BOLD) } val titlePanel = HorizontalBox().apply { border = JBUI.Borders.empty(4, 4, 4, 4) add(titleLabel) if (pendingReview != null) { val commentsCount = pendingReview.comments.totalCount!! add(Box.createRigidArea(JBDimension(5, 0))) add(JLabel(GithubBundle.message("pull.request.review.pending.comments.count", commentsCount))).apply { foreground = UIUtil.getContextHelpForeground() } } add(Box.createHorizontalGlue()) discardButton?.let { add(it) } add(InlineIconButton(AllIcons.Actions.Close, AllIcons.Actions.CloseHovered).apply { actionListener = cancelActionListener }) } val errorPanel = GHHtmlErrorPanel.create(errorModel, SwingConstants.LEFT).apply { border = JBUI.Borders.empty(4) } val buttonsPanel = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0)).apply { border = JBUI.Borders.empty(4) if (!viewerIsAuthor) add(approveButton) if (!viewerIsAuthor) add(rejectButton) add(commentButton) } return JPanel(MigLayout(LC().gridGap("0", "0") .insets("0", "0", "0", "0") .fill().flowY().noGrid())).apply { isOpaque = false preferredSize = JBDimension(450, 165) add(titlePanel, CC().growX()) add(editor, CC().growX().growY() .gap("0", "0", "0", "0")) add(errorPanel, CC().minHeight("${JBUIScale.scale(32)}").growY().growPrioY(0).hideMode(3) .gap("0", "0", "0", "0")) add(buttonsPanel, CC().alignX("right")) } } private fun createEditor(document: Document) = EditorTextField(document, null, FileTypes.PLAIN_TEXT).apply { setOneLineMode(false) putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) setPlaceholder(GithubBundle.message("pull.request.review.comment.empty.text")) addSettingsProvider { it.settings.isUseSoftWraps = true it.setVerticalScrollbarVisible(true) it.scrollPane.border = IdeBorderFactory.createBorder(SideBorder.TOP or SideBorder.BOTTOM) it.scrollPane.viewportBorder = JBUI.Borders.emptyLeft(4) it.putUserData(IncrementalFindAction.SEARCH_DISABLED, true) } } override fun getPreferredFocusableComponent() = editor override fun dispose() {} } } override fun updateButtonFromPresentation(button: JButton, presentation: Presentation) { super.updateButtonFromPresentation(button, presentation) val prefix = presentation.getClientProperty(PROP_PREFIX) as? String ?: GithubBundle.message("pull.request.review.submit.review") button.text = prefix + presentation.text UIUtil.putClientProperty(button, DarculaButtonUI.DEFAULT_STYLE_KEY, presentation.getClientProperty(DarculaButtonUI.DEFAULT_STYLE_KEY)) } companion object { private const val PROP_PREFIX = "PREFIX" } }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/action/GHPRReviewSubmitAction.kt
2262556133
// 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.codeInspection.ui.actions import com.intellij.codeInspection.InspectionsBundle import com.intellij.codeInspection.InspectionsResultUtil import com.intellij.codeInspection.ex.GlobalInspectionContextImpl import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.codeInspection.ex.InspectionToolWrapper import com.intellij.codeInspection.ex.ScopeToolState import com.intellij.codeInspection.ui.InspectionNode import com.intellij.codeInspection.ui.InspectionTree import com.intellij.codeInspection.ui.InspectionTreeModel import com.intellij.icons.AllIcons import com.intellij.openapi.project.Project import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.MultiMap import java.io.IOException import java.nio.file.Path import java.util.function.Supplier @Suppress("ComponentNotRegistered") class ExportToXMLAction : InspectionResultsExportActionProvider(Supplier { "XML" }, InspectionsBundle.messagePointer("inspection.action.export.xml.description"), AllIcons.FileTypes.Xml) { override val progressTitle: String = InspectionsBundle.message("inspection.generating.xml.progress.title") override fun writeResults(tree: InspectionTree, profile: InspectionProfileImpl, globalInspectionContext: GlobalInspectionContextImpl, project: Project, outputPath: Path) { dumpToXml(profile, tree, project, globalInspectionContext, outputPath) } companion object { fun dumpToXml(profile: InspectionProfileImpl, tree: InspectionTree, project: Project, globalInspectionContext: GlobalInspectionContextImpl, outputPath: Path) { val singleTool = profile.singleTool val shortName2Wrapper = MultiMap<String, InspectionToolWrapper<*, *>>() if (singleTool != null) { shortName2Wrapper.put(singleTool, getWrappersForAllScopes(singleTool, globalInspectionContext)) } else { val model: InspectionTreeModel = tree.inspectionTreeModel model .traverse(model.root) .filter(InspectionNode::class.java) .filter { !it.isExcluded } .map { obj: InspectionNode -> obj.toolWrapper } .forEach { w: InspectionToolWrapper<*, *> -> shortName2Wrapper.putValue(w.shortName, w) } } for (entry in shortName2Wrapper.entrySet()) { val shortName: String = entry.key val wrappers: Collection<InspectionToolWrapper<*, *>> = entry.value InspectionsResultUtil.writeInspectionResult(project, shortName, wrappers, outputPath) { wrapper: InspectionToolWrapper<*, *> -> globalInspectionContext.getPresentation(wrapper) } } val descriptionsFile: Path = outputPath.resolve(InspectionsResultUtil.DESCRIPTIONS + InspectionsResultUtil.XML_EXTENSION) try { InspectionsResultUtil.describeInspections(descriptionsFile, profile.name, profile) } catch (e: javax.xml.stream.XMLStreamException) { throw IOException(e) } } private fun getWrappersForAllScopes(shortName: String, context: GlobalInspectionContextImpl): Collection<InspectionToolWrapper<*, *>> { return when (val tools = context.tools[shortName]) { null -> emptyList() //dummy entry points tool else -> ContainerUtil.map(tools.tools) { obj: ScopeToolState -> obj.tool } } } } }
platform/lang-impl/src/com/intellij/codeInspection/ui/actions/ExportToXMLAction.kt
3823949537
// 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. @file:JvmName("DocumentationUtil") package com.intellij.lang.documentation.ide import com.intellij.lang.documentation.DocumentationTarget import com.intellij.lang.documentation.ide.impl.DocumentationBrowser import com.intellij.lang.documentation.ide.ui.DocumentationUI import com.intellij.lang.documentation.impl.DocumentationRequest import com.intellij.model.Pointer import com.intellij.navigation.TargetPresentation import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.util.ui.EDT import org.jetbrains.annotations.ApiStatus.Experimental import javax.swing.JComponent @Experimental fun documentationComponent( project: Project, targetPointer: Pointer<out DocumentationTarget>, targetPresentation: TargetPresentation, parentDisposable: Disposable, ): JComponent { EDT.assertIsEdt() val request = DocumentationRequest(targetPointer, targetPresentation) return documentationComponent(project, request, parentDisposable) } internal fun documentationComponent( project: Project, request: DocumentationRequest, parentDisposable: Disposable, ): JComponent { val browser = DocumentationBrowser.createBrowser(project, request) val ui = DocumentationUI(project, browser) Disposer.register(parentDisposable, ui) return ui.scrollPane }
platform/lang-impl/src/com/intellij/lang/documentation/ide/documentationUtil.kt
2559490804
package org.javacs.kt import org.hamcrest.Matchers.hasToString import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtReferenceExpression import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.resolve.BindingContext import org.javacs.kt.compiler.Compiler import org.junit.Assert.assertThat import org.junit.Test import org.junit.After import org.junit.AfterClass import org.junit.BeforeClass import java.io.File import java.nio.file.Files class CompilerTest { val myTestResources = testResourcesRoot().resolve("compiler") val file = myTestResources.resolve("FileToEdit.kt") val editedText = """ private class FileToEdit { val someVal = 1 }""" companion object { lateinit var outputDirectory: File lateinit var compiler: Compiler @JvmStatic @BeforeClass fun setup() { LOG.connectStdioBackend() outputDirectory = Files.createTempDirectory("klsBuildOutput").toFile() compiler = Compiler(setOf(), setOf(), outputDirectory = outputDirectory) } @JvmStatic @AfterClass fun tearDown() { outputDirectory.delete() } } @Test fun compileFile() { val content = Files.readAllLines(file).joinToString("\n") val original = compiler.createKtFile(content, file) val (context, _) = compiler.compileKtFile(original, listOf(original)) val psi = original.findElementAt(45)!! val kt = psi.parentsWithSelf.filterIsInstance<KtExpression>().first() assertThat(context.getType(kt), hasToString("String")) } @Test fun newFile() { val original = compiler.createKtFile(editedText, file) val (context, _) = compiler.compileKtFile(original, listOf(original)) val psi = original.findElementAt(46)!! val kt = psi.parentsWithSelf.filterIsInstance<KtExpression>().first() assertThat(context.getType(kt), hasToString("Int")) } @Test fun editFile() { val content = Files.readAllLines(file).joinToString("\n") val original = compiler.createKtFile(content, file) var (context, _) = compiler.compileKtFile(original, listOf(original)) var psi = original.findElementAt(46)!! var kt = psi.parentsWithSelf.filterIsInstance<KtExpression>().first() assertThat(context.getType(kt), hasToString("String")) val edited = compiler.createKtFile(editedText, file) context = compiler.compileKtFile(edited, listOf(edited)).first psi = edited.findElementAt(46)!! kt = psi.parentsWithSelf.filterIsInstance<KtExpression>().first() assertThat(context.getType(kt), hasToString("Int")) } @Test fun editRef() { val file1 = testResourcesRoot().resolve("hover/Recover.kt") val content = Files.readAllLines(file1).joinToString("\n") val original = compiler.createKtFile(content, file1) val (context, _) = compiler.compileKtFile(original, listOf(original)) val function = original.findElementAt(49)!!.parentsWithSelf.filterIsInstance<KtNamedFunction>().first() val scope = context.get(BindingContext.LEXICAL_SCOPE, function.bodyExpression)!! val recompile = compiler.createKtDeclaration("""private fun singleExpressionFunction() = intFunction()""") val (recompileContext, _) = compiler.compileKtExpression(recompile, scope, setOf(original)) val intFunctionRef = recompile.findElementAt(41)!!.parentsWithSelf.filterIsInstance<KtReferenceExpression>().first() val target = recompileContext.get(BindingContext.REFERENCE_TARGET, intFunctionRef)!! assertThat(target.name, hasToString("intFunction")) } @After fun cleanUp() { compiler.close() } }
server/src/test/kotlin/org/javacs/kt/CompilerTest.kt
2918233852
// WITH_STDLIB fun <T> String.ext(): List<T> = listOf() fun f() { val v : List<Int> = <selection>"".ext()</selection> }
plugins/kotlin/idea/tests/testData/refactoring/introduceVariable/explicateTypeArguments/Qualified.kt
3773063779
open class SuperChain1<T1, T2> {} open class SuperChain2<T3, T4>: SuperChain1<T3, String>() {} open class SuperChain3<T5, T6>: SuperChain2<T5, String>() {} // This should end up with SuperChain2<T5, String> having // SuperChain1<T5, String> as a supertype.
java/ql/test/kotlin/library-tests/classes/superChain.kt
1599949689
package ua.com.lavi.komock.app import org.slf4j.LoggerFactory import org.yaml.snakeyaml.Yaml import ua.com.lavi.komock.KomockRunner import ua.com.lavi.komock.model.config.KomockConfiguration import java.io.IOException import java.nio.file.Files import java.nio.file.Paths /** * Created by Oleksandr Loushkin */ object KomockApplication { private val log = LoggerFactory.getLogger(this.javaClass) @JvmStatic fun main(args: Array<String>) { if (args.isNotEmpty()) { runApplication(args[0]) } else { log.error("Please input path with the configuration! Example: komock-app mock_example.yml") } } private fun runApplication(path: String) { log.info("Run Komock version: ${version()}. config path: $path") try { Files.newInputStream(Paths.get(path)).use { it -> KomockRunner().run(Yaml().loadAs<KomockConfiguration>(it, KomockConfiguration::class.java)) } } catch (e: IOException) { log.error("Unable to read configuration file: ", e) } } private fun version(): String { return KomockApplication::class.java.classLoader.getResourceAsStream("version.properties").bufferedReader().use { it.readText() } } }
komock-app/src/main/kotlin/ua/com/lavi/komock/app/KomockApplication.kt
3598384767
package com.virtlink.paplj.syntaxcoloring import com.google.inject.Inject import com.virtlink.editorservices.* import com.virtlink.editorservices.resources.IResourceManager import com.virtlink.editorservices.syntaxcoloring.* import com.virtlink.logging.logger import com.virtlink.paplj.syntax.PapljAntlrLexer import org.antlr.v4.runtime.ANTLRInputStream import java.net.URI class AntlrSyntaxColorizer @Inject constructor( private val resourceManager: IResourceManager) : ISyntaxColoringService { @Suppress("PrivatePropertyName") private val LOG by logger() override fun configure(configuration: ISyntaxColoringConfiguration) { // Nothing to do. } override fun getSyntaxColoringInfo(document: URI, span: Span, cancellationToken: ICancellationToken?): ISyntaxColoringInfo? { val tokens = mutableListOf<IToken>() val content = this.resourceManager.getContent(document) if (content == null) { LOG.warn("$document: Could not get content.") return SyntaxColoringInfo(emptyList()) } val input = ANTLRInputStream(content.text) val lexer = PapljAntlrLexer(input) var token = lexer.nextToken() while (token.type != org.antlr.v4.runtime.Token.EOF) { val scope = getTokenScope(token) val startOffset = token.startIndex val endOffset = token.stopIndex + 1 tokens.add(Token(Span(startOffset.toLong(), endOffset.toLong()), ScopeNames(scope))) token = lexer.nextToken() } return SyntaxColoringInfo(tokens) } private val keywords = arrayOf("PROGRAM", "RUN", "IMPORT", "CLASS", "EXTENDS", "IF", "ELSE", "LET", "IN", "AS", "TRUE", "FALSE", "THIS", "NULL", "NEW") private val operators = arrayOf("EQ", "NEQ", "LTE", "GTE", "LT", "GT", "OR", "AND", "ASSIGN", "PLUS", "MIN", "MUL", "DIV", "NOT") private fun getTokenScope(token: org.antlr.v4.runtime.Token): String { val tokenName = if (token.type > 0 && token.type <= PapljAntlrLexer.ruleNames.size) PapljAntlrLexer.ruleNames[token.type - 1] else null return when (tokenName) { in keywords -> "keyword" in operators -> "keyword.operator" "LBRACE", "RBRACE" -> "meta.braces" "LPAREN", "RPAREN" -> "meta.parens" "DOT", "DOTSTAR" -> "punctuation.accessor" "COMMA" -> "punctuation.separator" "SEMICOLON" -> "punctuation.terminator" "ID" -> "entity.name" // Not really correct "INT" -> "constant.numeric" "COMMENT" -> "comment.block" "LINE_COMMENT" -> "comment.line" "WS" -> "text.whitespace" else -> "invalid.illegal" } } }
paplj/src/main/kotlin/com/virtlink/paplj/syntaxcoloring/AntlrSyntaxColorizer.kt
3540458034
package com.github.bumblebee.command.youtube.service import com.github.bumblebee.command.youtube.entity.VideoNotification import org.junit.Assert.assertEquals import org.junit.Test class AtomParserTest { private val xml = """ <?xml version='1.0' encoding='UTF-8'?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:yt="http://www.youtube.com/xml/schemas/2015"> <link href="https://pubsubhubbub.appspot.com" rel="hub"/> <link href="https://www.youtube.com/xml/fee ds/videos.xml?channel_id=UCZRc1nFfH2FmGd2feIBlPOQ" rel="self"/> <title>YouTube video feed</title> <updated>2018-03-07T10:00:41.416229036+00:00</updated> <entry> <id>yt:video:1OYzEVHUfqs</id> <yt:videoId>1OYzEVHUfqs</yt:videoId> <yt:channelId>UCZRc1nFfH2FmGd2feIBlPOQ</yt:channelId> <title>Some title!</title> <link href="https://www.youtube.com/watch?v=1OYzEVHUfqs" rel="alternate"/> <author> <name>Some author</name> <uri>https://www.youtube.com/channel/UCZRc1nFfH2FmGd2feIBlPOQ</uri> </author> <published>2018-03-07T10:00:00+00:00</published> <updated>2018-03-07T10:00:41.416229036+00:00</updated> </entry> </feed> """.trimIndent() @Test fun parse() { // given val parser = AtomParser() // when val notification = parser.parse(xml) // then assertEquals(VideoNotification("1OYzEVHUfqs", "UCZRc1nFfH2FmGd2feIBlPOQ"), notification) } }
telegram-bot-bumblebee-core/src/test/kotlin/com/github/bumblebee/command/youtube/service/AtomParserTest.kt
627631916
// "Add annotation target" "false" // ACTION: Introduce import alias // WITH_STDLIB // DISABLE-ERRORS @file:MyExperimentalAPI<caret> @RequiresOptIn @Target(AnnotationTarget.FIELD) annotation class MyExperimentalAPI
plugins/kotlin/idea/tests/testData/quickfix/addAnnotationTarget/requiresOptIn/file.kt
467197053
// 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.codeInspection.dataFlow.inference import com.intellij.codeInsight.Nullability import com.intellij.codeInsight.NullableNotNullManager import com.intellij.codeInspection.dataFlow.ContractReturnValue import com.intellij.codeInspection.dataFlow.JavaMethodContractUtil import com.intellij.codeInspection.dataFlow.NullabilityUtil import com.intellij.codeInspection.dataFlow.StandardMethodContract import com.intellij.codeInspection.dataFlow.StandardMethodContract.ValueConstraint.* import com.intellij.codeInspection.dataFlow.inference.ContractInferenceInterpreter.withConstraint import com.intellij.codeInspection.dataFlow.java.inst.MethodCallInstruction import com.intellij.psi.* import com.intellij.psi.util.PsiUtil import com.siyeh.ig.psiutils.SideEffectChecker /** * @author peter */ interface PreContract { fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> fun negate(): PreContract? = NegatingContract( this) } internal data class KnownContract(val contract: StandardMethodContract) : PreContract { override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock) = listOf(contract) override fun negate() = negateContract(contract)?.let(::KnownContract) } internal data class DelegationContract(internal val expression: ExpressionRange, internal val negated: Boolean) : PreContract { override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> { val call : PsiMethodCallExpression = expression.restoreExpression(body()) val result = call.resolveMethodGenerics() val targetMethod = result.element as PsiMethod? ?: return emptyList() if (targetMethod == method) return emptyList() val parameters = targetMethod.parameterList.parameters val arguments = call.argumentList.expressions val qualifier = call.methodExpression.qualifierExpression val varArgCall = MethodCallInstruction.isVarArgCall(targetMethod, result.substitutor, arguments, parameters) val methodContracts = StandardMethodContract.toNonIntersectingStandardContracts(JavaMethodContractUtil.getMethodContracts(targetMethod)) ?: return emptyList() val fromDelegate = methodContracts.mapNotNull { dc -> convertDelegatedMethodContract(method, parameters, qualifier, arguments, varArgCall, dc) }.toMutableList() while (fromDelegate.isNotEmpty() && fromDelegate[fromDelegate.size - 1].returnValue == ContractReturnValue.returnAny()) { fromDelegate.removeAt(fromDelegate.size - 1) } if (NullableNotNullManager.isNotNull(targetMethod)) { fromDelegate += listOf( StandardMethodContract(emptyConstraints(method), ContractReturnValue.returnNotNull())) } return StandardMethodContract.toNonIntersectingStandardContracts(fromDelegate) ?: emptyList() } private fun convertDelegatedMethodContract(callerMethod: PsiMethod, targetParameters: Array<PsiParameter>, qualifier: PsiExpression?, callArguments: Array<PsiExpression>, varArgCall: Boolean, targetContract: StandardMethodContract): StandardMethodContract? { var answer: Array<StandardMethodContract.ValueConstraint>? = emptyConstraints(callerMethod) for (i in 0 until targetContract.parameterCount) { if (i >= callArguments.size) return null val argConstraint = targetContract.getParameterConstraint(i) if (argConstraint != ANY_VALUE) { if (varArgCall && i >= targetParameters.size - 1) { if (argConstraint == NULL_VALUE) { return null } break } val argument = PsiUtil.skipParenthesizedExprDown(callArguments[i]) ?: return null val paramIndex = resolveParameter(callerMethod, argument) if (paramIndex >= 0) { answer = withConstraint(answer, paramIndex, argConstraint) ?: return null } else if (argConstraint != getLiteralConstraint(argument)) { return null } } } var returnValue = targetContract.returnValue returnValue = when (returnValue) { is ContractReturnValue.BooleanReturnValue -> { if (negated) returnValue.negate() else returnValue } is ContractReturnValue.ParameterReturnValue -> { mapReturnValue(callerMethod, callArguments[returnValue.parameterNumber]) } ContractReturnValue.returnThis() -> { mapReturnValue(callerMethod, qualifier) } else -> returnValue } return answer?.let { StandardMethodContract(it, returnValue) } } private fun mapReturnValue(callerMethod: PsiMethod, argument: PsiExpression?): ContractReturnValue? { val stripped = PsiUtil.skipParenthesizedExprDown(argument) val paramIndex = resolveParameter(callerMethod, stripped) return when { paramIndex >= 0 -> ContractReturnValue.returnParameter(paramIndex) stripped is PsiLiteralExpression -> when (stripped.value) { null -> ContractReturnValue.returnNull() true -> ContractReturnValue.returnTrue() false -> ContractReturnValue.returnFalse() else -> ContractReturnValue.returnNotNull() } stripped is PsiThisExpression && stripped.qualifier == null -> ContractReturnValue.returnThis() stripped is PsiNewExpression -> ContractReturnValue.returnNew() NullabilityUtil.getExpressionNullability(stripped) == Nullability.NOT_NULL -> ContractReturnValue.returnNotNull() else -> ContractReturnValue.returnAny() } } private fun emptyConstraints(method: PsiMethod) = StandardMethodContract.createConstraintArray( method.parameterList.parametersCount) private fun returnNotNull(mc: StandardMethodContract): StandardMethodContract { return if (mc.returnValue.isFail) mc else mc.withReturnValue(ContractReturnValue.returnNotNull()) } private fun getLiteralConstraint(argument: PsiExpression) = when (argument) { is PsiLiteralExpression -> ContractInferenceInterpreter.getLiteralConstraint( argument.getFirstChild().node.elementType) is PsiNewExpression, is PsiPolyadicExpression, is PsiFunctionalExpression -> NOT_NULL_VALUE else -> null } private fun resolveParameter(method: PsiMethod, expr: PsiExpression?): Int { val target = if (expr is PsiReferenceExpression && !expr.isQualified) expr.resolve() else null return if (target is PsiParameter && target.parent === method.parameterList) method.parameterList.getParameterIndex(target) else -1 } } internal data class SideEffectFilter(internal val expressionsToCheck: List<ExpressionRange>, internal val contracts: List<PreContract>) : PreContract { override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> { if (expressionsToCheck.any { d -> mayHaveSideEffects(body(), d) }) { return emptyList() } return contracts.flatMap { c -> c.toContracts(method, body) } } private fun mayHaveSideEffects(body: PsiCodeBlock, range: ExpressionRange) = range.restoreExpression<PsiExpression>(body).let { SideEffectChecker.mayHaveSideEffects(it) } } internal data class NegatingContract(internal val negated: PreContract) : PreContract { override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock) = negated.toContracts(method, body).mapNotNull(::negateContract) } private fun negateContract(c: StandardMethodContract): StandardMethodContract? { val ret = c.returnValue return if (ret is ContractReturnValue.BooleanReturnValue) c.withReturnValue(ret.negate()) else null } @Suppress("EqualsOrHashCode") internal data class MethodCallContract(internal val call: ExpressionRange, internal val states: List<List<StandardMethodContract.ValueConstraint>>) : PreContract { override fun hashCode() = call.hashCode() * 31 + states.flatten().map { it.ordinal }.hashCode() override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> { val target = call.restoreExpression<PsiMethodCallExpression>(body()).resolveMethod() if (target != null && target != method && NullableNotNullManager.isNotNull(target)) { return ContractInferenceInterpreter.toContracts(states.map { it.toTypedArray() }, ContractReturnValue.returnNotNull()) } return emptyList() } }
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/preContracts.kt
1233761959
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.ui import com.intellij.diagnostic.LoadingState import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponentWithModificationTracker import com.intellij.openapi.components.SettingsCategory import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.registry.Registry import com.intellij.serviceContainer.NonInjectable import com.intellij.ui.JreHiDpiUtil import com.intellij.ui.scale.JBUIScale import com.intellij.util.ComponentTreeEventDispatcher import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.UIUtil import com.intellij.util.xmlb.annotations.Transient import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval import java.awt.Graphics import java.awt.Graphics2D import java.awt.RenderingHints import javax.swing.JComponent import javax.swing.SwingConstants private val LOG = logger<UISettings>() @State(name = "UISettings", storages = [(Storage("ui.lnf.xml"))], useLoadedStateAsExisting = false, category = SettingsCategory.UI) class UISettings @NonInjectable constructor(private val notRoamableOptions: NotRoamableUiSettings) : PersistentStateComponentWithModificationTracker<UISettingsState> { constructor() : this(ApplicationManager.getApplication().getService(NotRoamableUiSettings::class.java)) private var state = UISettingsState() private val myTreeDispatcher = ComponentTreeEventDispatcher.create(UISettingsListener::class.java) var ideAAType: AntialiasingType get() = notRoamableOptions.state.ideAAType set(value) { notRoamableOptions.state.ideAAType = value } var editorAAType: AntialiasingType get() = notRoamableOptions.state.editorAAType set(value) { notRoamableOptions.state.editorAAType = value } val allowMergeButtons: Boolean get() = Registry.`is`("ide.allow.merge.buttons", true) val animateWindows: Boolean get() = Registry.`is`("ide.animate.toolwindows", false) var colorBlindness: ColorBlindness? get() = state.colorBlindness set(value) { state.colorBlindness = value } var useContrastScrollbars: Boolean get() = state.useContrastScrollBars set(value) { state.useContrastScrollBars = value } var hideToolStripes: Boolean get() = state.hideToolStripes set(value) { state.hideToolStripes = value } val hideNavigationOnFocusLoss: Boolean get() = Registry.`is`("ide.hide.navigation.on.focus.loss", false) var reuseNotModifiedTabs: Boolean get() = state.reuseNotModifiedTabs set(value) { state.reuseNotModifiedTabs = value } var openTabsInMainWindow: Boolean get() = state.openTabsInMainWindow set(value) { state.openTabsInMainWindow = value } var openInPreviewTabIfPossible: Boolean get() = state.openInPreviewTabIfPossible set(value) { state.openInPreviewTabIfPossible = value } var disableMnemonics: Boolean get() = state.disableMnemonics set(value) { state.disableMnemonics = value } var disableMnemonicsInControls: Boolean get() = state.disableMnemonicsInControls set(value) { state.disableMnemonicsInControls = value } var dndWithPressedAltOnly: Boolean get() = state.dndWithPressedAltOnly set(value) { state.dndWithPressedAltOnly = value } var separateMainMenu: Boolean get() = (SystemInfoRt.isWindows || SystemInfoRt.isXWindow) && state.separateMainMenu set(value) { state.separateMainMenu = value state.showMainToolbar = value } var useSmallLabelsOnTabs: Boolean get() = state.useSmallLabelsOnTabs set(value) { state.useSmallLabelsOnTabs = value } var smoothScrolling: Boolean get() = state.smoothScrolling set(value) { state.smoothScrolling = value } val animatedScrolling: Boolean get() = state.animatedScrolling val animatedScrollingDuration: Int get() = state.animatedScrollingDuration val animatedScrollingCurvePoints: Int get() = state.animatedScrollingCurvePoints val closeTabButtonOnTheRight: Boolean get() = state.closeTabButtonOnTheRight val cycleScrolling: Boolean get() = AdvancedSettings.getBoolean("ide.cycle.scrolling") val scrollTabLayoutInEditor: Boolean get() = state.scrollTabLayoutInEditor var showToolWindowsNumbers: Boolean get() = state.showToolWindowsNumbers set(value) { state.showToolWindowsNumbers = value } var showEditorToolTip: Boolean get() = state.showEditorToolTip set(value) { state.showEditorToolTip = value } var showNavigationBar: Boolean get() = state.showNavigationBar set(value) { state.showNavigationBar = value } var navBarLocation : NavBarLocation get() = state.navigationBarLocation set(value) { state.navigationBarLocation = value } val showNavigationBarInBottom : Boolean get() = showNavigationBar && navBarLocation == NavBarLocation.BOTTOM var showMembersInNavigationBar: Boolean get() = state.showMembersInNavigationBar set(value) { state.showMembersInNavigationBar = value } var showStatusBar: Boolean get() = state.showStatusBar set(value) { state.showStatusBar = value } var showMainMenu: Boolean get() = state.showMainMenu set(value) { state.showMainMenu = value } val showIconInQuickNavigation: Boolean get() = Registry.`is`("ide.show.icons.in.quick.navigation", false) var showTreeIndentGuides: Boolean get() = state.showTreeIndentGuides set(value) { state.showTreeIndentGuides = value } var compactTreeIndents: Boolean get() = state.compactTreeIndents set(value) { state.compactTreeIndents = value } var showMainToolbar: Boolean get() = state.showMainToolbar set(value) { state.showMainToolbar = value val toolbarSettingsState = ToolbarSettings.getInstance().state!! toolbarSettingsState.showNewMainToolbar = !value && toolbarSettingsState.showNewMainToolbar } var showIconsInMenus: Boolean get() = state.showIconsInMenus set(value) { state.showIconsInMenus = value } var sortLookupElementsLexicographically: Boolean get() = state.sortLookupElementsLexicographically set(value) { state.sortLookupElementsLexicographically = value } val hideTabsIfNeeded: Boolean get() = state.hideTabsIfNeeded || editorTabPlacement == SwingConstants.LEFT || editorTabPlacement == SwingConstants.RIGHT var showFileIconInTabs: Boolean get() = state.showFileIconInTabs set(value) { state.showFileIconInTabs = value } var hideKnownExtensionInTabs: Boolean get() = state.hideKnownExtensionInTabs set(value) { state.hideKnownExtensionInTabs = value } var leftHorizontalSplit: Boolean get() = state.leftHorizontalSplit set(value) { state.leftHorizontalSplit = value } var rightHorizontalSplit: Boolean get() = state.rightHorizontalSplit set(value) { state.rightHorizontalSplit = value } var wideScreenSupport: Boolean get() = state.wideScreenSupport set(value) { state.wideScreenSupport = value } var sortBookmarks: Boolean get() = state.sortBookmarks set(value) { state.sortBookmarks = value } val showCloseButton: Boolean get() = state.showCloseButton var presentationMode: Boolean get() = state.presentationMode set(value) { state.presentationMode = value } var presentationModeFontSize: Int get() = state.presentationModeFontSize set(value) { state.presentationModeFontSize = value } var editorTabPlacement: Int get() = state.editorTabPlacement set(value) { state.editorTabPlacement = value } var editorTabLimit: Int get() = state.editorTabLimit set(value) { state.editorTabLimit = value } var recentFilesLimit: Int get() = state.recentFilesLimit set(value) { state.recentFilesLimit = value } var recentLocationsLimit: Int get() = state.recentLocationsLimit set(value) { state.recentLocationsLimit = value } var maxLookupWidth: Int get() = state.maxLookupWidth set(value) { state.maxLookupWidth = value } var maxLookupListHeight: Int get() = state.maxLookupListHeight set(value) { state.maxLookupListHeight = value } var overrideLafFonts: Boolean get() = state.overrideLafFonts set(value) { state.overrideLafFonts = value } var fontFace: @NlsSafe String? get() = notRoamableOptions.state.fontFace set(value) { notRoamableOptions.state.fontFace = value } var fontSize: Int get() = (notRoamableOptions.state.fontSize + 0.5).toInt() set(value) { notRoamableOptions.state.fontSize = value.toFloat() } var fontSize2D: Float get() = notRoamableOptions.state.fontSize set(value) { notRoamableOptions.state.fontSize = value } var fontScale: Float get() = notRoamableOptions.state.fontScale set(value) { notRoamableOptions.state.fontScale = value } var showDirectoryForNonUniqueFilenames: Boolean get() = state.showDirectoryForNonUniqueFilenames set(value) { state.showDirectoryForNonUniqueFilenames = value } var pinFindInPath: Boolean get() = state.pinFindInPath set(value) { state.pinFindInPath = value } var activeRightEditorOnClose: Boolean get() = state.activeRightEditorOnClose set(value) { state.activeRightEditorOnClose = value } var showTabsTooltips: Boolean get() = state.showTabsTooltips set(value) { state.showTabsTooltips = value } var markModifiedTabsWithAsterisk: Boolean get() = state.markModifiedTabsWithAsterisk set(value) { state.markModifiedTabsWithAsterisk = value } var overrideConsoleCycleBufferSize: Boolean get() = state.overrideConsoleCycleBufferSize set(value) { state.overrideConsoleCycleBufferSize = value } var consoleCycleBufferSizeKb: Int get() = state.consoleCycleBufferSizeKb set(value) { state.consoleCycleBufferSizeKb = value } var consoleCommandHistoryLimit: Int get() = state.consoleCommandHistoryLimit set(value) { state.consoleCommandHistoryLimit = value } var sortTabsAlphabetically: Boolean get() = state.sortTabsAlphabetically set(value) { state.sortTabsAlphabetically = value } var alwaysKeepTabsAlphabeticallySorted: Boolean get() = state.alwaysKeepTabsAlphabeticallySorted set(value) { state.alwaysKeepTabsAlphabeticallySorted = value } var openTabsAtTheEnd: Boolean get() = state.openTabsAtTheEnd set(value) { state.openTabsAtTheEnd = value } var showInplaceComments: Boolean get() = state.showInplaceComments set(value) { state.showInplaceComments = value } val showInplaceCommentsInternal: Boolean get() = showInplaceComments && ApplicationManager.getApplication()?.isInternal ?: false var fullPathsInWindowHeader: Boolean get() = state.fullPathsInWindowHeader set(value) { state.fullPathsInWindowHeader = value } var mergeMainMenuWithWindowTitle: Boolean get() = state.mergeMainMenuWithWindowTitle set(value) { state.mergeMainMenuWithWindowTitle = value } var showVisualFormattingLayer: Boolean get() = state.showVisualFormattingLayer set(value) { state.showVisualFormattingLayer = value } companion object { init { if (JBUIScale.SCALE_VERBOSE) { LOG.info(String.format("defFontSize=%.1f, defFontScale=%.2f", defFontSize, defFontScale)) } } const val ANIMATION_DURATION = 300 // Milliseconds /** Not tabbed pane. */ const val TABS_NONE = 0 @Volatile private var cachedInstance: UISettings? = null @JvmStatic fun getInstance(): UISettings { var result = cachedInstance if (result == null) { LoadingState.CONFIGURATION_STORE_INITIALIZED.checkOccurred() result = ApplicationManager.getApplication().getService(UISettings::class.java)!! cachedInstance = result } return result } @JvmStatic val instanceOrNull: UISettings? get() { val result = cachedInstance if (result == null && LoadingState.CONFIGURATION_STORE_INITIALIZED.isOccurred) { return getInstance() } return result } /** * Use this method if you are not sure whether the application is initialized. * @return persisted UISettings instance or default values. */ @JvmStatic val shadowInstance: UISettings get() = instanceOrNull ?: UISettings(NotRoamableUiSettings()) private fun calcFractionalMetricsHint(registryKey: String, defaultValue: Boolean): Any { val hint: Boolean if (LoadingState.APP_STARTED.isOccurred) { val registryValue = Registry.get(registryKey) if (registryValue.isMultiValue) { val option = registryValue.selectedOption if (option.equals("Enabled")) hint = true else if (option.equals("Disabled")) hint = false else hint = defaultValue } else { hint = if (registryValue.isBoolean && registryValue.asBoolean()) true else defaultValue } } else hint = defaultValue return if (hint) RenderingHints.VALUE_FRACTIONALMETRICS_ON else RenderingHints.VALUE_FRACTIONALMETRICS_OFF } fun getPreferredFractionalMetricsValue(): Any { val enableByDefault = SystemInfo.isMacOSCatalina || (FontSubpixelResolution.ENABLED && AntialiasingType.getKeyForCurrentScope(false) == RenderingHints.VALUE_TEXT_ANTIALIAS_ON) return calcFractionalMetricsHint("ide.text.fractional.metrics", enableByDefault) } @JvmStatic val editorFractionalMetricsHint: Any get() { val enableByDefault = FontSubpixelResolution.ENABLED && AntialiasingType.getKeyForCurrentScope(true) == RenderingHints.VALUE_TEXT_ANTIALIAS_ON return calcFractionalMetricsHint("editor.text.fractional.metrics", enableByDefault) } @JvmStatic fun setupFractionalMetrics(g2d: Graphics2D) { g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, getPreferredFractionalMetricsValue()) } /** * This method must not be used for set up antialiasing for editor components. To make sure antialiasing settings are taken into account * when preferred size of component is calculated, [.setupComponentAntialiasing] method should be called from * `updateUI()` or `setUI()` method of component. */ @JvmStatic fun setupAntialiasing(g: Graphics) { g as Graphics2D g.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, UIUtil.getLcdContrastValue()) if (LoadingState.CONFIGURATION_STORE_INITIALIZED.isOccurred && ApplicationManager.getApplication() == null) { // cannot use services while Application has not been loaded yet, so let's apply the default hints GraphicsUtil.applyRenderingHints(g) return } g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false)) setupFractionalMetrics(g) } @JvmStatic fun setupComponentAntialiasing(component: JComponent) { GraphicsUtil.setAntialiasingType(component, AntialiasingType.getAAHintForSwingComponent()) } @JvmStatic fun setupEditorAntialiasing(component: JComponent) { GraphicsUtil.setAntialiasingType(component, getInstance().editorAAType.textInfo) } /** * Returns the default font scale, which depends on the HiDPI mode (see [com.intellij.ui.scale.ScaleType]). * <p> * The font is represented: * - in relative (dpi-independent) points in the JRE-managed HiDPI mode, so the method returns 1.0f * - in absolute (dpi-dependent) points in the IDE-managed HiDPI mode, so the method returns the default screen scale * * @return the system font scale */ @JvmStatic val defFontScale: Float get() = when { JreHiDpiUtil.isJreHiDPIEnabled() -> 1f else -> JBUIScale.sysScale() } /** * Returns the default font size scaled by #defFontScale * * @return the default scaled font size */ @JvmStatic val defFontSize: Float get() = UISettingsState.defFontSize @Deprecated("Use {@link #restoreFontSize(Float, Float?)} instead") @JvmStatic fun restoreFontSize(readSize: Int, readScale: Float?): Int { return restoreFontSize(readSize.toFloat(), readScale).toInt() } @JvmStatic fun restoreFontSize(readSize: Float, readScale: Float?): Float { var size = readSize if (readScale == null || readScale <= 0) { if (JBUIScale.SCALE_VERBOSE) LOG.info("Reset font to default") // Reset font to default on switch from IDE-managed HiDPI to JRE-managed HiDPI. Doesn't affect OSX. if (!SystemInfoRt.isMac && JreHiDpiUtil.isJreHiDPIEnabled()) { size = UISettingsState.defFontSize } } else if (readScale != defFontScale) { size = (readSize / readScale) * defFontScale } if (JBUIScale.SCALE_VERBOSE) LOG.info("Loaded: fontSize=$readSize, fontScale=$readScale; restored: fontSize=$size, fontScale=$defFontScale") return size } const val MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY = "ide.win.frame.decoration" @JvmStatic val mergeMainMenuWithWindowTitleOverrideValue = System.getProperty(MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY)?.toBoolean() val isMergeMainMenuWithWindowTitleOverridden = mergeMainMenuWithWindowTitleOverrideValue != null } @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated("Please use {@link UISettingsListener#TOPIC}") @ScheduledForRemoval fun addUISettingsListener(listener: UISettingsListener, parentDisposable: Disposable) { ApplicationManager.getApplication().messageBus.connect(parentDisposable).subscribe(UISettingsListener.TOPIC, listener) } /** * Notifies all registered listeners that UI settings has been changed. */ fun fireUISettingsChanged() { updateDeprecatedProperties() // todo remove when all old properties will be converted state._incrementModificationCount() IconLoader.setFilter(ColorBlindnessSupport.get(state.colorBlindness)?.filter) // if this is the main UISettings instance (and not on first call to getInstance) push event to bus and to all current components if (this === cachedInstance) { myTreeDispatcher.multicaster.uiSettingsChanged(this) ApplicationManager.getApplication().messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(this) } } @Suppress("DEPRECATION") private fun updateDeprecatedProperties() { HIDE_TOOL_STRIPES = hideToolStripes SHOW_MAIN_TOOLBAR = showMainToolbar SHOW_CLOSE_BUTTON = showCloseButton PRESENTATION_MODE = presentationMode OVERRIDE_NONIDEA_LAF_FONTS = overrideLafFonts PRESENTATION_MODE_FONT_SIZE = presentationModeFontSize CONSOLE_COMMAND_HISTORY_LIMIT = state.consoleCommandHistoryLimit FONT_SIZE = fontSize FONT_FACE = fontFace EDITOR_TAB_LIMIT = editorTabLimit } override fun getState() = state override fun loadState(state: UISettingsState) { this.state = state updateDeprecatedProperties() migrateOldSettings() if (migrateOldFontSettings()) { notRoamableOptions.fixFontSettings() } // Check tab placement in editor val editorTabPlacement = state.editorTabPlacement if (editorTabPlacement != TABS_NONE && editorTabPlacement != SwingConstants.TOP && editorTabPlacement != SwingConstants.LEFT && editorTabPlacement != SwingConstants.BOTTOM && editorTabPlacement != SwingConstants.RIGHT) { state.editorTabPlacement = SwingConstants.TOP } // Check that alpha delay and ratio are valid if (state.alphaModeDelay < 0) { state.alphaModeDelay = 1500 } if (state.alphaModeRatio < 0.0f || state.alphaModeRatio > 1.0f) { state.alphaModeRatio = 0.5f } fireUISettingsChanged() } override fun getStateModificationCount(): Long { return state.modificationCount } @Suppress("DEPRECATION") private fun migrateOldSettings() { if (state.ideAAType != AntialiasingType.SUBPIXEL) { ideAAType = state.ideAAType state.ideAAType = AntialiasingType.SUBPIXEL } if (state.editorAAType != AntialiasingType.SUBPIXEL) { editorAAType = state.editorAAType state.editorAAType = AntialiasingType.SUBPIXEL } if (!state.allowMergeButtons) { Registry.get("ide.allow.merge.buttons").setValue(false) state.allowMergeButtons = true } } @Suppress("DEPRECATION") private fun migrateOldFontSettings(): Boolean { var migrated = false if (state.fontSize != 0) { fontSize2D = restoreFontSize(state.fontSize.toFloat(), state.fontScale) state.fontSize = 0 migrated = true } if (state.fontScale != 0f) { fontScale = state.fontScale state.fontScale = 0f migrated = true } if (state.fontFace != null) { fontFace = state.fontFace state.fontFace = null migrated = true } return migrated } //<editor-fold desc="Deprecated stuff."> @Suppress("PropertyName") @Deprecated("Use fontFace", replaceWith = ReplaceWith("fontFace")) @JvmField @Transient var FONT_FACE: String? = null @Suppress("PropertyName") @Deprecated("Use fontSize", replaceWith = ReplaceWith("fontSize")) @JvmField @Transient var FONT_SIZE: Int? = 0 @Suppress("PropertyName") @Deprecated("Use hideToolStripes", replaceWith = ReplaceWith("hideToolStripes")) @JvmField @Transient var HIDE_TOOL_STRIPES = true @Suppress("PropertyName") @Deprecated("Use consoleCommandHistoryLimit", replaceWith = ReplaceWith("consoleCommandHistoryLimit")) @JvmField @Transient var CONSOLE_COMMAND_HISTORY_LIMIT = 300 @Suppress("unused", "PropertyName") @Deprecated("Use cycleScrolling", replaceWith = ReplaceWith("cycleScrolling"), level = DeprecationLevel.ERROR) @JvmField @Transient var CYCLE_SCROLLING = true @Suppress("PropertyName") @Deprecated("Use showMainToolbar", replaceWith = ReplaceWith("showMainToolbar")) @JvmField @Transient var SHOW_MAIN_TOOLBAR = false @Suppress("PropertyName") @Deprecated("Use showCloseButton", replaceWith = ReplaceWith("showCloseButton")) @JvmField @Transient var SHOW_CLOSE_BUTTON = true @Suppress("PropertyName") @Deprecated("Use presentationMode", replaceWith = ReplaceWith("presentationMode")) @JvmField @Transient var PRESENTATION_MODE = false @Suppress("PropertyName", "SpellCheckingInspection") @Deprecated("Use overrideLafFonts", replaceWith = ReplaceWith("overrideLafFonts")) @JvmField @Transient var OVERRIDE_NONIDEA_LAF_FONTS = false @Suppress("PropertyName") @Deprecated("Use presentationModeFontSize", replaceWith = ReplaceWith("presentationModeFontSize")) @JvmField @Transient var PRESENTATION_MODE_FONT_SIZE = 24 @Suppress("PropertyName") @Deprecated("Use editorTabLimit", replaceWith = ReplaceWith("editorTabLimit")) @JvmField @Transient var EDITOR_TAB_LIMIT = editorTabLimit //</editor-fold> }
platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.kt
2887430260
package model data class Greeting(val id: Long, val content: String)
gs-rest-service/src/main/kotlin/model/Greeting.kt
1450931198
package com.androidessence.lib import android.graphics.Canvas import android.graphics.Paint import android.text.Layout import android.text.Spanned import android.text.style.LeadingMarginSpan /** * Allows a number of rows in a TextView to have bullets in front of them. * * Created by Raghunandan on 28-11-2016. */ class CustomBulletSpan(private val mGapWidth: Int, private val mIgnoreSpan: Boolean, private val bulletColor: Int, private val bulletRadius: Int) : LeadingMarginSpan { override fun getLeadingMargin(first: Boolean): Int { return mGapWidth//mIgnoreSpan ? 0 : Math.max(Math.round(mWidth + 2), mGapWidth); } override fun drawLeadingMargin(c: Canvas, p: Paint, x: Int, dir: Int, top: Int, baseline: Int, bottom: Int, text: CharSequence, start: Int, end: Int, first: Boolean, l: Layout) { val spanned = text as Spanned if (!mIgnoreSpan && spanned.getSpanStart(this) == start) { // set paint val oldStyle = p.style val oldcolor = p.color p.style = Paint.Style.FILL p.color = bulletColor c.drawCircle((x + dir * 10).toFloat(), (top + bottom) / 2.0f, bulletRadius.toFloat(), p) // this is required if not the color and style is carried to other spans. p.color = oldcolor p.style = oldStyle } } }
lib/src/main/java/com/androidessence/lib/CustomBulletSpan.kt
3452271021
/* * 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 com.intellij.diff.comparison import com.intellij.diff.DiffTestCase import com.intellij.diff.fragments.* import com.intellij.diff.util.DiffUtil import com.intellij.diff.util.ThreeSide import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.util.Couple import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil class ComparisonUtilAutoTest : DiffTestCase() { val RUNS = 30 val MAX_LENGTH = 300 fun testChar() { doTestChar(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testWord() { doTestWord(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testLine() { doTestLine(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testLineSquashed() { doTestLineSquashed(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testLineTrimSquashed() { doTestLineTrimSquashed(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testMerge() { doTestMerge(System.currentTimeMillis(), RUNS, MAX_LENGTH) } private fun doTestLine(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val fragments = MANAGER.compareLinesInner(sequence1, sequence2, policy, INDICATOR) debugData.put("Fragments", fragments) checkResultLine(text1, text2, fragments, policy, true) } } private fun doTestLineSquashed(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val fragments = MANAGER.compareLinesInner(sequence1, sequence2, policy, INDICATOR) debugData.put("Fragments", fragments) val squashedFragments = MANAGER.squash(fragments) debugData.put("Squashed Fragments", squashedFragments) checkResultLine(text1, text2, squashedFragments, policy, false) } } private fun doTestLineTrimSquashed(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val fragments = MANAGER.compareLinesInner(sequence1, sequence2, policy, INDICATOR) debugData.put("Fragments", fragments) val processed = MANAGER.processBlocks(fragments, sequence1, sequence2, policy, true, true) debugData.put("Processed Fragments", processed) checkResultLine(text1, text2, processed, policy, false) } } private fun doTestChar(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.IGNORE_WHITESPACES) doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val fragments = MANAGER.compareChars(sequence1, sequence2, policy, INDICATOR) debugData.put("Fragments", fragments) checkResultChar(sequence1, sequence2, fragments, policy) } } private fun doTestWord(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val fragments = MANAGER.compareWords(sequence1, sequence2, policy, INDICATOR) debugData.put("Fragments", fragments) checkResultWord(sequence1, sequence2, fragments, policy) } } private fun doTestMerge(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest3(seed, runs, maxLength, policies) { text1, text2, text3, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val sequence3 = text3.charsSequence val fragments = MANAGER.compareLines(sequence1, sequence2, sequence3, policy, INDICATOR) val fineFragments = fragments.map { f -> val chunk1 = DiffUtil.getLinesContent(text1, f.startLine1, f.endLine1) val chunk2 = DiffUtil.getLinesContent(text2, f.startLine2, f.endLine2) val chunk3 = DiffUtil.getLinesContent(text3, f.startLine3, f.endLine3) val wordFragments = ByWord.compare(chunk1, chunk2, chunk3, policy, INDICATOR) MergeLineFragmentImpl(f, wordFragments) } debugData.put("Fragments", fineFragments) checkResultMerge(text1, text2, text3, fineFragments, policy) } } private fun doTest(seed: Long, runs: Int, maxLength: Int, policies: List<ComparisonPolicy>, test: (Document, Document, ComparisonPolicy, DiffTestCase.DebugData) -> Unit) { doAutoTest(seed, runs) { debugData -> debugData.put("MaxLength", maxLength) val text1 = DocumentImpl(generateText(maxLength)) val text2 = DocumentImpl(generateText(maxLength)) debugData.put("Text1", textToReadableFormat(text1.charsSequence)) debugData.put("Text2", textToReadableFormat(text2.charsSequence)) for (comparisonPolicy in policies) { debugData.put("Policy", comparisonPolicy) test(text1, text2, comparisonPolicy, debugData) } } } private fun doTest3(seed: Long, runs: Int, maxLength: Int, policies: List<ComparisonPolicy>, test: (Document, Document, Document, ComparisonPolicy, DiffTestCase.DebugData) -> Unit) { doAutoTest(seed, runs) { debugData -> debugData.put("MaxLength", maxLength) val text1 = DocumentImpl(generateText(maxLength)) val text2 = DocumentImpl(generateText(maxLength)) val text3 = DocumentImpl(generateText(maxLength)) debugData.put("Text1", textToReadableFormat(text1.charsSequence)) debugData.put("Text2", textToReadableFormat(text2.charsSequence)) debugData.put("Text3", textToReadableFormat(text3.charsSequence)) for (comparisonPolicy in policies) { debugData.put("Policy", comparisonPolicy) test(text1, text2, text2, comparisonPolicy, debugData) } } } private fun checkResultLine(text1: Document, text2: Document, fragments: List<LineFragment>, policy: ComparisonPolicy, allowNonSquashed: Boolean) { checkLineConsistency(text1, text2, fragments, allowNonSquashed) for (fragment in fragments) { if (fragment.innerFragments != null) { val sequence1 = text1.subsequence(fragment.startOffset1, fragment.endOffset1) val sequence2 = text2.subsequence(fragment.startOffset2, fragment.endOffset2) checkResultWord(sequence1, sequence2, fragment.innerFragments!!, policy) } } checkValidRanges(text1.charsSequence, text2.charsSequence, fragments, policy, true) checkCantTrimLines(text1, text2, fragments, policy, allowNonSquashed) } private fun checkResultWord(text1: CharSequence, text2: CharSequence, fragments: List<DiffFragment>, policy: ComparisonPolicy) { checkDiffConsistency(fragments) checkValidRanges(text1, text2, fragments, policy, false) } private fun checkResultChar(text1: CharSequence, text2: CharSequence, fragments: List<DiffFragment>, policy: ComparisonPolicy) { checkDiffConsistency(fragments) checkValidRanges(text1, text2, fragments, policy, false) } private fun checkResultMerge(text1: Document, text2: Document, text3: Document, fragments: List<MergeLineFragment>, policy: ComparisonPolicy) { checkLineConsistency3(text1, text2, text3, fragments) for (f in fragments) { val chunk1 = DiffUtil.getLinesContent(text1, f.startLine1, f.endLine1) val chunk2 = DiffUtil.getLinesContent(text2, f.startLine2, f.endLine2) val chunk3 = DiffUtil.getLinesContent(text3, f.startLine3, f.endLine3) checkDiffConsistency3(f.innerFragments!!) checkValidRanges3(chunk1, chunk2, chunk3, f.innerFragments!!, policy) } checkValidRanges3(text1, text2, text3, fragments, policy) checkCantTrimLines3(text1, text2, text3, fragments, policy) } private fun checkLineConsistency(text1: Document, text2: Document, fragments: List<LineFragment>, allowNonSquashed: Boolean) { var last1 = -1 var last2 = -1 for (fragment in fragments) { val startOffset1 = fragment.startOffset1 val startOffset2 = fragment.startOffset2 val endOffset1 = fragment.endOffset1 val endOffset2 = fragment.endOffset2 val start1 = fragment.startLine1 val start2 = fragment.startLine2 val end1 = fragment.endLine1 val end2 = fragment.endLine2 assertTrue(startOffset1 >= 0) assertTrue(startOffset2 >= 0) assertTrue(endOffset1 <= text1.textLength) assertTrue(endOffset2 <= text2.textLength) assertTrue(start1 >= 0) assertTrue(start2 >= 0) assertTrue(end1 <= getLineCount(text1)) assertTrue(end2 <= getLineCount(text2)) assertTrue(startOffset1 <= endOffset1) assertTrue(startOffset2 <= endOffset2) assertTrue(start1 <= end1) assertTrue(start2 <= end2) assertTrue(start1 != end1 || start2 != end2) assertTrue(allowNonSquashed || start1 != last1 || start2 != last2) checkLineOffsets(fragment, text1, text2) last1 = end1 last2 = end2 } } private fun checkLineConsistency3(text1: Document, text2: Document, text3: Document, fragments: List<MergeLineFragment>) { var last1 = -1 var last2 = -1 var last3 = -1 for (fragment in fragments) { val start1 = fragment.startLine1 val start2 = fragment.startLine2 val start3 = fragment.startLine3 val end1 = fragment.endLine1 val end2 = fragment.endLine2 val end3 = fragment.endLine3 assertTrue(start1 >= 0) assertTrue(start2 >= 0) assertTrue(start3 >= 0) assertTrue(end1 <= getLineCount(text1)) assertTrue(end2 <= getLineCount(text2)) assertTrue(end3 <= getLineCount(text3)) assertTrue(start1 <= end1) assertTrue(start2 <= end2) assertTrue(start3 <= end3) assertTrue(start1 != end1 || start2 != end2 || start3 != end3) assertTrue(start1 != last1 || start2 != last2 || start3 != last3) last1 = end1 last2 = end2 last3 = end3 } } private fun checkDiffConsistency(fragments: List<DiffFragment>) { var last1 = -1 var last2 = -1 for (diffFragment in fragments) { val start1 = diffFragment.startOffset1 val start2 = diffFragment.startOffset2 val end1 = diffFragment.endOffset1 val end2 = diffFragment.endOffset2 assertTrue(start1 <= end1) assertTrue(start2 <= end2) assertTrue(start1 != end1 || start2 != end2) assertTrue(start1 != last1 || start2 != last2) last1 = end1 last2 = end2 } } private fun checkDiffConsistency3(fragments: List<MergeWordFragment>) { var last1 = -1 var last2 = -1 var last3 = -1 for (diffFragment in fragments) { val start1 = diffFragment.startOffset1 val start2 = diffFragment.startOffset2 val start3 = diffFragment.startOffset3 val end1 = diffFragment.endOffset1 val end2 = diffFragment.endOffset2 val end3 = diffFragment.endOffset3 assertTrue(start1 <= end1) assertTrue(start2 <= end2) assertTrue(start3 <= end3) assertTrue(start1 != end1 || start2 != end2 || start3 != end3) assertTrue(start1 != last1 || start2 != last2 || start3 != last3) last1 = end1 last2 = end2 last3 = end3 } } private fun checkLineOffsets(fragment: LineFragment, before: Document, after: Document) { checkLineOffsets(before, fragment.startLine1, fragment.endLine1, fragment.startOffset1, fragment.endOffset1) checkLineOffsets(after, fragment.startLine2, fragment.endLine2, fragment.startOffset2, fragment.endOffset2) } private fun checkLineOffsets(document: Document, startLine: Int, endLine: Int, startOffset: Int, endOffset: Int) { if (startLine != endLine) { assertEquals(document.getLineStartOffset(startLine), startOffset) var offset = document.getLineEndOffset(endLine - 1) if (offset < document.textLength) offset++ assertEquals(offset, endOffset) } else { val offset = if (startLine == getLineCount(document)) document.textLength else document.getLineStartOffset(startLine) assertEquals(offset, startOffset) assertEquals(offset, endOffset) } } private fun checkValidRanges(text1: CharSequence, text2: CharSequence, fragments: List<DiffFragment>, policy: ComparisonPolicy, skipNewline: Boolean) { // TODO: better check for Trim spaces case ? val ignoreSpacesUnchanged = policy != ComparisonPolicy.DEFAULT val ignoreSpacesChanged = policy == ComparisonPolicy.IGNORE_WHITESPACES var last1 = 0 var last2 = 0 for (fragment in fragments) { val start1 = fragment.startOffset1 val start2 = fragment.startOffset2 val end1 = fragment.endOffset1 val end2 = fragment.endOffset2 val chunk1 = text1.subSequence(last1, start1) val chunk2 = text2.subSequence(last2, start2) assertEqualsCharSequences(chunk1, chunk2, ignoreSpacesUnchanged, skipNewline) val chunkContent1 = text1.subSequence(start1, end1) val chunkContent2 = text2.subSequence(start2, end2) if (!skipNewline) { assertNotEqualsCharSequences(chunkContent1, chunkContent2, ignoreSpacesChanged, skipNewline) } last1 = fragment.endOffset1 last2 = fragment.endOffset2 } val chunk1 = text1.subSequence(last1, text1.length) val chunk2 = text2.subSequence(last2, text2.length) assertEqualsCharSequences(chunk1, chunk2, ignoreSpacesUnchanged, skipNewline) } private fun checkValidRanges3(text1: Document, text2: Document, text3: Document, fragments: List<MergeLineFragment>, policy: ComparisonPolicy) { val ignoreSpaces = policy != ComparisonPolicy.DEFAULT var last1 = 0 var last2 = 0 var last3 = 0 for (fragment in fragments) { val start1 = fragment.startLine1 val start2 = fragment.startLine2 val start3 = fragment.startLine3 val content1 = DiffUtil.getLinesContent(text1, last1, start1) val content2 = DiffUtil.getLinesContent(text2, last2, start2) val content3 = DiffUtil.getLinesContent(text3, last3, start3) assertEqualsCharSequences(content2, content1, ignoreSpaces, false) assertEqualsCharSequences(content2, content3, ignoreSpaces, false) last1 = fragment.endLine1 last2 = fragment.endLine2 last3 = fragment.endLine3 } val content1 = DiffUtil.getLinesContent(text1, last1, getLineCount(text1)) val content2 = DiffUtil.getLinesContent(text2, last2, getLineCount(text2)) val content3 = DiffUtil.getLinesContent(text3, last3, getLineCount(text3)) assertEqualsCharSequences(content2, content1, ignoreSpaces, false) assertEqualsCharSequences(content2, content3, ignoreSpaces, false) } private fun checkValidRanges3(text1: CharSequence, text2: CharSequence, text3: CharSequence, fragments: List<MergeWordFragment>, policy: ComparisonPolicy) { val ignoreSpacesUnchanged = policy != ComparisonPolicy.DEFAULT val ignoreSpacesChanged = policy == ComparisonPolicy.IGNORE_WHITESPACES var last1 = 0 var last2 = 0 var last3 = 0 for (fragment in fragments) { val start1 = fragment.startOffset1 val start2 = fragment.startOffset2 val start3 = fragment.startOffset3 val end1 = fragment.endOffset1 val end2 = fragment.endOffset2 val end3 = fragment.endOffset3 val content1 = text1.subSequence(last1, start1) val content2 = text2.subSequence(last2, start2) val content3 = text3.subSequence(last3, start3) assertEqualsCharSequences(content2, content1, ignoreSpacesUnchanged, false) assertEqualsCharSequences(content2, content3, ignoreSpacesUnchanged, false) val chunkContent1 = text1.subSequence(start1, end1) val chunkContent2 = text2.subSequence(start2, end2) val chunkContent3 = text3.subSequence(start3, end3) assertFalse(isEqualsCharSequences(chunkContent2, chunkContent1, ignoreSpacesChanged) && isEqualsCharSequences(chunkContent2, chunkContent3, ignoreSpacesChanged)) last1 = fragment.endOffset1 last2 = fragment.endOffset2 last3 = fragment.endOffset3 } val content1 = text1.subSequence(last1, text1.length) val content2 = text2.subSequence(last2, text2.length) val content3 = text3.subSequence(last3, text3.length) assertEqualsCharSequences(content2, content1, ignoreSpacesUnchanged, false) assertEqualsCharSequences(content2, content3, ignoreSpacesUnchanged, false) } private fun checkCantTrimLines(text1: Document, text2: Document, fragments: List<LineFragment>, policy: ComparisonPolicy, allowNonSquashed: Boolean) { for (fragment in fragments) { val sequence1 = getFirstLastLines(text1, fragment.startLine1, fragment.endLine1) val sequence2 = getFirstLastLines(text2, fragment.startLine2, fragment.endLine2) if (sequence1 == null || sequence2 == null) continue checkNonEqualsIfLongEnough(sequence1.first, sequence2.first, policy, allowNonSquashed) checkNonEqualsIfLongEnough(sequence1.second, sequence2.second, policy, allowNonSquashed) } } private fun checkCantTrimLines3(text1: Document, text2: Document, text3: Document, fragments: List<MergeLineFragment>, policy: ComparisonPolicy) { for (fragment in fragments) { val sequence1 = getFirstLastLines(text1, fragment.startLine1, fragment.endLine1) val sequence2 = getFirstLastLines(text2, fragment.startLine2, fragment.endLine2) val sequence3 = getFirstLastLines(text3, fragment.startLine3, fragment.endLine3) if (sequence1 == null || sequence2 == null || sequence3 == null) continue assertFalse(MANAGER.isEquals(sequence2.first, sequence1.first, policy) && MANAGER.isEquals(sequence2.first, sequence3.first, policy)) assertFalse(MANAGER.isEquals(sequence2.second, sequence1.second, policy) && MANAGER.isEquals(sequence2.second, sequence3.second, policy)) } } private fun checkNonEqualsIfLongEnough(line1: CharSequence, line2: CharSequence, policy: ComparisonPolicy, allowNonSquashed: Boolean) { // in non-squashed blocks non-trimmed elements are possible if (allowNonSquashed) { if (policy != ComparisonPolicy.IGNORE_WHITESPACES) return if (countNonWhitespaceCharacters(line1) <= Registry.get("diff.unimportant.line.char.count").asInteger()) return if (countNonWhitespaceCharacters(line2) <= Registry.get("diff.unimportant.line.char.count").asInteger()) return } assertFalse(MANAGER.isEquals(line1, line2, policy)) } private fun countNonWhitespaceCharacters(line: CharSequence): Int { return (0 until line.length).count { !StringUtil.isWhiteSpace(line[it]) } } private fun getFirstLastLines(text: Document, start: Int, end: Int): Couple<CharSequence>? { if (start == end) return null val firstLineRange = DiffUtil.getLinesRange(text, start, start + 1) val lastLineRange = DiffUtil.getLinesRange(text, end - 1, end) val firstLine = firstLineRange.subSequence(text.charsSequence) val lastLine = lastLineRange.subSequence(text.charsSequence) return Couple.of(firstLine, lastLine) } private fun Document.subsequence(start: Int, end: Int): CharSequence { return this.charsSequence.subSequence(start, end) } private val MergeLineFragment.startLine1: Int get() = this.getStartLine(ThreeSide.LEFT) private val MergeLineFragment.startLine2: Int get() = this.getStartLine(ThreeSide.BASE) private val MergeLineFragment.startLine3: Int get() = this.getStartLine(ThreeSide.RIGHT) private val MergeLineFragment.endLine1: Int get() = this.getEndLine(ThreeSide.LEFT) private val MergeLineFragment.endLine2: Int get() = this.getEndLine(ThreeSide.BASE) private val MergeLineFragment.endLine3: Int get() = this.getEndLine(ThreeSide.RIGHT) private val MergeWordFragment.startOffset1: Int get() = this.getStartOffset(ThreeSide.LEFT) private val MergeWordFragment.startOffset2: Int get() = this.getStartOffset(ThreeSide.BASE) private val MergeWordFragment.startOffset3: Int get() = this.getStartOffset(ThreeSide.RIGHT) private val MergeWordFragment.endOffset1: Int get() = this.getEndOffset(ThreeSide.LEFT) private val MergeWordFragment.endOffset2: Int get() = this.getEndOffset(ThreeSide.BASE) private val MergeWordFragment.endOffset3: Int get() = this.getEndOffset(ThreeSide.RIGHT) }
platform/diff-impl/tests/com/intellij/diff/comparison/ComparisonUtilAutoTest.kt
248936505
package com.intellij.configurationStore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.components.impl.ServiceManagerImpl import com.intellij.openapi.components.stateStore import com.intellij.openapi.util.io.FileUtil import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.testFramework.runInEdtAndWait import com.intellij.util.io.delete import org.junit.ClassRule import org.junit.Test import java.nio.file.Path import java.nio.file.Paths private val testData: Path get() = Paths.get(PathManagerEx.getHomePath(DoNotSaveDefaultsTest::class.java), FileUtil.toSystemDependentName("platform/configuration-store-impl/testSrc")) class DoNotSaveDefaultsTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule() init { Paths.get(PathManager.getConfigPath()).delete() } } @Test fun test() { val app = ApplicationManager.getApplication() as ApplicationImpl val directory = app.stateStore.stateStorageManager.expandMacros(APP_CONFIG) val dirPath = Paths.get(directory) val useModCountOldValue = System.getProperty("store.save.use.modificationCount") // wake up ServiceManagerImpl.processAllImplementationClasses(app, { clazz, pluginDescriptor -> app.picoContainer.getComponentInstance(clazz.name) true }) try { System.setProperty("store.save.use.modificationCount", "false") app.doNotSave(false) runInEdtAndWait { app.saveAll() } } finally { System.setProperty("store.save.use.modificationCount", useModCountOldValue ?: "false") app.doNotSave(true) } println(directory) val directoryTree = printDirectoryTree(dirPath, setOf( "path.macros.xml" /* todo EP to register (provide) macro dynamically */, "stubIndex.xml" /* low-level non-roamable stuff */, "usage.statistics.xml" /* SHOW_NOTIFICATION_ATTR in internal mode */, "feature.usage.statistics.xml" /* non-roamable usage counters */, "tomee.extensions.xml", "jboss.extensions.xml", "glassfish.extensions.xml" /* javaee non-roamable stuff, it will be better to fix it */, "dimensions.xml" /* non-roamable sizes of window, dialogs, etc. */, "debugger.renderers.xml", "debugger.xml" /* todo */ )) println(directoryTree) assertThat(directoryTree).toMatchSnapshot(testData.resolve("DoNotSaveDefaults.snap.txt")) } }
platform/configuration-store-impl/testSrc/DoNotSaveDefaults.kt
2067406322
// 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.webSymbols.query import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.webSymbols.WebSymbolsScope import com.intellij.webSymbols.context.WebSymbolsContext import com.intellij.webSymbols.context.WebSymbolsContextRulesProvider interface WebSymbolsQueryConfigurator { fun getScope(project: Project, element: PsiElement?, context: WebSymbolsContext, allowResolve: Boolean): List<WebSymbolsScope> = emptyList() fun getContextRulesProviders(project: Project, dir: VirtualFile): List<WebSymbolsContextRulesProvider> = emptyList() fun getNameConversionRulesProviders(project: Project, element: PsiElement?, context: WebSymbolsContext): List<WebSymbolNameConversionRulesProvider> = emptyList() fun beforeQueryExecutorCreation(project: Project) { } companion object { internal val EP_NAME = ExtensionPointName<WebSymbolsQueryConfigurator>("com.intellij.webSymbols.queryConfigurator") } }
platform/webSymbols/src/com/intellij/webSymbols/query/WebSymbolsQueryConfigurator.kt
1153374055
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.macrobenchmark_codelab.ui.home.search import android.content.res.Configuration import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Add import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.constraintlayout.compose.ChainStyle import androidx.constraintlayout.compose.ConstraintLayout import com.example.macrobenchmark_codelab.R import com.example.macrobenchmark_codelab.model.Filter import com.example.macrobenchmark_codelab.model.Snack import com.example.macrobenchmark_codelab.model.snacks import com.example.macrobenchmark_codelab.ui.components.FilterBar import com.example.macrobenchmark_codelab.ui.components.JetsnackButton import com.example.macrobenchmark_codelab.ui.components.JetsnackDivider import com.example.macrobenchmark_codelab.ui.components.JetsnackSurface import com.example.macrobenchmark_codelab.ui.components.SnackImage import com.example.macrobenchmark_codelab.ui.theme.JetsnackTheme import com.example.macrobenchmark_codelab.ui.utils.formatPrice @Composable fun SearchResults( searchResults: List<Snack>, filters: List<Filter>, onSnackClick: (Long) -> Unit ) { Column { FilterBar(filters, onShowFilters = {}) Text( text = stringResource(R.string.search_count, searchResults.size), style = MaterialTheme.typography.h6, color = JetsnackTheme.colors.textPrimary, modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp) ) LazyColumn { itemsIndexed(searchResults) { index, snack -> SearchResult(snack, onSnackClick, index != 0) } } } } @Composable private fun SearchResult( snack: Snack, onSnackClick: (Long) -> Unit, showDivider: Boolean, modifier: Modifier = Modifier ) { ConstraintLayout( modifier = modifier .fillMaxWidth() .clickable { onSnackClick(snack.id) } .padding(horizontal = 24.dp) ) { val (divider, image, name, tag, priceSpacer, price, add) = createRefs() createVerticalChain(name, tag, priceSpacer, price, chainStyle = ChainStyle.Packed) if (showDivider) { JetsnackDivider( Modifier.constrainAs(divider) { linkTo(start = parent.start, end = parent.end) top.linkTo(parent.top) } ) } SnackImage( imageUrl = snack.imageUrl, contentDescription = null, modifier = Modifier .size(100.dp) .constrainAs(image) { linkTo( top = parent.top, topMargin = 16.dp, bottom = parent.bottom, bottomMargin = 16.dp ) start.linkTo(parent.start) } ) Text( text = snack.name, style = MaterialTheme.typography.subtitle1, color = JetsnackTheme.colors.textSecondary, modifier = Modifier.constrainAs(name) { linkTo( start = image.end, startMargin = 16.dp, end = add.start, endMargin = 16.dp, bias = 0f ) } ) Text( text = snack.tagline, style = MaterialTheme.typography.body1, color = JetsnackTheme.colors.textHelp, modifier = Modifier.constrainAs(tag) { linkTo( start = image.end, startMargin = 16.dp, end = add.start, endMargin = 16.dp, bias = 0f ) } ) Spacer( Modifier .height(8.dp) .constrainAs(priceSpacer) { linkTo(top = tag.bottom, bottom = price.top) } ) Text( text = formatPrice(snack.price), style = MaterialTheme.typography.subtitle1, color = JetsnackTheme.colors.textPrimary, modifier = Modifier.constrainAs(price) { linkTo( start = image.end, startMargin = 16.dp, end = add.start, endMargin = 16.dp, bias = 0f ) } ) JetsnackButton( onClick = { /* todo */ }, shape = CircleShape, contentPadding = PaddingValues(0.dp), modifier = Modifier .size(36.dp) .constrainAs(add) { linkTo(top = parent.top, bottom = parent.bottom) end.linkTo(parent.end) } ) { Icon( imageVector = Icons.Outlined.Add, contentDescription = stringResource(R.string.label_add) ) } } } @Composable fun NoResults( query: String, modifier: Modifier = Modifier ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier .fillMaxSize() .wrapContentSize() .padding(24.dp) ) { Image( painterResource(R.drawable.empty_state_search), contentDescription = null ) Spacer(Modifier.height(24.dp)) Text( text = stringResource(R.string.search_no_matches, query), style = MaterialTheme.typography.subtitle1, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth() ) Spacer(Modifier.height(16.dp)) Text( text = stringResource(R.string.search_no_matches_retry), style = MaterialTheme.typography.body2, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth() ) } } @Preview("default") @Preview("dark theme", uiMode = Configuration.UI_MODE_NIGHT_YES) @Preview("large font", fontScale = 2f) @Composable private fun SearchResultPreview() { JetsnackTheme { JetsnackSurface { SearchResult( snack = snacks[0], onSnackClick = { }, showDivider = false ) } } }
benchmarking/app/src/main/java/com/example/macrobenchmark_codelab/ui/home/search/Results.kt
76297935
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.execution.build.output import com.intellij.build.BuildProgressListener import com.intellij.build.events.BuildEvent import com.intellij.build.events.DuplicateMessageAware import com.intellij.build.events.FinishEvent import com.intellij.build.events.StartEvent import com.intellij.build.events.impl.OutputBuildEventImpl import com.intellij.build.output.BuildOutputInstantReaderImpl import com.intellij.build.output.BuildOutputParser import com.intellij.build.output.LineProcessor import com.intellij.openapi.externalSystem.service.execution.AbstractOutputMessageDispatcher import com.intellij.openapi.externalSystem.service.execution.ExternalSystemOutputDispatcherFactory import com.intellij.openapi.externalSystem.service.execution.ExternalSystemOutputMessageDispatcher import org.apache.commons.lang.ClassUtils import org.gradle.api.logging.LogLevel import org.jetbrains.plugins.gradle.util.GradleConstants import java.lang.reflect.InvocationHandler import java.lang.reflect.Method import java.lang.reflect.Proxy import java.util.concurrent.CompletableFuture class GradleOutputDispatcherFactory : ExternalSystemOutputDispatcherFactory { override val externalSystemId: Any? = GradleConstants.SYSTEM_ID override fun create(buildId: Any, buildProgressListener: BuildProgressListener, appendOutputToMainConsole: Boolean, parsers: List<BuildOutputParser>): ExternalSystemOutputMessageDispatcher { return GradleOutputMessageDispatcher(buildId, buildProgressListener, appendOutputToMainConsole, parsers) } private class GradleOutputMessageDispatcher(private val buildId: Any, private val myBuildProgressListener: BuildProgressListener, private val appendOutputToMainConsole: Boolean, private val parsers: List<BuildOutputParser>) : AbstractOutputMessageDispatcher( myBuildProgressListener) { override var stdOut: Boolean = true private val lineProcessor: LineProcessor private val myRootReader: BuildOutputInstantReaderImpl private var myCurrentReader: BuildOutputInstantReaderImpl private val tasksOutputReaders = mutableMapOf<String, BuildOutputInstantReaderImpl>() private val tasksEventIds = mutableMapOf<String, Any>() init { val deferredRootEvents = mutableListOf<BuildEvent>() myRootReader = object : BuildOutputInstantReaderImpl(buildId, buildId, BuildProgressListener { _: Any, event: BuildEvent -> var buildEvent = event val parentId = buildEvent.parentId if (parentId != buildId && parentId is String) { val taskEventId = tasksEventIds[parentId] if (taskEventId != null) { buildEvent = BuildEventInvocationHandler.wrap(event, taskEventId) } } if (buildEvent is DuplicateMessageAware) { deferredRootEvents += buildEvent } else { myBuildProgressListener.onEvent(buildId, buildEvent) } }, parsers) { override fun closeAndGetFuture(): CompletableFuture<Unit> = super.closeAndGetFuture().whenComplete { _, _ -> deferredRootEvents.forEach { myBuildProgressListener.onEvent(buildId, it) } } } var isBuildException = false myCurrentReader = myRootReader lineProcessor = object : LineProcessor() { override fun process(line: String) { val cleanLine = removeLoggerPrefix(line) // skip Gradle test runner output if (cleanLine.startsWith("<ijLog>")) return if (cleanLine.startsWith("> Task :")) { isBuildException = false val taskName = cleanLine.removePrefix("> Task ").substringBefore(' ') myCurrentReader = tasksOutputReaders[taskName] ?: myRootReader } else if (cleanLine.startsWith("> Configure") || cleanLine.startsWith("FAILURE: Build failed") || cleanLine.startsWith("CONFIGURE SUCCESSFUL") || cleanLine.startsWith("BUILD SUCCESSFUL")) { isBuildException = false myCurrentReader = myRootReader } if (cleanLine == "* Exception is:") isBuildException = true if (isBuildException && myCurrentReader == myRootReader) return myCurrentReader.appendln(cleanLine) if (myCurrentReader != myRootReader) { val parentEventId = myCurrentReader.parentEventId myBuildProgressListener.onEvent(buildId, OutputBuildEventImpl(parentEventId, line + '\n', stdOut)) } } } } override fun onEvent(buildId: Any, event: BuildEvent) { super.onEvent(buildId, event) if (event.parentId != buildId) return if (event is StartEvent) { tasksOutputReaders[event.message]?.close() // multiple invocations of the same task during the build session val parentEventId = event.id tasksOutputReaders[event.message] = BuildOutputInstantReaderImpl(buildId, parentEventId, myBuildProgressListener, parsers) tasksEventIds[event.message] = parentEventId } else if (event is FinishEvent) { // unreceived output is still possible after finish task event but w/o long pauses between chunks // also no output expected for up-to-date tasks tasksOutputReaders[event.message]?.disableActiveReading() } } override fun closeAndGetFuture(): CompletableFuture<*> { lineProcessor.close() val futures = mutableListOf<CompletableFuture<Unit>>() tasksOutputReaders.forEach { (_, reader) -> reader.closeAndGetFuture().let { futures += it } } futures += myRootReader.closeAndGetFuture() tasksOutputReaders.clear() return CompletableFuture.allOf(*futures.toTypedArray()) } override fun append(csq: CharSequence): Appendable { if (appendOutputToMainConsole) { myBuildProgressListener.onEvent(buildId, OutputBuildEventImpl(buildId, csq.toString(), stdOut)) } lineProcessor.append(csq) return this } override fun append(csq: CharSequence, start: Int, end: Int): Appendable { if (appendOutputToMainConsole) { myBuildProgressListener.onEvent(buildId, OutputBuildEventImpl(buildId, csq.subSequence(start, end).toString(), stdOut)) } lineProcessor.append(csq, start, end) return this } override fun append(c: Char): Appendable { if (appendOutputToMainConsole) { myBuildProgressListener.onEvent(buildId, OutputBuildEventImpl(buildId, c.toString(), stdOut)) } lineProcessor.append(c) return this } private fun removeLoggerPrefix(line: String): String { val list = mutableListOf<String>() list += line.split(' ', limit = 3) if (list.size < 3) return line if (!list[1].startsWith('[') || !list[1].endsWith(']')) return line if (!list[2].startsWith('[')) return line if (!list[2].endsWith(']')) { val i = list[2].indexOf(']') if (i == -1) return line list[2] = list[2].substring(0, i + 1) if (!list[2].endsWith(']')) return line } try { LogLevel.valueOf(list[1].drop(1).dropLast(1)) } catch (e: Exception) { return line } return line.drop(list.sumBy { it.length } + 2).trimStart() } private class BuildEventInvocationHandler(private val buildEvent: BuildEvent, private val parentEventId: Any) : InvocationHandler { override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any? { if (method?.name.equals("getParentId")) return parentEventId return method?.invoke(buildEvent, *args ?: arrayOfNulls<Any>(0)) } companion object { fun wrap(buildEvent: BuildEvent, parentEventId: Any): BuildEvent { val classLoader = buildEvent.javaClass.classLoader val interfaces = ClassUtils.getAllInterfaces(buildEvent.javaClass) .filterIsInstance(Class::class.java) .toTypedArray() val invocationHandler = BuildEventInvocationHandler(buildEvent, parentEventId) return Proxy.newProxyInstance(classLoader, interfaces, invocationHandler) as BuildEvent } } } } }
plugins/gradle/src/org/jetbrains/plugins/gradle/execution/build/output/GradleOutputDispatcherFactory.kt
2933531606
/** <slate_header> url: www.slatekit.com git: www.github.com/code-helix/slatekit org: www.codehelix.co author: Kishore Reddy copyright: 2016 CodeHelix Solutions Inc. license: refer to website and/or github about: A Kotlin utility library, tool-kit and server backend. mantra: Simplicity above all else </slate_header> */ package test.apis import org.junit.Assert import org.junit.Test import slatekit.apis.core.Roles /** * Created by kishorereddy on 6/12/17. */ class Api_Roles_Tests : ApiTestsBase() { @Test fun is_authed() { Assert.assertEquals(true, Roles(listOf("dev")).isAuthed) } @Test fun is_empty() { Assert.assertEquals(true, Roles(listOf()).isEmpty) } @Test fun allow_guest() { Assert.assertEquals(true, Roles(listOf(slatekit.common.auth.Roles.GUEST)).allowGuest) } @Test fun allow_all() { Assert.assertEquals(false, Roles(listOf(slatekit.common.auth.Roles.ALL)).allowGuest) } @Test fun can_refer_to_parent() { val action = Roles(listOf(slatekit.common.auth.Roles.PARENT)) val api = Roles(listOf("ops")) val roles = action.orElse(api) Assert.assertEquals("ops", roles.all.first()) } }
src/lib/kotlin/slatekit-tests/src/test/kotlin/test/apis/Api_Roles_Tests.kt
1527563222
/* * Copyright 2015-2019 The twitlatte authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.moko256.latte.client.base.entity /** * Created by moko256 on 2019/02/15. * * @author moko256 */ data class UpdateStatus( var inReplyToStatusId: Long, var contentWarning: String?, var context: String, var imageIdList: List<Long>?, var isPossiblySensitive: Boolean, var location: Pair<Double, Double>?, var visibility: String?, var pollList: List<String>?, var isPollSelectableMultiple: Boolean, var isPollHideTotalsUntilExpired: Boolean, var pollExpiredSecond: Long )
component_client_base/src/main/java/com/github/moko256/latte/client/base/entity/UpdateStatus.kt
2145424674
/* * Copyright 2017 Rod MacKenzie. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.rodm.teamcity.gradle.scripts.server import jetbrains.buildServer.serverSide.BuildTypeTemplate import jetbrains.buildServer.serverSide.SBuildType import java.util.LinkedHashSet class ScriptUsage { private val buildTypes = LinkedHashSet<SBuildType>() private val buildTemplates = LinkedHashSet<BuildTypeTemplate>() fun getBuildTypes() = buildTypes fun addBuildType(buildType: SBuildType) { buildTypes.add(buildType) } fun getBuildTemplates() = buildTemplates fun addBuildTemplate(buildTemplate: BuildTypeTemplate) { buildTemplates.add(buildTemplate) } }
server/src/main/kotlin/com/github/rodm/teamcity/gradle/scripts/server/ScriptUsage.kt
1332241016
package com.dbflow5.query import com.dbflow5.config.FlowLog import com.dbflow5.database.DatabaseStatement import com.dbflow5.database.DatabaseStatementWrapper import com.dbflow5.database.DatabaseWrapper import com.dbflow5.database.FlowCursor import com.dbflow5.database.SQLiteException import com.dbflow5.longForQuery import com.dbflow5.runtime.NotifyDistributor import com.dbflow5.stringForQuery import com.dbflow5.structure.ChangeAction /** * Description: Base implementation of something that can be queried from the database. */ abstract class BaseQueriable<TModel : Any> protected constructor( /** * @return The table associated with this INSERT */ val table: Class<TModel>) : Queriable, Actionable { abstract override val primaryAction: ChangeAction override fun longValue(databaseWrapper: DatabaseWrapper): Long { try { val query = query FlowLog.log(FlowLog.Level.V, "Executing query: $query") return longForQuery(databaseWrapper, query) } catch (sde: SQLiteException) { // catch exception here, log it but return 0; FlowLog.logWarning(sde) } return 0 } override fun stringValue(databaseWrapper: DatabaseWrapper): String? { try { val query = query FlowLog.log(FlowLog.Level.V, "Executing query: $query") return stringForQuery(databaseWrapper, query) } catch (sde: SQLiteException) { // catch exception here, log it but return null; FlowLog.logWarning(sde) } return null } override fun hasData(databaseWrapper: DatabaseWrapper): Boolean = longValue(databaseWrapper) > 0 override fun cursor(databaseWrapper: DatabaseWrapper): FlowCursor? { if (primaryAction == ChangeAction.INSERT) { // inserting, let's compile and insert compileStatement(databaseWrapper).use { it.executeInsert() } } else { val query = query FlowLog.log(FlowLog.Level.V, "Executing query: " + query) databaseWrapper.execSQL(query) } return null } override fun executeInsert(databaseWrapper: DatabaseWrapper): Long = compileStatement(databaseWrapper).use { it.executeInsert() } override fun execute(databaseWrapper: DatabaseWrapper) { val cursor = cursor(databaseWrapper) if (cursor != null) { cursor.close() } else { // we dont query, we're executing something here. NotifyDistributor.get().notifyTableChanged(table, primaryAction) } } override fun compileStatement(databaseWrapper: DatabaseWrapper): DatabaseStatement { val query = query FlowLog.log(FlowLog.Level.V, "Compiling Query Into Statement: " + query) return DatabaseStatementWrapper(databaseWrapper.compileStatement(query), this) } override fun toString(): String = query }
lib/src/main/kotlin/com/dbflow5/query/BaseQueriable.kt
837161133
/** <slate_header> url: www.slatekit.com git: www.github.com/code-helix/slatekit org: www.codehelix.co author: Kishore Reddy copyright: 2016 CodeHelix Solutions Inc. license: refer to website and/or github about: A Kotlin utility library, tool-kit and server backend. mantra: Simplicity above all else </slate_header> */ import kotlinx.coroutines.Deferred import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import kotlinx.coroutines.delay import slatekit.async.coroutines.AsyncContextCoroutine import slatekit.async.futures.AsyncContextFuture import slatekit.entities.repo.EntityRepo import slatekit.entities.services.EntityService import slatekit.async.futures.Future import slatekit.async.futures.await import java.time.LocalDateTime import java.util.concurrent.CompletableFuture import kotlin.system.measureTimeMillis suspend fun main(args:Array<String>) { testCompose_Via_Futures().await() println("\n====================") testCompose_Via_Coroutines().await() } suspend fun testCoRoutines() { val asyncScope = AsyncContextCoroutine() val svc = EntityService<User>(EntityRepo<User>(mutableListOf(), asyncScope), asyncScope) val futures = listOf( svc.create(User(0, "user_1")), svc.create(User(0, "user_2")), svc.create(User(0, "user_3")) ) futures.forEach{ it.await() } val member = EntityService::class.members.first { it.name == "all" } val result = member.call(svc) when(result) { is Future<*> -> { val v = result.await() println(v) } else -> println(result) } svc.all().await().forEach { println(it) } //svc.all().forEach { println(it) } println("done with suspend") } fun testCompose_Via_Futures(): Future<String> { val f0 = CompletableFuture.supplyAsync { println("JAVA FUTURES ================\n") val f1 = CompletableFuture.supplyAsync { println("f1: loading user : begin : " + LocalDateTime.now().toString()) Thread.sleep(2000L) println("f1: loaded user : end : " + LocalDateTime.now().toString()) "user_01" } val f2 = f1.thenApply { it -> println("\n") println("f2: updating user : begin : " + LocalDateTime.now().toString()) Thread.sleep(3000L) println("f2: updated user : end : " + LocalDateTime.now().toString()) "f2: updated user: $it" } val f3 = f2.thenCompose { it -> println("\n") println("f3: logging user : begin : " + LocalDateTime.now().toString()) Thread.sleep(2000L) println("f3: logged user : end : " + LocalDateTime.now().toString()) CompletableFuture.completedFuture("f3:logged: $it") } val result = f3.get() println() println(result) result } return f0 } suspend fun testCompose_Via_Coroutines(): Deferred<String> { val f0 = GlobalScope.async { println("KOTLIN COROUTINES ================\n") val f1 = GlobalScope.async { println("f1: loading user : begin : " + LocalDateTime.now().toString()) delay(2000L) println("f1: loaded user : end : " + LocalDateTime.now().toString()) "user_01" } val f1Result = f1.await() val f2 = GlobalScope.async { val it = f1Result println("\n") println("f2: updating user : begin : " + LocalDateTime.now().toString()) delay(3000L) println("f2: updated user : end : " + LocalDateTime.now().toString()) "f2: updated user: $it" } val f2Result = f2.await() val f3 = GlobalScope.async { val it = f2Result println("\n") println("f3: logging user : begin : " + LocalDateTime.now().toString()) delay(2000L) println("f3: logged user : end : " + LocalDateTime.now().toString()) "f3:logged: $it" } val result = f3.await() println() println(result) result } return f0 } fun testFutures(){ val f1 = CompletableFuture.completedFuture(123) val f2 = f1.thenApply { it -> it + 1 } val f3 = f1.thenCompose { v -> CompletableFuture.completedFuture(v + 2) } val f4 = f1.thenAccept { it -> it + 3 } f3.handle { t, x -> println(t) println(x) } val f1Val = f1.get() val f2Val = f2.get() val f3Val = f3.get() val f4Val = f4.get() println(f1Val) println(f2Val) println(f3Val) println(f4Val) } suspend fun testMeasure(){ val time = measureTimeMillis { println("before 1") val one = doSomethingUsefulOne() println("before 2") val two = doSomethingUsefulTwo() println("The answer is ${one + two}") } //test_runBlocking() //Thread.sleep(2000) }
test/coroutine-tests/src/main/kotlin/app.kt
4221002274
/* * Copyright (c) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.chromeos.videocompositionsample.presentation.ui.base import androidx.fragment.app.Fragment import dev.chromeos.videocompositionsample.presentation.VideoCompositionSampleApp import dev.chromeos.videocompositionsample.presentation.di.AppComponent import dev.chromeos.videocompositionsample.presentation.tools.exception.ErrorModel import dev.chromeos.videocompositionsample.presentation.tools.info.MessageModel import dev.chromeos.videocompositionsample.presentation.tools.logger.ILogger import dev.chromeos.videocompositionsample.presentation.ui.Navigator import io.reactivex.disposables.Disposable import javax.inject.Inject open class BaseFragment: Fragment(), IBaseView { @Inject lateinit var navigator: Navigator @Inject lateinit var logger: ILogger protected val component: AppComponent by lazy { ((activity as? BaseActivity)?.application as? VideoCompositionSampleApp) ?.appComponent ?: throw IllegalStateException("Exception while instantiating fragment component.") } override fun showProgress(disposable: Disposable?, withPercent: Boolean) { (activity as? BaseActivity)?.showProgress(disposable) } override fun showProgress(withPercent: Boolean) { (activity as? BaseActivity)?.showProgress(withPercent) } override fun setProgressPercent(percent: Int) { (activity as? BaseActivity)?.setProgressPercent(percent) } override fun hideProgress() { (activity as? BaseActivity)?.hideProgress() } override fun showError(errorModel: ErrorModel) { showError(errorModel.getMessage(requireContext())) } override fun showError(message: String) { if (activity is BaseActivity) (activity as BaseActivity).onShowError(message) } override fun onShowMessage(message: String) { if (activity is BaseActivity) (activity as BaseActivity).onShowMessage(message) } override fun onShowMessage(messageModel: MessageModel) { if (activity is BaseActivity) (activity as BaseActivity).onShowMessage(messageModel) } fun removeAllFragment() { if (activity is BaseActivity) (activity as BaseActivity).removeAllFragment() } }
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/ui/base/BaseFragment.kt
3723046596
package net.ndrei.teslacorelib.gui import net.minecraft.entity.player.EntityPlayer import net.minecraft.util.math.BlockPos import net.minecraft.world.World import net.minecraftforge.fml.common.network.IGuiHandler import net.ndrei.teslacorelib.capabilities.TeslaCoreCapabilities /** * Created by CF on 2017-06-28. */ class TeslaCoreGuiProxy : IGuiHandler { override fun getServerGuiElement(id: Int, player: EntityPlayer, world: World, x: Int, y: Int, z: Int): Any? { val pos = BlockPos(x, y, z) val te = world.getTileEntity(pos) if (te != null && te.hasCapability(TeslaCoreCapabilities.CAPABILITY_GUI_CONTAINER, null)) { val provider = te.getCapability(TeslaCoreCapabilities.CAPABILITY_GUI_CONTAINER, null) if (provider != null) { return provider.getContainer(id, player) } } return null } override fun getClientGuiElement(id: Int, player: EntityPlayer, world: World, x: Int, y: Int, z: Int): Any? { val pos = BlockPos(x, y, z) val te = world.getTileEntity(pos) if (te != null && te.hasCapability(TeslaCoreCapabilities.CAPABILITY_GUI_CONTAINER, null)) { val provider = te.getCapability(TeslaCoreCapabilities.CAPABILITY_GUI_CONTAINER, null) if (provider != null) { return provider.getGuiContainer(id, player) } } return null } }
src/main/kotlin/net/ndrei/teslacorelib/gui/TeslaCoreGuiProxy.kt
4125720603
// FILE: 1.kt package test inline fun <R> doCall(p: () -> R) { p() } // FILE: 2.kt import test.* class A { var result = 0; var field: Int get() { doCall { return 1 } return 2 } set(v: Int) { doCall { result = v / 2 return } result = v } } fun box(): String { val a = A() if (a.field != 1) return "fail 1: ${a.field}" a.field = 4 if (a.result != 2) return "fail 2: ${a.result}" return "OK" }
backend.native/tests/external/codegen/boxInline/nonLocalReturns/propertyAccessors.kt
2793453232
package com.rizafu.coachmark import android.content.res.Resources import android.view.View import android.view.ViewTreeObserver /** * Created by RizaFu on 11/12/16. */ internal object ViewUtils { fun pxToDp(px: Int): Int { return (px / Resources.getSystem().displayMetrics.density).toInt() } fun dpToPx(dp: Int): Int { return (dp * Resources.getSystem().displayMetrics.density).toInt() } fun doAfterLayout(view: View, listen: () -> Unit) { val listener = object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { val viewTreeObserver = view.viewTreeObserver viewTreeObserver.removeOnGlobalLayoutListener(this) listen.invoke() } } view.viewTreeObserver.addOnGlobalLayoutListener(listener) } }
coachmark/src/main/java/com/rizafu/coachmark/ViewUtils.kt
3660415701
// IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import java.io.* import kotlin.test.* data class Foo(val value: String) : Serializable fun box(): String { val baos = ByteArrayOutputStream() val oos = ObjectOutputStream(baos) oos.writeObject(Foo("abacaba")::value) oos.close() val bais = ByteArrayInputStream(baos.toByteArray()) val ois = ObjectInputStream(bais) assertEquals(Foo("abacaba")::value, ois.readObject()) ois.close() return "OK" }
backend.native/tests/external/codegen/box/callableReference/serializability/boundWithSerializableReceiver.kt
1366358923
package versioned.host.exp.exponent import org.junit.Test class VersionedUtilsTest { @Test fun isHermesBundle_plainJS_returnFalse() { val jsBundlePath = VersionedUtilsTest::class.java.getResource("/plain.js")?.path assert(jsBundlePath != null) assert(!VersionedUtils.isHermesBundle(jsBundlePath)) } @Test fun isHermesBundle_hermesBytecodeBundle74_returnTrue() { val jsBundlePath = VersionedUtilsTest::class.java.getResource("/plain.74.hbc")?.path assert(jsBundlePath != null) assert(VersionedUtils.isHermesBundle(jsBundlePath)) } @Test fun isHermesBundle_nullInput_returnFalse() { assert(!VersionedUtils.isHermesBundle(null)) assert(!VersionedUtils.isHermesBundle("")) } @Test fun getHermesBundleBytecodeVersion_plainJS_return0() { val jsBundlePath = VersionedUtilsTest::class.java.getResource("/plain.js")?.path assert(jsBundlePath != null) assert(VersionedUtils.getHermesBundleBytecodeVersion(jsBundlePath) == 0) } @Test fun getHermesBundleBytecodeVersion_hermesBytecodeBundle74_return74() { val jsBundlePath = VersionedUtilsTest::class.java.getResource("/plain.74.hbc")?.path assert(jsBundlePath != null) assert(VersionedUtils.getHermesBundleBytecodeVersion(jsBundlePath) == 74) } }
android/expoview/src/test/java/versioned/host/exp/exponent/VersionedUtilsTest.kt
1783857559
// MODE: usages-&-inheritors // USAGES-LIMIT: 3 // INHERITORS-LIMIT: 2 <# block [ 3+ Usages 2+ Inheritors] #> open class SomeClass { class NestedDerivedClass: SomeClass() {} // <== (1): nested class } <# block [ 1 Usage 1 Inheritor] #> open class DerivedClass : SomeClass {} // <== (2): direct derived one class AnotherDerivedClass : SomeClass {} // <== (3): yet another derived one class DerivedDerivedClass : DerivedClass { // <== (): indirect inheritor of SomeClass fun main() { val someClassInstance = object : SomeClass() // { <== (4): anonymous derived one val somethingHere = "" } } }
plugins/kotlin/idea/tests/testData/codeInsight/codeVision/TooManyUsagesAndInheritors.kt
1797560294
package com.intellij.ide.actions.searcheverywhere.ml.id import com.intellij.openapi.extensions.ExtensionPointName internal abstract class ElementKeyForIdProvider { companion object { private val EP_NAME = ExtensionPointName.create<ElementKeyForIdProvider>("com.intellij.searcheverywhere.ml.elementKeyForIdProvider") fun isElementSupported(element: Any) = getKeyOrNull(element) != null /** * Returns key that will be used by [SearchEverywhereMlItemIdProvider]. * The method may throw a [UnsupportedElementTypeException] if no provider was found for the element, * therefore [isElementSupported] should be used before to make sure that calling this method is safe. * @return Key for ID */ fun getKey(element: Any) = getKeyOrNull(element) ?: throw UnsupportedElementTypeException(element::class.java) private fun getKeyOrNull(element: Any): Any? { EP_NAME.extensionList.forEach { val key = it.getKey(element) if (key != null) { return key } } return null } } /** * Returns a unique key that will be used by [SearchEverywhereMlItemIdProvider] to obtain * an id of the element. * * If the element type is not supported by the provider, it will return null. * @return Unique key based on the [element] or null if not supported */ protected abstract fun getKey(element: Any): Any? } internal class UnsupportedElementTypeException(elementType: Class<*>): Exception("No provider found for element type: ${elementType}")
plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/id/ElementKeyForIdProvider.kt
480433487
// 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.decompiler.common import org.jetbrains.kotlin.idea.decompiler.textBuilder.DecompiledText import org.jetbrains.kotlin.idea.decompiler.textBuilder.DecompiledTextIndex import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion private const val FILE_ABI_VERSION_MARKER: String = "FILE_ABI" private const val CURRENT_ABI_VERSION_MARKER: String = "CURRENT_ABI" const val INCOMPATIBLE_ABI_VERSION_GENERAL_COMMENT: String = "// This class file was compiled with different version of Kotlin compiler and can't be decompiled." private const val INCOMPATIBLE_ABI_VERSION_COMMENT: String = "$INCOMPATIBLE_ABI_VERSION_GENERAL_COMMENT\n" + "//\n" + "// Current compiler ABI version is $CURRENT_ABI_VERSION_MARKER\n" + "// File ABI version is $FILE_ABI_VERSION_MARKER" fun <V : BinaryVersion> createIncompatibleAbiVersionDecompiledText(expectedVersion: V, actualVersion: V): DecompiledText = DecompiledText( INCOMPATIBLE_ABI_VERSION_COMMENT.replace(CURRENT_ABI_VERSION_MARKER, expectedVersion.toString()) .replace(FILE_ABI_VERSION_MARKER, actualVersion.toString()), DecompiledTextIndex.Empty )
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/decompiler/common/incompatibleAbiVersion.kt
3342071802
// 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.util inline fun <T> Boolean.ifTrue(body: () -> T?): T? = if (this) body() else null inline fun <T> Boolean.ifFalse(body: () -> T?): T? = if (!this) body() else null
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/util/utilsIndependent.kt
3946702199
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.statistics import com.intellij.featureStatistics.fusCollectors.EventsRateThrottle import com.intellij.featureStatistics.fusCollectors.ThrowableDescription import com.intellij.ide.plugins.PluginUtil import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventFields.Boolean import com.intellij.internal.statistic.eventLog.events.EventFields.DurationMs import com.intellij.internal.statistic.eventLog.events.EventFields.Int import com.intellij.internal.statistic.eventLog.events.EventFields.StringValidatedByCustomRule import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.internal.statistic.utils.getPluginInfoById import com.intellij.internal.statistic.utils.platformPlugin import com.intellij.openapi.externalSystem.model.ExternalSystemException import com.intellij.openapi.project.Project import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal enum class Phase { GRADLE_CALL, PROJECT_RESOLVERS, DATA_SERVICES } /** * Collect gradle import stats. * * This collector is an internal implementation aimed gather data on * the Gradle synchronization duration. Phases are also * specific to Gradle build system. */ @ApiStatus.Internal class ExternalSystemSyncActionsCollector : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP companion object { private val GROUP = EventLogGroup("build.gradle.import", 4) val activityIdField = EventFields.Long("ide_activity_id") val importPhaseField = EventFields.Enum<Phase>("phase") private val syncStartedEvent = GROUP.registerEvent("gradle.sync.started", activityIdField) private val syncFinishedEvent = GROUP.registerEvent("gradle.sync.finished", activityIdField, Boolean("sync_successful")) private val phaseStartedEvent = GROUP.registerEvent("phase.started", activityIdField, importPhaseField) private val phaseFinishedEvent = GROUP.registerVarargEvent("phase.finished", activityIdField, importPhaseField, DurationMs, Int("error_count")) val errorField = StringValidatedByCustomRule("error", "class_name") val severityField = EventFields.String("severity", listOf("fatal", "warning")) val errorHashField = Int("error_hash") val tooManyErrorsField = Boolean("too_many_errors") private val errorEvent = GROUP.registerVarargEvent("error", activityIdField, errorField, severityField, errorHashField, EventFields.PluginInfo, tooManyErrorsField) private val ourErrorsRateThrottle = EventsRateThrottle(100, 5L * 60 * 1000) // 100 errors per 5 minutes @JvmStatic fun logSyncStarted(project: Project?, activityId: Long) = syncStartedEvent.log(project, activityId) @JvmStatic fun logSyncFinished(project: Project?, activityId: Long, success: Boolean) = syncFinishedEvent.log(project, activityId, success) @JvmStatic fun logPhaseStarted(project: Project?, activityId: Long, phase: Phase) = phaseStartedEvent.log(project, activityId, phase) @JvmStatic fun logPhaseFinished(project: Project?, activityId: Long, phase: Phase, durationMs: Long, errorCount: Int = 0) = phaseFinishedEvent.log(project, activityIdField.with(activityId), importPhaseField.with(phase), DurationMs.with(durationMs), EventPair(Int("error_count"), errorCount)) @JvmStatic fun logError(project: Project?, activityId: Long, throwable: Throwable) { val description = ThrowableDescription(throwable) val framesHash = if (throwable is ExternalSystemException) { throwable.originalReason.hashCode() } else { description.getLastFrames(50).hashCode() } val data = ArrayList<EventPair<*>>() data.add(activityIdField.with(activityId)) data.add(severityField.with("fatal")) val pluginId = PluginUtil.getInstance().findPluginId(throwable) data.add(EventFields.PluginInfo.with(if (pluginId == null) platformPlugin else getPluginInfoById(pluginId))) data.add(errorField.with(description.className)) if (ourErrorsRateThrottle.tryPass(System.currentTimeMillis())) { data.add(errorHashField.with(framesHash)) } else { data.add(tooManyErrorsField.with(true)) } errorEvent.log(project, *data.toTypedArray()) } } }
platform/external-system-impl/src/com/intellij/openapi/externalSystem/statistics/ExternalSystemSyncActionsCollector.kt
32250220
// PROBLEM: none // WITH_STDLIB class Foo(val bar: () -> Int) fun bar(foo: Foo?) { foo?.<caret>let { it.bar.invoke() } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/complexRedundantLet/functionInVariableInvokeCall.kt
1707230268
// DISABLE-ERRORS fun Int.invoke() = this + 1 val a = <selection>1()</selection> val b = 1.invoke() val c = invoke(1) val d = 1.plus()
plugins/kotlin/idea/tests/testData/unifier/equivalence/expressions/conventions/invoke/invokeOnConst.kt
1689049031
package <%= appPackage %>.data.remote class FakeAppApi: AppApi {}
app/templates/app_mvp/src/mock/kotlin/data/remote/FakeAppApi.kt
2150987947
package com.cn29.aac.ui.masterdetail import com.cn29.aac.R import com.cn29.aac.databinding.ItemGithubCardBinding import com.cn29.aac.repo.github.Repo import com.cn29.aac.ui.common.BaseRecyclerViewAdapter import java.util.* /** * Created by Charles Ng on 11/10/2017. */ class GithubRepoAdapter( itemClickListener: OnItemClickListener<Repo?>) : BaseRecyclerViewAdapter<Repo?, ItemGithubCardBinding>( itemClickListener) { private var repos: List<Repo> = ArrayList() fun setRepos(repos: List<Repo>) { this.repos = repos } override fun getItemForPosition(position: Int): Repo { return repos[position] } override fun getLayoutIdForPosition(position: Int): Int { return R.layout.item_github_card } override fun bind(binding: ItemGithubCardBinding, item: Repo?) { binding.repo = item } override fun getItemCount(): Int { return repos.size } }
app/src/main/java/com/cn29/aac/ui/masterdetail/GithubRepoAdapter.kt
1623326164
package com.tofi.peekazoo.api import com.tofi.peekazoo.models.InkbunnyLoginResponse import com.tofi.peekazoo.models.InkbunnySearchResponse import io.reactivex.Observable import retrofit2.http.* /** * Created by Derek on 01/05/2017. * Defines Inkbunny api endpoints */ interface InkbunnyApi { @FormUrlEncoded @POST("api_login.php") fun login(@Field("username") username: String, @Field("password") password: String): Observable<InkbunnyLoginResponse> @GET("api_search.php") fun search(@Query("page") page: Int): Observable<InkbunnySearchResponse> }
app/src/main/java/com/tofi/peekazoo/api/InkbunnyApi.kt
1264210749
package flank.scripts.cli.release import com.google.common.truth.Truth.assertThat import flank.scripts.FuelTestRunner import flank.scripts.cli.github.DeleteOldTagCommand import org.junit.Rule import org.junit.Test import org.junit.contrib.java.lang.system.SystemOutRule import org.junit.runner.RunWith @RunWith(FuelTestRunner::class) class DeleteOldTagCommandTest { @Rule @JvmField val systemOutRule = SystemOutRule().enableLog()!! @Test fun `Should return properly message when success`() { // when DeleteOldTagCommand.main(arrayOf("--git-tag=success", "--username=1", "--token=1")) // then assertThat(systemOutRule.log).contains("Tag success was deleted") } @Test fun `Should return with exit code 1 when failure`() { // when DeleteOldTagCommand.main(arrayOf("--git-tag=failure", "--username=1", "--token=1")) // then assertThat(systemOutRule.log).contains("Error while doing GitHub request") } }
flank-scripts/src/test/kotlin/flank/scripts/cli/release/DeleteOldTagCommandTest.kt
733770594
package de.fabmax.kool.pipeline.shadermodel import de.fabmax.kool.math.Vec2f import de.fabmax.kool.math.Vec3f import de.fabmax.kool.math.Vec4f import de.fabmax.kool.pipeline.Attribute import de.fabmax.kool.pipeline.GlslType import de.fabmax.kool.pipeline.ShaderStage class FlipBacksideNormalNode(graph: ShaderGraph) : ShaderNode("flipBacksideNormal_${graph.nextNodeId}", graph, ShaderStage.FRAGMENT_SHADER.mask) { var inNormal = ShaderNodeIoVar(ModelVar3fConst(Vec3f.Y_AXIS)) val outNormal: ShaderNodeIoVar = ShaderNodeIoVar(ModelVar3f("${name}_outNormal"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inNormal) } override fun generateCode(generator: CodeGenerator) { super.generateCode(generator) generator.appendMain(""" ${outNormal.declare()} = ${inNormal.ref3f()} * (float(gl_FrontFacing) * 2.0 - 1.0); """) } } class SplitNode(val outChannels: String, graph: ShaderGraph) : ShaderNode("split_${graph.nextNodeId}", graph) { var input = ShaderNodeIoVar(ModelVar4fConst(Vec4f.ZERO)) val output: ShaderNodeIoVar = when (outChannels.length) { 1 -> ShaderNodeIoVar(ModelVar1f("${name}_out"), this) 2 -> ShaderNodeIoVar(ModelVar2f("${name}_out"), this) 3 -> ShaderNodeIoVar(ModelVar3f("${name}_out"), this) 4 -> ShaderNodeIoVar(ModelVar4f("${name}_out"), this) else -> throw IllegalArgumentException("outChannels parameter must be between 1 and 4 characters long (e.g. 'xyz')") } override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(input) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = ${input.name}.$outChannels;") } } class CombineNode(outType: GlslType, graph: ShaderGraph) : ShaderNode("combine_${graph.nextNodeId}", graph) { var inX = ShaderNodeIoVar(ModelVar1fConst(0f)) var inY = ShaderNodeIoVar(ModelVar1fConst(0f)) var inZ = ShaderNodeIoVar(ModelVar1fConst(0f)) var inW = ShaderNodeIoVar(ModelVar1fConst(0f)) var output = when (outType) { GlslType.VEC_2F -> ShaderNodeIoVar(ModelVar2f("${name}_out"), this) GlslType.VEC_3F -> ShaderNodeIoVar(ModelVar3f("${name}_out"), this) GlslType.VEC_4F -> ShaderNodeIoVar(ModelVar4f("${name}_out"), this) else -> throw IllegalArgumentException("Only allowed out types are VEC_2F, VEC_3F and VEC_4F") } override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inX, inY, inZ, inW) } override fun generateCode(generator: CodeGenerator) { when (output.variable.type) { GlslType.VEC_2F -> generator.appendMain("${output.declare()} = vec2(${inX.ref1f()}, ${inY.ref1f()});") GlslType.VEC_3F -> generator.appendMain("${output.declare()} = vec3(${inX.ref1f()}, ${inY.ref1f()}, ${inZ.ref1f()});") GlslType.VEC_4F -> generator.appendMain("${output.declare()} = vec4(${inX.ref1f()}, ${inY.ref1f()}, ${inZ.ref1f()}, ${inW.ref1f()});") else -> throw IllegalArgumentException("Only allowed out types are VEC_2F, VEC_3F and VEC_4F") } } } class Combine31Node(graph: ShaderGraph) : ShaderNode("combine31_${graph.nextNodeId}", graph) { var inXyz = ShaderNodeIoVar(ModelVar3fConst(Vec3f.ZERO)) var inW = ShaderNodeIoVar(ModelVar1fConst(0f)) var output = ShaderNodeIoVar(ModelVar4f("${name}_out"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inXyz, inW) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = vec4(${inXyz.ref3f()}, ${inW.ref1f()});") } } class AttributeNode(val attribute: Attribute, graph: ShaderGraph) : ShaderNode(attribute.name, graph, ShaderStage.VERTEX_SHADER.mask) { val output = ShaderNodeIoVar(ModelVar(attribute.name, attribute.type), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) shaderGraph as VertexShaderGraph shaderGraph.requiredVertexAttributes += attribute } } class InstanceAttributeNode(val attribute: Attribute, graph: ShaderGraph) : ShaderNode(attribute.name, graph, ShaderStage.VERTEX_SHADER.mask) { val output = ShaderNodeIoVar(ModelVar(attribute.name, attribute.type), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) shaderGraph as VertexShaderGraph shaderGraph.requiredInstanceAttributes += attribute } } class StageInterfaceNode(val name: String, vertexGraph: ShaderGraph, fragmentGraph: ShaderGraph) { // written in source stage (i.e. vertex shader) var input = ShaderNodeIoVar(ModelVar1fConst(0f)) set(value) { output = ShaderNodeIoVar(ModelVar(name, value.variable.type), fragmentNode) field = value } // accessible in target stage (i.e. fragment shader) var output = ShaderNodeIoVar(ModelVar1f(name)) private set var isFlat = false private lateinit var ifVar: ShaderInterfaceIoVar val vertexNode = InputNode(vertexGraph) val fragmentNode = OutputNode(fragmentGraph) inner class InputNode(graph: ShaderGraph) : ShaderNode(name, graph, ShaderStage.VERTEX_SHADER.mask) { val ifNode = this@StageInterfaceNode var input: ShaderNodeIoVar get() = ifNode.input set(value) { ifNode.input = value } override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(input) ifVar = shaderGraph.addStageOutput(output.variable, isFlat) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.name} = ${input.refAsType(output.variable.type)};") } } inner class OutputNode(graph: ShaderGraph) : ShaderNode(name, graph, ShaderStage.FRAGMENT_SHADER.mask) { val ifNode = this@StageInterfaceNode val output: ShaderNodeIoVar get() = ifNode.output override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) shaderGraph.inputs += ifVar } } } class ScreenCoordNode(graph: ShaderGraph) : ShaderNode("screenCoord_${graph.nextNodeId}", graph, ShaderStage.FRAGMENT_SHADER.mask) { var inViewport = ShaderNodeIoVar(ModelVar4fConst(Vec4f.ZERO)) val outScreenCoord = ShaderNodeIoVar(ModelVar4f("gl_FragCoord"), this) val outNormalizedScreenCoord = ShaderNodeIoVar(ModelVar3f("${name}_outNormalizedCoord"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inViewport) } override fun generateCode(generator: CodeGenerator) { generator.appendMain(""" ${outNormalizedScreenCoord.declare()} = ${outScreenCoord.ref3f()}; $outNormalizedScreenCoord.xy - ${inViewport.ref2f()}; $outNormalizedScreenCoord.xy /= ${inViewport.ref4f()}.zw; """) } } class FullScreenQuadTexPosNode(graph: ShaderGraph) : ShaderNode("fullScreenQuad_${graph.nextNodeId}", graph) { var inTexCoord = ShaderNodeIoVar(ModelVar2fConst(Vec2f.ZERO)) var inDepth = ShaderNodeIoVar(ModelVar1fConst(0.999f)) val outQuadPos = ShaderNodeIoVar(ModelVar4f("${name}_outPos"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inTexCoord, inDepth) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${outQuadPos.declare()} = vec4(${inTexCoord.ref2f()} * 2.0 - 1.0, ${inDepth.ref1f()}, 1.0);") } } class GetMorphWeightNode(val iWeight: Int, graph: ShaderGraph) : ShaderNode("getMorphWeight_${graph.nextNodeId}", graph) { var inWeights0 = ShaderNodeIoVar(ModelVar4fConst(Vec4f.ZERO)) var inWeights1 = ShaderNodeIoVar(ModelVar4fConst(Vec4f.ZERO)) val outWeight = ShaderNodeIoVar(ModelVar1f("${name}_outW"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inWeights0, inWeights1) } override fun generateCode(generator: CodeGenerator) { val inW = if (iWeight < 4) { inWeights0 } else { inWeights1 } val c = when (iWeight % 4) { 0 -> "x" 1 -> "y" 2 -> "z" else -> "w" } generator.appendMain("${outWeight.declare()} = ${inW.ref4f()}.$c;") } } class NamedVariableNode(name: String, graph: ShaderGraph) : ShaderNode(name, graph) { var input = ShaderNodeIoVar(ModelVar1fConst(0f)) set(value) { field = value output = ShaderNodeIoVar(ModelVar(name, value.variable.type), this) } var output = ShaderNodeIoVar(ModelVar(name, GlslType.FLOAT), this) private set override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(input) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = $input;") } } class PointSizeNode(graph: ShaderGraph) : ShaderNode("pointSz", graph, ShaderStage.VERTEX_SHADER.mask) { var inSize = ShaderNodeIoVar(ModelVar1fConst(1f)) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inSize) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("gl_PointSize = ${inSize.ref1f()};") } }
kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/shadermodel/UtilityNodes.kt
386237455
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.wifi.graphutils import com.jjoe64.graphview.GraphView import com.vrem.wifianalyzer.wifi.model.WiFiData import com.vrem.wifianalyzer.wifi.scanner.UpdateNotifier open class GraphAdapter(private val graphViewNotifiers: List<GraphViewNotifier>) : UpdateNotifier { fun graphViews(): List<GraphView> = graphViewNotifiers.map { it.graphView() } override fun update(wiFiData: WiFiData) = graphViewNotifiers.forEach { it.update(wiFiData) } fun graphViewNotifiers(): List<GraphViewNotifier> = graphViewNotifiers }
app/src/main/kotlin/com/vrem/wifianalyzer/wifi/graphutils/GraphAdapter.kt
1149933084
// PROBLEM: none // WITH_RUNTIME fun foo(s: String, i: Int) = s.length + i fun test() { val s = "" s.length.let<caret> { foo("", it) } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/simpleRedundantLet/functionCall5.kt
622868130
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.autoimport import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType.EXTERNAL import com.intellij.openapi.externalSystem.autoimport.changes.AsyncFilesChangesListener.Companion.subscribeOnDocumentsAndVirtualFilesChanges import com.intellij.openapi.externalSystem.autoimport.changes.FilesChangesListener import com.intellij.openapi.externalSystem.autoimport.changes.NewFilesListener.Companion.whenNewFilesCreated import com.intellij.openapi.externalSystem.autoimport.settings.* import com.intellij.openapi.externalSystem.util.calculateCrc import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.LocalTimeCounter.currentTime import org.jetbrains.annotations.ApiStatus import java.nio.file.Path import java.util.concurrent.Executor import java.util.concurrent.atomic.AtomicReference @ApiStatus.Internal class ProjectSettingsTracker( private val project: Project, private val projectTracker: AutoImportProjectTracker, private val backgroundExecutor: Executor, private val projectAware: ExternalSystemProjectAware, private val parentDisposable: Disposable ) { private val status = ProjectStatus(debugName = "Settings ${projectAware.projectId.readableName}") private val settingsFilesStatus = AtomicReference(SettingsFilesStatus()) private val applyChangesOperation = AnonymousParallelOperationTrace(debugName = "Apply changes operation") private val settingsAsyncSupplier = SettingsFilesAsyncSupplier() private fun calculateSettingsFilesCRC(settingsFiles: Set<String>): Map<String, Long> { val localFileSystem = LocalFileSystem.getInstance() return settingsFiles .mapNotNull { localFileSystem.findFileByPath(it) } .associate { it.path to calculateCrc(it) } } private fun calculateCrc(file: VirtualFile): Long { val fileDocumentManager = FileDocumentManager.getInstance() val document = fileDocumentManager.getCachedDocument(file) if (document != null) return document.calculateCrc(project, projectAware.projectId.systemId, file) return file.calculateCrc(project, projectAware.projectId.systemId) } fun isUpToDate() = status.isUpToDate() fun getModificationType() = status.getModificationType() fun getSettingsContext(): ExternalSystemSettingsFilesReloadContext = settingsFilesStatus.get() private fun createSettingsFilesStatus( oldSettingsFilesCRC: Map<String, Long>, newSettingsFilesCRC: Map<String, Long> ): SettingsFilesStatus { val updatedFiles = oldSettingsFilesCRC.keys.intersect(newSettingsFilesCRC.keys) .filterTo(HashSet()) { oldSettingsFilesCRC[it] != newSettingsFilesCRC[it] } val createdFiles = newSettingsFilesCRC.keys.minus(oldSettingsFilesCRC.keys) val deletedFiles = oldSettingsFilesCRC.keys.minus(newSettingsFilesCRC.keys) return SettingsFilesStatus(oldSettingsFilesCRC, newSettingsFilesCRC, updatedFiles, createdFiles, deletedFiles) } /** * Usually all crc hashes must be previously calculated * => this apply will be fast * => collisions is a rare thing */ private fun applyChanges() { applyChangesOperation.startTask() submitSettingsFilesRefreshAndCRCCalculation("applyChanges") { newSettingsFilesCRC -> settingsFilesStatus.set(SettingsFilesStatus(newSettingsFilesCRC)) status.markSynchronized(currentTime()) applyChangesOperation.finishTask() } } /** * Applies changes for newly registered files * Needed to cases: tracked files are registered during project reload */ private fun applyUnknownChanges() { applyChangesOperation.startTask() submitSettingsFilesRefreshAndCRCCalculation("applyUnknownChanges") { newSettingsFilesCRC -> val settingsFilesStatus = settingsFilesStatus.updateAndGet { createSettingsFilesStatus(newSettingsFilesCRC + it.oldCRC, newSettingsFilesCRC) } if (!settingsFilesStatus.hasChanges()) { status.markSynchronized(currentTime()) } applyChangesOperation.finishTask() } } fun refreshChanges() { submitSettingsFilesRefreshAndCRCCalculation("refreshChanges") { newSettingsFilesCRC -> val settingsFilesStatus = settingsFilesStatus.updateAndGet { createSettingsFilesStatus(it.oldCRC, newSettingsFilesCRC) } LOG.info("Settings file status: ${settingsFilesStatus}") when (settingsFilesStatus.hasChanges()) { true -> status.markDirty(currentTime(), EXTERNAL) else -> status.markReverted(currentTime()) } projectTracker.scheduleChangeProcessing() } } fun getState() = State(status.isDirty(), settingsFilesStatus.get().oldCRC.toMap()) fun loadState(state: State) { if (state.isDirty) status.markDirty(currentTime(), EXTERNAL) settingsFilesStatus.set(SettingsFilesStatus(state.settingsFiles.toMap())) } private fun submitSettingsFilesRefreshAndCRCCalculation(id: Any, callback: (Map<String, Long>) -> Unit) { submitSettingsFilesRefresh { settingsPaths -> submitSettingsFilesCRCCalculation(id, settingsPaths, callback) } } @Suppress("SameParameterValue") private fun submitSettingsFilesCRCCalculation(id: Any, callback: (Map<String, Long>) -> Unit) { settingsAsyncSupplier.supply({ settingsPaths -> submitSettingsFilesCRCCalculation(id, settingsPaths, callback) }, parentDisposable) } private fun submitSettingsFilesRefresh(callback: (Set<String>) -> Unit) { EdtAsyncSupplier.invokeOnEdt(projectTracker::isAsyncChangesProcessing, { val fileDocumentManager = FileDocumentManager.getInstance() fileDocumentManager.saveAllDocuments() settingsAsyncSupplier.invalidate() settingsAsyncSupplier.supply({ settingsPaths -> val localFileSystem = LocalFileSystem.getInstance() val settingsFiles = settingsPaths.map { Path.of(it) } localFileSystem.refreshNioFiles(settingsFiles, projectTracker.isAsyncChangesProcessing, false) { callback(settingsPaths) } }, parentDisposable) }, parentDisposable) } private fun submitSettingsFilesCRCCalculation(id: Any, settingsPaths: Set<String>, callback: (Map<String, Long>) -> Unit) { ReadAsyncSupplier.Builder { calculateSettingsFilesCRC(settingsPaths) } .shouldKeepTasksAsynchronous { projectTracker.isAsyncChangesProcessing } .coalesceBy(this, id) .build(backgroundExecutor) .supply(callback, parentDisposable) } fun beforeApplyChanges(listener: () -> Unit) = applyChangesOperation.beforeOperation(listener) fun afterApplyChanges(listener: () -> Unit) = applyChangesOperation.afterOperation(listener) init { val projectRefreshListener = object : ExternalSystemProjectRefreshListener { override fun beforeProjectRefresh() { applyChangesOperation.startTask() applyChanges() } override fun afterProjectRefresh(status: ExternalSystemRefreshStatus) { applyUnknownChanges() applyChangesOperation.finishTask() } } projectAware.subscribe(projectRefreshListener, parentDisposable) } init { whenNewFilesCreated(settingsAsyncSupplier::invalidate, parentDisposable) subscribeOnDocumentsAndVirtualFilesChanges(settingsAsyncSupplier, ProjectSettingsListener(), parentDisposable) } companion object { private val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport") } data class State(var isDirty: Boolean = true, var settingsFiles: Map<String, Long> = emptyMap()) private data class SettingsFilesStatus( val oldCRC: Map<String, Long> = emptyMap(), val newCRC: Map<String, Long> = emptyMap(), override val updated: Set<String> = emptySet(), override val created: Set<String> = emptySet(), override val deleted: Set<String> = emptySet() ) : ExternalSystemSettingsFilesReloadContext { constructor(CRC: Map<String, Long>) : this(oldCRC = CRC) fun hasChanges() = updated.isNotEmpty() || created.isNotEmpty() || deleted.isNotEmpty() } private inner class ProjectSettingsListener : FilesChangesListener { override fun onFileChange(path: String, modificationStamp: Long, modificationType: ModificationType) { logModificationAsDebug(path, modificationStamp, modificationType) if (applyChangesOperation.isOperationCompleted()) { status.markModified(currentTime(), modificationType) } else { status.markDirty(currentTime(), modificationType) } } override fun apply() { submitSettingsFilesCRCCalculation("apply") { newSettingsFilesCRC -> val settingsFilesStatus = settingsFilesStatus.updateAndGet { createSettingsFilesStatus(it.oldCRC, newSettingsFilesCRC) } if (!settingsFilesStatus.hasChanges()) { status.markReverted(currentTime()) } projectTracker.scheduleChangeProcessing() } } private fun logModificationAsDebug(path: String, modificationStamp: Long, type: ModificationType) { if (LOG.isDebugEnabled) { val projectPath = projectAware.projectId.externalProjectPath val relativePath = FileUtil.getRelativePath(projectPath, path, '/') ?: path LOG.debug("File $relativePath is modified at ${modificationStamp} as $type") } } } private inner class SettingsFilesAsyncSupplier : AsyncSupplier<Set<String>> { private val cachingAsyncSupplier = CachingAsyncSupplier( BackgroundAsyncSupplier.Builder(projectAware::settingsFiles) .shouldKeepTasksAsynchronous(projectTracker::isAsyncChangesProcessing) .build(backgroundExecutor)) private val supplier = BackgroundAsyncSupplier.Builder(cachingAsyncSupplier) .shouldKeepTasksAsynchronous(projectTracker::isAsyncChangesProcessing) .build(backgroundExecutor) override fun supply(consumer: (Set<String>) -> Unit, parentDisposable: Disposable) { supplier.supply({ consumer(it + settingsFilesStatus.get().oldCRC.keys) }, parentDisposable) } fun invalidate() = cachingAsyncSupplier.invalidate() } }
platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectSettingsTracker.kt
1986202129
class A {<caret>}
plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyBraces/ClassWithoutConstructor.kt
934106867
// "Add '@OptIn(A::class)' annotation to 'root'" "true" // WITH_RUNTIME @RequiresOptIn annotation class A @A fun f1() {} @OptIn fun root() { <caret>f1() }
plugins/kotlin/idea/tests/testData/quickfix/experimental/hasOptInAnnotation3.kt
38991574
package io.github.feelfreelinux.wykopmobilny.ui.modules.addlink.fragments.urlinput import io.github.feelfreelinux.wykopmobilny.base.BaseView import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.responses.NewLinkResponse interface AddLinkUrlInputFragmentView : BaseView { fun setLinkDraft(draft: NewLinkResponse) fun showDuplicatesLoading(visibility: Boolean) }
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/addlink/fragments/urlinput/AddLinkUrlInputFragmentView.kt
1915488929
/* * 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 com.intellij.configurationStore import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.project.impl.ProjectStoreClassProvider class PlatformLangProjectStoreClassProvider : ProjectStoreClassProvider { override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> { return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectStoreImpl.ProjectWithModulesStoreImpl::class.java } }
platform/configuration-store-impl/src/ProjectWithModulesStoreImpl.kt
455809819
// p.B // FIR_COMPARISON package p expect class B
plugins/kotlin/idea/tests/testData/compiler/asJava/lightClasses/compilationErrors/ExpectClass.kt
3151957841
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package kotlin.collections /** * A collection that holds pairs of objects (keys and values) and supports efficiently retrieving * the value corresponding to each key. Map keys are unique; the map holds only one value for each key. * Methods in this interface support only read-only access to the map; read-write access is supported through * the [MutableMap] interface. * @param K the type of map keys. The map is invariant in its key type, as it * can accept key as a parameter (of [containsKey] for example) and return it in [keys] set. * @param V the type of map values. The map is covariant in its value type. */ public interface Map<K, out V> { // Query Operations /** * Returns the number of key/value pairs in the map. */ public val size: Int /** * Returns `true` if the map is empty (contains no elements), `false` otherwise. */ public fun isEmpty(): Boolean /** * Returns `true` if the map contains the specified [key]. */ public fun containsKey(key: K): Boolean /** * Returns `true` if the map maps one or more keys to the specified [value]. */ public fun containsValue(value: @UnsafeVariance V): Boolean /** * Returns the value corresponding to the given [key], or `null` if such a key is not present in the map. */ public operator fun get(key: K): V? // Views /** * Returns a read-only [Set] of all keys in this map. */ public val keys: Set<K> /** * Returns a read-only [Collection] of all values in this map. Note that this collection may contain duplicate values. */ public val values: Collection<V> /** * Returns a read-only [Set] of all key/value pairs in this map. */ public val entries: Set<Map.Entry<K, V>> /** * Represents a key/value pair held by a [Map]. */ public interface Entry<out K, out V> { /** * Returns the key of this key/value pair. */ public val key: K /** * Returns the value of this key/value pair. */ public val value: V } } /** * A modifiable collection that holds pairs of objects (keys and values) and supports efficiently retrieving * the value corresponding to each key. Map keys are unique; the map holds only one value for each key. * @param K the type of map keys. The map is invariant in its key type. * @param V the type of map values. The mutable map is invariant in its value type. */ public interface MutableMap<K, V> : Map<K, V> { // Modification Operations /** * Associates the specified [value] with the specified [key] in the map. * * @return the previous value associated with the key, or `null` if the key was not present in the map. */ public fun put(key: K, value: V): V? /** * Removes the specified key and its corresponding value from this map. * * @return the previous value associated with the key, or `null` if the key was not present in the map. */ public fun remove(key: K): V? // Bulk Modification Operations /** * Updates this map with key/value pairs from the specified map [from]. */ public fun putAll(from: Map<out K, V>): Unit /** * Removes all elements from this map. */ public fun clear(): Unit // Views /** * Returns a [MutableSet] of all keys in this map. */ override val keys: MutableSet<K> /** * Returns a [MutableCollection] of all values in this map. Note that this collection may contain duplicate values. */ override val values: MutableCollection<V> /** * Returns a [MutableSet] of all key/value pairs in this map. */ override val entries: MutableSet<MutableMap.MutableEntry<K, V>> /** * Represents a key/value pair held by a [MutableMap]. */ public interface MutableEntry<K, V> : Map.Entry<K, V> { /** * Changes the value associated with the key of this entry. * * @return the previous value corresponding to the key. */ public fun setValue(newValue: V): V } }
runtime/src/main/kotlin/kotlin/collections/Map.kt
290789502
package com.petukhovsky.jvaluer.cli import com.fasterxml.jackson.annotation.JsonIgnore import com.petukhovsky.jvaluer.JValuer import com.petukhovsky.jvaluer.commons.builtin.JValuerBuiltin import com.petukhovsky.jvaluer.commons.checker.Checker import com.petukhovsky.jvaluer.commons.compiler.CompilationResult import com.petukhovsky.jvaluer.commons.data.StringData import com.petukhovsky.jvaluer.commons.data.TestData import com.petukhovsky.jvaluer.commons.exe.Executable import com.petukhovsky.jvaluer.commons.gen.Generator import com.petukhovsky.jvaluer.commons.invoker.DefaultInvoker import com.petukhovsky.jvaluer.commons.invoker.Invoker import com.petukhovsky.jvaluer.commons.lang.Language import com.petukhovsky.jvaluer.commons.lang.Languages import com.petukhovsky.jvaluer.commons.run.* import com.petukhovsky.jvaluer.commons.source.Source import com.petukhovsky.jvaluer.impl.JValuerImpl import com.petukhovsky.jvaluer.lang.LanguagesImpl import com.petukhovsky.jvaluer.run.RunnerBuilder import com.petukhovsky.jvaluer.run.SafeRunner import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.nio.file.StandardCopyOption import java.time.Instant class DefInvokerBuiltin( val invoker: Invoker, val chain: JValuerBuiltin ) : JValuerBuiltin { override fun checker(s: String?): Checker = chain.checker(s) override fun generator(s: String?): Generator = chain.generator(s) override fun invoker(s: String?): Invoker = if (s == "default") invoker else chain.invoker(s) } class MyJValuer( languages: Languages, path: Path, forceInvoker: String? ) : JValuerImpl(languages, path, null) { val myBuiltin by lazy { if (forceInvoker == null) super.builtin() else { DefInvokerBuiltin( super.builtin() .invoker(forceInvoker) ?: throw NullPointerException("runexe invoker not supported"), super.builtin() ) } } override fun builtin(): JValuerBuiltin = myBuiltin override fun invokeDefault(runOptions: RunOptions?): RunInfo { val def = myBuiltin.invoker("default") ?: throw UnsupportedOperationException("can't find default invoker") return invoke(def, runOptions) } } val jValuer by lazy { try { val config = jValuerConfig.get()!! if (config.forceInvoker == null) { JValuerImpl(langConfig.get()!!.toLanguages(), configDir.resolve("jvaluer/"), null) } else { MyJValuer(langConfig.get()!!.toLanguages(), configDir.resolve("jvaluer/"), config.forceInvoker) } } catch (e: Exception) { println("Can't initialize jValuer. Check your config, run 'jv init' if you still haven't") throw e } } fun createRunnerBuilder(): RunnerBuilder = RunnerBuilder(jValuer).trusted(jValuerConfig.get()!!.trusted) fun RunnerBuilder.buildSafe(path: Path, lang: Language) = this.buildSafe(path, lang.invoker()) fun RunnerBuilder.buildSafe(path: Path, invoker: Invoker) = this.buildSafe(Executable(path, invoker))!! fun compileSrc(src: Source, liveProgress: Boolean = true, allInfo: Boolean = true): MyExecutable { val dbSrc = dbSource(src) val srcInfo = dbSrc.get()!! if (srcInfo.exe != null) { if (allInfo) println("Already compiled at ${srcInfo.compiled}") return MyExecutable(getObject(srcInfo.exe!!), src.language.invoker(), null, true) } val result: CompilationResult if (!liveProgress) { println("Compiling...") result = jValuer.compile(src) } else { result = object : LiveProcess<CompilationResult>() { override fun update() { val passed = (ended ?: now()) - started val seconds = passed / 1000 val ms = passed % 1000 print("\rCompil") if (ended == null) { print("ing") for (i in 0..2) print(if (i < seconds % 4) '.' else ' ') } else { print("ed! ") } print(" ") print("[${seconds}s ${String.format("%03d", ms)}ms]") } override fun run(): CompilationResult = jValuer.compile(src) }.execute() println() } if (result.isSuccess) { srcInfo.compiled = Instant.now() srcInfo.exe = saveObject(result.exe) dbSrc.save(srcInfo) } return MyExecutable(result.exe, src.language.invoker(), result, result.isSuccess) } fun runExe(exe: Executable, test: TestData = StringData(""), limits: RunLimits = RunLimits.unlimited(), io: RunInOut = RunInOut.std(), args: String? = null, liveProgress: Boolean = true, prefix: String = "" ): InvocationResult { val runner = createRunnerBuilder().inOut(io).limits(limits).buildSafe(exe) return runner.runLive(test, args, liveProgress, prefix = prefix) } fun runExe(exe: ExeInfo, test: TestData = StringData(""), args: String? = null, liveProgress: Boolean = true, allInfo: Boolean = true, prefix: String = "" ) = runExe( exe.toExecutable(allInfo = allInfo, liveProgress = liveProgress)!!, test, exe.createLimits(), exe.io, args, liveProgress, prefix = prefix ) fun SafeRunner.runLive( test: TestData, args: String? = null, liveProgress: Boolean = true, prefix: String = "", ln: Boolean = true ): InvocationResult { fun verdictSign(verdict: RunVerdict): String = if (verdict == RunVerdict.SUCCESS) ui.okSign else ui.wrongSign fun verdictString(verdict: RunVerdict): String = if (verdict == RunVerdict.SUCCESS) "Ok" else verdict.toString() val result: InvocationResult val argsArr = if (args == null) arrayOf() else arrayOf(args) if (!liveProgress) { result = this.run(test, *argsArr) } else { result = object : LiveProcess<InvocationResult>() { val running = listOf("\\", "|", "/", "-") override fun update() { val time: Long val message: String print("\r$prefix") if (ended == null) { time = now() - started print("[${running[(time / 300).toInt() % 4]}]") message = "Running..." } else { time = this.result!!.run.userTime print("[${verdictSign(this.result!!.run.runVerdict)}]") message = verdictString(this.result!!.run.runVerdict) } print(String.format(" %-13s ", message)) if (ended == null) { print("[${RunLimits.timeString(time)}]") } else { val run = this.result!!.run print(run.shortInfo) } } override fun run(): InvocationResult = [email protected](test, *argsArr) }.execute() } if (ln) println() return result } class MyExecutable(path: Path?, invoker: Invoker?, val compilation: CompilationResult?, val compilationSuccess: Boolean) : Executable(path, invoker) { fun exists(): Boolean = path != null && !Files.exists(path) fun printLog() = compilation?.printLog() } fun CompilationResult.printLog() = println("Compilation log: $comment") enum class FileType { src, exe, auto } class ExeInfo( val file: String, val type: FileType, val lang: String?, val tl: String?, val ml: String?, val `in`: String, val out: String ) : Script() { fun createLimits(): RunLimits = RunLimits.of(tl, ml) val path: Path @JsonIgnore get() = resolve(file) val io: RunInOut @JsonIgnore get() = RunInOut(`in`, out) val name: String @JsonIgnore get() = path.fileName.toString() fun toExecutable( liveProgress: Boolean = true, allInfo: Boolean = true ): MyExecutable? { val type: FileType val lang: Language? when (this.type) { FileType.auto -> { lang = jValuer.languages.findByName(this.lang) ?: jValuer.languages.findByPath(path) if (lang != null) { if (allInfo) println("Detected language: ${lang.name()}") type = FileType.src } else { println("Language not found. Assuming file is exe") type = FileType.exe } } FileType.exe -> { lang = jValuer.languages.findByName(this.lang) type = FileType.exe } FileType.src -> { type = FileType.src lang = jValuer.languages.findByName(this.lang) if (lang == null) { println("Language ${this.lang} not found") println("Available languages: " + langConfig.get()!!.map(Lang::id).toString()) return null } } } assert(type != FileType.auto) { "Wat, report to GitHub." } val exe: MyExecutable if (type == FileType.src) { exe = compileSrc(Source(path, lang), allInfo = allInfo, liveProgress = liveProgress) exe.printLog() if (!exe.compilationSuccess) { println("Compilation failed") return null } } else { exe = MyExecutable(path, if (lang == null) DefaultInvoker() else lang.invoker(), null, true) } return exe } override fun execute() { toExecutable() } } fun TestData.copyIfNotNull(path: Path?) { Files.copy(this.path, path ?: return, StandardCopyOption.REPLACE_EXISTING) } fun InvocationResult.isSuccess() = this.run.runVerdict == RunVerdict.SUCCESS fun InvocationResult.notSuccess() = !this.isSuccess() val RunInfo.shortInfo: String get() = "[$timeString; $memoryString]"
src/main/kotlin/com/petukhovsky/jvaluer/cli/JValuer.kt
3101941291
package com.jay.montior.test import org.hamcrest.MatcherAssert import org.hamcrest.Matchers import org.mockito.Mockito object TestUtil : TestUtilClass() open class TestUtilClass { inline fun <reified T : Any> lazyMock() = lazy { Mockito.mock(T::class.java) } infix fun Any?.returns(returnValue: Any?) = Mockito.`when`(this).thenReturn(returnValue) infix fun <T> T.equalTo(other: T) = MatcherAssert.assertThat(this, Matchers.equalTo(other)) }
montior-web/src/test/java/com/jay/montior/test/TestUtil.kt
2898302839
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots import com.intellij.configurationStore.serializeStateInto import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.ModuleOrderEnumerator import com.intellij.openapi.roots.impl.RootConfigurationAccessor import com.intellij.openapi.roots.impl.RootModelBase.CollectDependentModules import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtilRt import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.getInstance import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeModifiableBase import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity import com.intellij.workspaceModel.ide.legacyBridge.ModifiableRootModelBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleExtensionBridge import com.intellij.workspaceModel.storage.CachedValue import com.intellij.workspaceModel.storage.WorkspaceEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Element import org.jetbrains.jps.model.module.JpsModuleSourceRoot import org.jetbrains.jps.model.module.JpsModuleSourceRootType import java.util.concurrent.ConcurrentHashMap internal class ModifiableRootModelBridgeImpl( diff: WorkspaceEntityStorageBuilder, override val moduleBridge: ModuleBridge, override val accessor: RootConfigurationAccessor, cacheStorageResult: Boolean = true ) : LegacyBridgeModifiableBase(diff, cacheStorageResult), ModifiableRootModelBridge, ModuleRootModelBridge { /* We save the module entity for the following case: - Modifiable model created - module disposed - modifiable model used This case can appear, for example, during maven import moduleEntity would be removed from this diff after module disposing */ private var savedModuleEntity: ModuleEntity init { savedModuleEntity = getModuleEntity(entityStorageOnDiff.current, module) ?: error("Cannot find module entity for ${module.moduleEntityId}. Bridge: '$moduleBridge'. Store: $diff") } private fun getModuleEntity(current: WorkspaceEntityStorage, myModuleBridge: ModuleBridge): ModuleEntity? { // Try to get entity by module id // In some cases this won't work. These cases can happen during maven or gradle import where we provide a general builder. // The case: we rename the module. Since the changes not yet committed, the module will remain with the old persistentId. After that // we try to get modifiableRootModel. In general case it would work fine because the builder will be based on main store, but // in case of gradle/maven import we take the builder that was used for renaming. So, the old name cannot be found in the new store. return current.resolve(myModuleBridge.moduleEntityId) ?: current.findModuleEntity(myModuleBridge) } override fun getModificationCount(): Long = diff.modificationCount private val extensionsDisposable = Disposer.newDisposable() private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project) private val extensionsDelegate = lazy { RootModelBridgeImpl.loadExtensions(storage = entityStorageOnDiff, module = module, diff = diff, writable = true, parentDisposable = extensionsDisposable) } private val extensions by extensionsDelegate private val sourceRootPropertiesMap = ConcurrentHashMap<VirtualFileUrl, JpsModuleSourceRoot>() internal val moduleEntity: ModuleEntity get() { val actualModuleEntity = getModuleEntity(entityStorageOnDiff.current, module) ?: return savedModuleEntity savedModuleEntity = actualModuleEntity return actualModuleEntity } private val moduleLibraryTable = ModifiableModuleLibraryTableBridge(this) /** * Contains instances of OrderEntries edited via [ModifiableRootModel] interfaces; we need to keep references to them to update their indices; * it should be used for modifications only, in order to read actual state one need to use [orderEntriesArray]. */ private val mutableOrderEntries: ArrayList<OrderEntryBridge> by lazy { ArrayList<OrderEntryBridge>().also { addOrderEntries(moduleEntity.dependencies, it) } } /** * Provides cached value for [mutableOrderEntries] converted to an array to avoid creating array each time [getOrderEntries] is called; * also it updates instances in [mutableOrderEntries] when underlying entities are changed via [WorkspaceModel] interface (e.g. when a * library referenced from [LibraryOrderEntry] is renamed). */ private val orderEntriesArrayValue: CachedValue<Array<OrderEntry>> = CachedValue { storage -> val dependencies = storage.findModuleEntity(module)?.dependencies ?: return@CachedValue emptyArray() if (mutableOrderEntries.size == dependencies.size) { //keep old instances of OrderEntries if possible (i.e. if only some properties of order entries were changes via WorkspaceModel) for (i in mutableOrderEntries.indices) { if (dependencies[i] != mutableOrderEntries[i].item && dependencies[i].javaClass == mutableOrderEntries[i].item.javaClass) { mutableOrderEntries[i].item = dependencies[i] } } } else { mutableOrderEntries.clear() addOrderEntries(dependencies, mutableOrderEntries) } mutableOrderEntries.toTypedArray() } private val orderEntriesArray get() = entityStorageOnDiff.cachedValue(orderEntriesArrayValue) private fun addOrderEntries(dependencies: List<ModuleDependencyItem>, target: MutableList<OrderEntryBridge>) = dependencies.mapIndexedTo(target) { index, item -> RootModelBridgeImpl.toOrderEntry(item, index, this, this::updateDependencyItem) } private val contentEntriesImplValue: CachedValue<List<ModifiableContentEntryBridge>> = CachedValue { storage -> val moduleEntity = storage.findModuleEntity(module) ?: return@CachedValue emptyList<ModifiableContentEntryBridge>() val contentEntries = moduleEntity.contentRoots.sortedBy { it.url.url }.toList() contentEntries.map { ModifiableContentEntryBridge( diff = diff, contentEntryUrl = it.url, modifiableRootModel = this ) } } private fun updateDependencyItem(index: Int, transformer: (ModuleDependencyItem) -> ModuleDependencyItem) { val oldItem = moduleEntity.dependencies[index] val newItem = transformer(oldItem) if (oldItem == newItem) return diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { val copy = dependencies.toMutableList() copy[index] = newItem dependencies = copy } } override val storage: WorkspaceEntityStorage get() = entityStorageOnDiff.current override fun getOrCreateJpsRootProperties(sourceRootUrl: VirtualFileUrl, creator: () -> JpsModuleSourceRoot): JpsModuleSourceRoot { return sourceRootPropertiesMap.computeIfAbsent(sourceRootUrl) { creator() } } override fun removeCachedJpsRootProperties(sourceRootUrl: VirtualFileUrl) { sourceRootPropertiesMap.remove(sourceRootUrl) } private val contentEntries get() = entityStorageOnDiff.cachedValue(contentEntriesImplValue) override fun getProject(): Project = moduleBridge.project override fun addContentEntry(root: VirtualFile): ContentEntry = addContentEntry(root.url) override fun addContentEntry(url: String): ContentEntry { assertModelIsLive() val virtualFileUrl = virtualFileManager.fromUrl(url) val existingEntry = contentEntries.firstOrNull { it.contentEntryUrl == virtualFileUrl } if (existingEntry != null) { return existingEntry } diff.addContentRootEntity( module = moduleEntity, excludedUrls = emptyList(), excludedPatterns = emptyList(), url = virtualFileUrl ) // TODO It's N^2 operations since we need to recreate contentEntries every time return contentEntries.firstOrNull { it.contentEntryUrl == virtualFileUrl } ?: error("addContentEntry: unable to find content entry after adding: $url to module ${moduleEntity.name}") } override fun removeContentEntry(entry: ContentEntry) { assertModelIsLive() val entryImpl = entry as ModifiableContentEntryBridge val contentEntryUrl = entryImpl.contentEntryUrl val entity = currentModel.contentEntities.firstOrNull { it.url == contentEntryUrl } ?: error("ContentEntry $entry does not belong to modifiableRootModel of module ${moduleBridge.name}") entry.clearSourceFolders() diff.removeEntity(entity) if (assertChangesApplied && contentEntries.any { it.url == contentEntryUrl.url }) { error("removeContentEntry: removed content entry url '$contentEntryUrl' still exists after removing") } } override fun addOrderEntry(orderEntry: OrderEntry) { assertModelIsLive() when (orderEntry) { is LibraryOrderEntryBridge -> { if (orderEntry.isModuleLevel) { moduleLibraryTable.addLibraryCopy(orderEntry.library as LibraryBridgeImpl, orderEntry.isExported, orderEntry.libraryDependencyItem.scope) } else { appendDependency(orderEntry.libraryDependencyItem) } } is ModuleOrderEntry -> orderEntry.module?.let { addModuleOrderEntry(it) } ?: error("Module is empty: $orderEntry") is ModuleSourceOrderEntry -> appendDependency(ModuleDependencyItem.ModuleSourceDependency) is InheritedJdkOrderEntry -> appendDependency(ModuleDependencyItem.InheritedSdkDependency) is ModuleJdkOrderEntry -> appendDependency((orderEntry as SdkOrderEntryBridge).sdkDependencyItem) else -> error("OrderEntry should not be extended by external systems") } } override fun addLibraryEntry(library: Library): LibraryOrderEntry { appendDependency(ModuleDependencyItem.Exportable.LibraryDependency( library = library.libraryId, exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE )) return (mutableOrderEntries.lastOrNull() as? LibraryOrderEntry ?: error("Unable to find library orderEntry after adding")) } private val Library.libraryId: LibraryId get() { val libraryId = if (this is LibraryBridge) libraryId else { val libraryName = name if (libraryName.isNullOrEmpty()) { error("Library name is null or empty: $this") } LibraryId(libraryName, LibraryNameGenerator.getLibraryTableId(table.tableLevel)) } return libraryId } override fun addLibraryEntries(libraries: List<Library>, scope: DependencyScope, exported: Boolean) { val dependencyScope = scope.toEntityDependencyScope() appendDependencies(libraries.map { ModuleDependencyItem.Exportable.LibraryDependency(it.libraryId, exported, dependencyScope) }) } override fun addInvalidLibrary(name: String, level: String): LibraryOrderEntry { val libraryDependency = ModuleDependencyItem.Exportable.LibraryDependency( library = LibraryId(name, LibraryNameGenerator.getLibraryTableId(level)), exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE ) appendDependency(libraryDependency) return (mutableOrderEntries.lastOrNull() as? LibraryOrderEntry ?: error("Unable to find library orderEntry after adding")) } override fun addModuleOrderEntry(module: Module): ModuleOrderEntry { val moduleDependency = ModuleDependencyItem.Exportable.ModuleDependency( module = (module as ModuleBridge).moduleEntityId, productionOnTest = false, exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE ) appendDependency(moduleDependency) return mutableOrderEntries.lastOrNull() as? ModuleOrderEntry ?: error("Unable to find module orderEntry after adding") } override fun addModuleEntries(modules: MutableList<Module>, scope: DependencyScope, exported: Boolean) { val dependencyScope = scope.toEntityDependencyScope() appendDependencies(modules.map { ModuleDependencyItem.Exportable.ModuleDependency((it as ModuleBridge).moduleEntityId, exported, dependencyScope, productionOnTest = false) }) } override fun addInvalidModuleEntry(name: String): ModuleOrderEntry { val moduleDependency = ModuleDependencyItem.Exportable.ModuleDependency( module = ModuleId(name), productionOnTest = false, exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE ) appendDependency(moduleDependency) return mutableOrderEntries.lastOrNull() as? ModuleOrderEntry ?: error("Unable to find module orderEntry after adding") } internal fun appendDependency(dependency: ModuleDependencyItem) { mutableOrderEntries.add(RootModelBridgeImpl.toOrderEntry(dependency, mutableOrderEntries.size, this, this::updateDependencyItem)) entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = dependencies + dependency } } internal fun appendDependencies(dependencies: List<ModuleDependencyItem>) { for (dependency in dependencies) { mutableOrderEntries.add(RootModelBridgeImpl.toOrderEntry(dependency, mutableOrderEntries.size, this, this::updateDependencyItem)) } entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { this.dependencies = this.dependencies + dependencies } } internal fun insertDependency(dependency: ModuleDependencyItem, position: Int): OrderEntryBridge { val last = position == mutableOrderEntries.size val newEntry = RootModelBridgeImpl.toOrderEntry(dependency, position, this, this::updateDependencyItem) if (last) { mutableOrderEntries.add(newEntry) } else { mutableOrderEntries.add(position, newEntry) for (i in position + 1 until mutableOrderEntries.size) { mutableOrderEntries[i].updateIndex(i) } } entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = if (last) dependencies + dependency else dependencies.subList(0, position) + dependency + dependencies.subList(position, dependencies.size) } return newEntry } internal fun removeDependencies(filter: (Int, ModuleDependencyItem) -> Boolean) { val newDependencies = ArrayList<ModuleDependencyItem>() val newOrderEntries = ArrayList<OrderEntryBridge>() val oldDependencies = moduleEntity.dependencies for (i in oldDependencies.indices) { if (!filter(i, oldDependencies[i])) { newDependencies.add(oldDependencies[i]) val entryBridge = mutableOrderEntries[i] entryBridge.updateIndex(newOrderEntries.size) newOrderEntries.add(entryBridge) } } mutableOrderEntries.clear() mutableOrderEntries.addAll(newOrderEntries) entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = newDependencies } } override fun findModuleOrderEntry(module: Module): ModuleOrderEntry? { return orderEntries.filterIsInstance<ModuleOrderEntry>().firstOrNull { module == it.module } } override fun findLibraryOrderEntry(library: Library): LibraryOrderEntry? { if (library is LibraryBridge) { val libraryIdToFind = library.libraryId return orderEntries .filterIsInstance<LibraryOrderEntry>() .firstOrNull { libraryIdToFind == (it.library as? LibraryBridge)?.libraryId } } else { return orderEntries.filterIsInstance<LibraryOrderEntry>().firstOrNull { it.library == library } } } override fun removeOrderEntry(orderEntry: OrderEntry) { assertModelIsLive() val entryImpl = orderEntry as OrderEntryBridge val item = entryImpl.item if (mutableOrderEntries.none { it.item == item }) { LOG.error("OrderEntry $item does not belong to modifiableRootModel of module ${moduleBridge.name}") return } if (orderEntry is LibraryOrderEntryBridge && orderEntry.isModuleLevel) { moduleLibraryTable.removeLibrary(orderEntry.library as LibraryBridge) } else { val itemIndex = entryImpl.currentIndex removeDependencies { index, _ -> index == itemIndex } } } override fun rearrangeOrderEntries(newOrder: Array<out OrderEntry>) { val newOrderEntries = newOrder.mapTo(ArrayList()) { it as OrderEntryBridge } val newEntities = newOrderEntries.map { it.item } if (newEntities.toSet() != moduleEntity.dependencies.toSet()) { error("Expected the same entities as existing order entries, but in a different order") } mutableOrderEntries.clear() mutableOrderEntries.addAll(newOrderEntries) for (i in mutableOrderEntries.indices) { mutableOrderEntries[i].updateIndex(i) } entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = newEntities } } override fun clear() { for (library in moduleLibraryTable.libraries) { moduleLibraryTable.removeLibrary(library) } val currentSdk = sdk val jdkItem = currentSdk?.let { ModuleDependencyItem.SdkDependency(it.name, it.sdkType.name) } if (moduleEntity.dependencies != listOfNotNull(jdkItem, ModuleDependencyItem.ModuleSourceDependency)) { removeDependencies { _, _ -> true } if (jdkItem != null) { appendDependency(jdkItem) } appendDependency(ModuleDependencyItem.ModuleSourceDependency) } for (contentRoot in moduleEntity.contentRoots) { diff.removeEntity(contentRoot) } } fun collectChangesAndDispose(): WorkspaceEntityStorageBuilder? { assertModelIsLive() Disposer.dispose(moduleLibraryTable) if (!isChanged) { moduleLibraryTable.restoreLibraryMappingsAndDisposeCopies() disposeWithoutLibraries() return null } if (extensionsDelegate.isInitialized() && extensions.any { it.isChanged }) { val element = Element("component") for (extension in extensions) { if (extension is ModuleExtensionBridge) continue extension.commit() if (extension is PersistentStateComponent<*>) { serializeStateInto(extension, element) } else { @Suppress("DEPRECATION") extension.writeExternal(element) } } val elementAsString = JDOMUtil.writeElement(element) val customImlDataEntity = moduleEntity.customImlData if (customImlDataEntity?.rootManagerTagCustomData != elementAsString) { when { customImlDataEntity == null && !JDOMUtil.isEmpty(element) -> diff.addModuleCustomImlDataEntity( module = moduleEntity, rootManagerTagCustomData = elementAsString, customModuleOptions = emptyMap(), source = moduleEntity.entitySource ) customImlDataEntity == null && JDOMUtil.isEmpty(element) -> Unit customImlDataEntity != null && customImlDataEntity.customModuleOptions.isEmpty() && JDOMUtil.isEmpty(element) -> diff.removeEntity(customImlDataEntity) customImlDataEntity != null && customImlDataEntity.customModuleOptions.isNotEmpty() && JDOMUtil.isEmpty(element) -> diff.modifyEntity(ModifiableModuleCustomImlDataEntity::class.java, customImlDataEntity) { rootManagerTagCustomData = null } customImlDataEntity != null && !JDOMUtil.isEmpty(element) -> diff.modifyEntity(ModifiableModuleCustomImlDataEntity::class.java, customImlDataEntity) { rootManagerTagCustomData = elementAsString } else -> error("Should not be reached") } } } if (!sourceRootPropertiesMap.isEmpty()) { for (sourceRoot in moduleEntity.sourceRoots) { val actualSourceRootData = sourceRootPropertiesMap[sourceRoot.url] ?: continue SourceRootPropertiesHelper.applyChanges(diff, sourceRoot, actualSourceRootData) } } disposeWithoutLibraries() return diff } private fun areSourceRootPropertiesChanged(): Boolean { if (sourceRootPropertiesMap.isEmpty()) return false return moduleEntity.sourceRoots.any { sourceRoot -> val actualSourceRootData = sourceRootPropertiesMap[sourceRoot.url] actualSourceRootData != null && !SourceRootPropertiesHelper.hasEqualProperties(sourceRoot, actualSourceRootData) } } override fun commit() { val diff = collectChangesAndDispose() ?: return val moduleDiff = module.diff if (moduleDiff != null) { moduleDiff.addDiff(diff) } else { WorkspaceModel.getInstance(project).updateProjectModel { it.addDiff(diff) } } postCommit() } override fun prepareForCommit() { collectChangesAndDispose() } override fun postCommit() { moduleLibraryTable.disposeOriginalLibrariesAndUpdateCopies() } override fun dispose() { disposeWithoutLibraries() moduleLibraryTable.restoreLibraryMappingsAndDisposeCopies() Disposer.dispose(moduleLibraryTable) } private fun disposeWithoutLibraries() { if (!modelIsCommittedOrDisposed) { Disposer.dispose(extensionsDisposable) } // No assertions here since it is ok to call dispose twice or more modelIsCommittedOrDisposed = true } override fun getModuleLibraryTable(): LibraryTable = moduleLibraryTable override fun setSdk(jdk: Sdk?) { if (jdk == null) { setSdkItem(null) if (assertChangesApplied && sdkName != null) { error("setSdk: expected sdkName is null, but got: $sdkName") } } else { if (ModifiableRootModelBridge.findSdk(jdk.name, jdk.sdkType.name) == null) { error("setSdk: sdk '${jdk.name}' type '${jdk.sdkType.name}' is not registered in ProjectJdkTable") } setInvalidSdk(jdk.name, jdk.sdkType.name) } } override fun setInvalidSdk(sdkName: String, sdkType: String) { setSdkItem(ModuleDependencyItem.SdkDependency(sdkName, sdkType)) if (assertChangesApplied && getSdkName() != sdkName) { error("setInvalidSdk: expected sdkName '$sdkName' but got '${getSdkName()}' after doing a change") } } override fun inheritSdk() { if (isSdkInherited) return setSdkItem(ModuleDependencyItem.InheritedSdkDependency) if (assertChangesApplied && !isSdkInherited) { error("inheritSdk: Sdk is still not inherited after inheritSdk()") } } // TODO compare by actual values override fun isChanged(): Boolean { if (!diff.isEmpty()) return true if (extensionsDelegate.isInitialized() && extensions.any { it.isChanged }) return true if (areSourceRootPropertiesChanged()) return true return false } override fun isWritable(): Boolean = true override fun <T : OrderEntry?> replaceEntryOfType(entryClass: Class<T>, entry: T) = throw NotImplementedError("Not implemented since it was used only by project model implementation") override fun getSdkName(): String? = orderEntries.filterIsInstance<JdkOrderEntry>().firstOrNull()?.jdkName // TODO override fun isDisposed(): Boolean = modelIsCommittedOrDisposed private fun setSdkItem(item: ModuleDependencyItem?) { removeDependencies { _, it -> it is ModuleDependencyItem.InheritedSdkDependency || it is ModuleDependencyItem.SdkDependency } if (item != null) { insertDependency(item, 0) } } private val modelValue = CachedValue { storage -> RootModelBridgeImpl( moduleEntity = getModuleEntity(storage, moduleBridge), storage = entityStorageOnDiff, itemUpdater = null, rootModel = this, updater = { transformer -> transformer(diff) } ) } internal val currentModel get() = entityStorageOnDiff.cachedValue(modelValue) override fun getExcludeRoots(): Array<VirtualFile> = currentModel.excludeRoots override fun orderEntries(): OrderEnumerator = ModuleOrderEnumerator(this, null) override fun <T : Any?> getModuleExtension(klass: Class<T>): T? { return extensions.filterIsInstance(klass).firstOrNull() } override fun getDependencyModuleNames(): Array<String> { val result = orderEntries().withoutSdk().withoutLibraries().withoutModuleSourceEntries().process(CollectDependentModules(), ArrayList()) return ArrayUtilRt.toStringArray(result) } override fun getModule(): ModuleBridge = moduleBridge override fun isSdkInherited(): Boolean = orderEntriesArray.any { it is InheritedJdkOrderEntry } override fun getOrderEntries(): Array<OrderEntry> = orderEntriesArray override fun getSourceRootUrls(): Array<String> = currentModel.sourceRootUrls override fun getSourceRootUrls(includingTests: Boolean): Array<String> = currentModel.getSourceRootUrls(includingTests) override fun getContentEntries(): Array<ContentEntry> = contentEntries.toTypedArray() override fun getExcludeRootUrls(): Array<String> = currentModel.excludeRootUrls override fun <R : Any?> processOrder(policy: RootPolicy<R>, initialValue: R): R { var result = initialValue for (orderEntry in orderEntries) { result = orderEntry.accept(policy, result) } return result } override fun getSdk(): Sdk? = (orderEntriesArray.find { it is JdkOrderEntry } as JdkOrderEntry?)?.jdk override fun getSourceRoots(): Array<VirtualFile> = currentModel.sourceRoots override fun getSourceRoots(includingTests: Boolean): Array<VirtualFile> = currentModel.getSourceRoots(includingTests) override fun getSourceRoots(rootType: JpsModuleSourceRootType<*>): MutableList<VirtualFile> = currentModel.getSourceRoots(rootType) override fun getSourceRoots(rootTypes: MutableSet<out JpsModuleSourceRootType<*>>): MutableList<VirtualFile> = currentModel.getSourceRoots(rootTypes) override fun getContentRoots(): Array<VirtualFile> = currentModel.contentRoots override fun getContentRootUrls(): Array<String> = currentModel.contentRootUrls override fun getModuleDependencies(): Array<Module> = getModuleDependencies(true) override fun getModuleDependencies(includeTests: Boolean): Array<Module> { var result: MutableList<Module>? = null for (entry in orderEntriesArray) { if (entry is ModuleOrderEntry) { val scope = entry.scope if (includeTests || scope.isForProductionCompile || scope.isForProductionRuntime) { val module = entry.module if (module != null) { if (result == null) { result = ArrayList() } result.add(module) } } } } return if (result.isNullOrEmpty()) Module.EMPTY_ARRAY else result.toTypedArray() } companion object { private val LOG = logger<ModifiableRootModelBridgeImpl>() } }
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModifiableRootModelBridgeImpl.kt
604671379
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.shared.data.db import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Fts4 import com.google.samples.apps.iosched.model.Session /** * This class represents [Session] data for searching with FTS. * * The [ColumnInfo] name is explicitly declared to allow flexibility for renaming the data class * properties without requiring changing the column name. */ @Entity(tableName = "sessionsFts") @Fts4 data class SessionFtsEntity( /** * An FTS entity table always has a column named rowid that is the equivalent of an * INTEGER PRIMARY KEY index. Therefore, an FTS entity can only have a single field * annotated with PrimaryKey, it must be named rowid and must be of INTEGER affinity. * * The field can be optionally omitted in the class (as is done here), * but can still be used in queries. */ /** * Unique string identifying this session. */ @ColumnInfo(name = "sessionId") val sessionId: String, /** * Session title. */ @ColumnInfo(name = "title") val title: String, /** * Body of text with the session's description. */ @ColumnInfo(name = "description") val description: String, /** * The session speaker(s), stored as a CSV String. */ @ColumnInfo(name = "speakers") val speakers: String )
shared/src/main/java/com/google/samples/apps/iosched/shared/data/db/SessionFtsEntity.kt
4208801886
package io.mstream.boardgameengine.game import com.google.common.eventbus.* import io.mstream.boardgameengine.move.* class GuavaBusEventSender( private val id: Int, private val eventBus: EventBus) : EventSender { override fun post(event: Any) { val gameEvent = GameEvent(id, event) eventBus.post(gameEvent) } }
src/main/kotlin/io.mstream.boardgameengine/game/GuavaBusEventSender.kt
2436260633
package org.thoughtcrime.securesms.mediasend.v2 import android.animation.ValueAnimator import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Bundle import android.view.KeyEvent import android.widget.FrameLayout import android.widget.TextView import androidx.activity.OnBackPressedCallback import androidx.activity.viewModels import androidx.appcompat.app.AppCompatDelegate import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintSet import androidx.core.content.ContextCompat import androidx.core.view.updateLayoutParams import androidx.lifecycle.ViewModelProvider import androidx.navigation.Navigation import androidx.navigation.fragment.NavHostFragment import androidx.transition.AutoTransition import androidx.transition.TransitionManager import com.google.android.material.animation.ArgbEvaluatorCompat import org.signal.core.util.BreakIteratorCompat import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.PassphraseRequiredActivity import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.emoji.EmojiEventListener import org.thoughtcrime.securesms.contacts.paged.ContactSearchKey import org.thoughtcrime.securesms.conversation.MessageSendType import org.thoughtcrime.securesms.keyboard.emoji.EmojiKeyboardPageFragment import org.thoughtcrime.securesms.keyboard.emoji.search.EmojiSearchFragment import org.thoughtcrime.securesms.linkpreview.LinkPreviewUtil import org.thoughtcrime.securesms.mediasend.CameraDisplay import org.thoughtcrime.securesms.mediasend.Media import org.thoughtcrime.securesms.mediasend.MediaSendActivityResult import org.thoughtcrime.securesms.mediasend.v2.review.MediaReviewFragment import org.thoughtcrime.securesms.mediasend.v2.text.TextStoryPostCreationViewModel import org.thoughtcrime.securesms.mediasend.v2.text.send.TextStoryPostSendRepository import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.safety.SafetyNumberBottomSheet import org.thoughtcrime.securesms.stories.Stories import org.thoughtcrime.securesms.util.FullscreenHelper import org.thoughtcrime.securesms.util.WindowUtil import org.thoughtcrime.securesms.util.navigation.safeNavigate import org.thoughtcrime.securesms.util.visible class MediaSelectionActivity : PassphraseRequiredActivity(), MediaReviewFragment.Callback, EmojiKeyboardPageFragment.Callback, EmojiEventListener, EmojiSearchFragment.Callback { private var animateInShadowLayerValueAnimator: ValueAnimator? = null private var animateInTextColorValueAnimator: ValueAnimator? = null private var animateOutShadowLayerValueAnimator: ValueAnimator? = null private var animateOutTextColorValueAnimator: ValueAnimator? = null lateinit var viewModel: MediaSelectionViewModel private val textViewModel: TextStoryPostCreationViewModel by viewModels( factoryProducer = { TextStoryPostCreationViewModel.Factory(TextStoryPostSendRepository()) } ) private val destination: MediaSelectionDestination get() = MediaSelectionDestination.fromBundle(requireNotNull(intent.getBundleExtra(DESTINATION))) private val isStory: Boolean get() = intent.getBooleanExtra(IS_STORY, false) private val shareToTextStory: Boolean get() = intent.getBooleanExtra(AS_TEXT_STORY, false) private val draftText: CharSequence? get() = intent.getCharSequenceExtra(MESSAGE) override fun attachBaseContext(newBase: Context) { delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_YES super.attachBaseContext(newBase) } override fun onCreate(savedInstanceState: Bundle?, ready: Boolean) { setContentView(R.layout.media_selection_activity) FullscreenHelper.showSystemUI(window) WindowUtil.setNavigationBarColor(this, 0x01000000) WindowUtil.setStatusBarColor(window, Color.TRANSPARENT) val sendType: MessageSendType = requireNotNull(intent.getParcelableExtra(MESSAGE_SEND_TYPE)) val initialMedia: List<Media> = intent.getParcelableArrayListExtra(MEDIA) ?: listOf() val message: CharSequence? = if (shareToTextStory) null else draftText val isReply: Boolean = intent.getBooleanExtra(IS_REPLY, false) val factory = MediaSelectionViewModel.Factory(destination, sendType, initialMedia, message, isReply, isStory, MediaSelectionRepository(this)) viewModel = ViewModelProvider(this, factory)[MediaSelectionViewModel::class.java] val textStoryToggle: ConstraintLayout = findViewById(R.id.switch_widget) val cameraDisplay = CameraDisplay.getDisplay(this) textStoryToggle.updateLayoutParams<FrameLayout.LayoutParams> { bottomMargin = cameraDisplay.getToggleBottomMargin() } val cameraSelectedConstraintSet = ConstraintSet().apply { clone(textStoryToggle) } val textSelectedConstraintSet = ConstraintSet().apply { clone(this@MediaSelectionActivity, R.layout.media_selection_activity_text_selected_constraints) } val textSwitch: TextView = findViewById(R.id.text_switch) val cameraSwitch: TextView = findViewById(R.id.camera_switch) textSwitch.setOnClickListener { viewModel.sendCommand(HudCommand.GoToText) } cameraSwitch.setOnClickListener { viewModel.sendCommand(HudCommand.GoToCapture) } if (savedInstanceState == null) { if (shareToTextStory) { initializeTextStory() } cameraSwitch.isSelected = true val navHostFragment = NavHostFragment.create(R.navigation.media) supportFragmentManager .beginTransaction() .replace(R.id.fragment_container, navHostFragment, NAV_HOST_TAG) .commitNowAllowingStateLoss() navigateToStartDestination() } else { viewModel.onRestoreState(savedInstanceState) textViewModel.restoreFromInstanceState(savedInstanceState) } (supportFragmentManager.findFragmentByTag(NAV_HOST_TAG) as NavHostFragment).navController.addOnDestinationChangedListener { _, d, _ -> when (d.id) { R.id.mediaCaptureFragment -> { textStoryToggle.visible = canDisplayStorySwitch() animateTextStyling(cameraSwitch, textSwitch, 200) TransitionManager.beginDelayedTransition(textStoryToggle, AutoTransition().setDuration(200)) cameraSelectedConstraintSet.applyTo(textStoryToggle) } R.id.textStoryPostCreationFragment -> { textStoryToggle.visible = canDisplayStorySwitch() animateTextStyling(textSwitch, cameraSwitch, 200) TransitionManager.beginDelayedTransition(textStoryToggle, AutoTransition().setDuration(200)) textSelectedConstraintSet.applyTo(textStoryToggle) } else -> textStoryToggle.visible = false } } onBackPressedDispatcher.addCallback(OnBackPressed()) } private fun animateTextStyling(selectedSwitch: TextView, unselectedSwitch: TextView, duration: Long) { val offTextColor = ContextCompat.getColor(this, R.color.signal_colorOnSurface) val onTextColor = ContextCompat.getColor(this, R.color.signal_colorSecondaryContainer) animateInShadowLayerValueAnimator?.cancel() animateInTextColorValueAnimator?.cancel() animateOutShadowLayerValueAnimator?.cancel() animateOutTextColorValueAnimator?.cancel() animateInShadowLayerValueAnimator = ValueAnimator.ofFloat(selectedSwitch.shadowRadius, 0f).apply { this.duration = duration addUpdateListener { selectedSwitch.setShadowLayer(it.animatedValue as Float, 0f, 0f, Color.BLACK) } start() } animateInTextColorValueAnimator = ValueAnimator.ofObject(ArgbEvaluatorCompat(), selectedSwitch.currentTextColor, onTextColor).apply { setEvaluator(ArgbEvaluatorCompat.getInstance()) this.duration = duration addUpdateListener { selectedSwitch.setTextColor(it.animatedValue as Int) } start() } animateOutShadowLayerValueAnimator = ValueAnimator.ofFloat(unselectedSwitch.shadowRadius, 3f).apply { this.duration = duration addUpdateListener { unselectedSwitch.setShadowLayer(it.animatedValue as Float, 0f, 0f, Color.BLACK) } start() } animateOutTextColorValueAnimator = ValueAnimator.ofObject(ArgbEvaluatorCompat(), unselectedSwitch.currentTextColor, offTextColor).apply { setEvaluator(ArgbEvaluatorCompat.getInstance()) this.duration = duration addUpdateListener { unselectedSwitch.setTextColor(it.animatedValue as Int) } start() } } private fun initializeTextStory() { val message = draftText?.toString() ?: return val firstLink = LinkPreviewUtil.findValidPreviewUrls(message).findFirst() val firstLinkUrl = firstLink.map { it.url }.orElse(null) val iterator = BreakIteratorCompat.getInstance() iterator.setText(message) val trimmedMessage = iterator.take(700).toString() if (firstLinkUrl == message) { textViewModel.setLinkPreview(firstLinkUrl) } else if (firstLinkUrl != null) { textViewModel.setLinkPreview(firstLinkUrl) textViewModel.setBody(trimmedMessage.replace(firstLinkUrl, "").trim()) } else { textViewModel.setBody(trimmedMessage.trim()) } } private fun canDisplayStorySwitch(): Boolean { return Stories.isFeatureEnabled() && isCameraFirst() && !viewModel.hasSelectedMedia() && destination == MediaSelectionDestination.ChooseAfterMediaSelection } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) viewModel.onSaveState(outState) textViewModel.saveToInstanceState(outState) } override fun onSentWithResult(mediaSendActivityResult: MediaSendActivityResult) { setResult( RESULT_OK, Intent().apply { putExtra(MediaSendActivityResult.EXTRA_RESULT, mediaSendActivityResult) } ) finish() overridePendingTransition(R.anim.stationary, R.anim.camera_slide_to_bottom) } override fun onSentWithoutResult() { val intent = Intent() setResult(RESULT_OK, intent) finish() overridePendingTransition(R.anim.stationary, R.anim.camera_slide_to_bottom) } override fun onSendError(error: Throwable) { if (error is UntrustedRecords.UntrustedRecordsException) { Log.w(TAG, "Send failed due to untrusted identities.") SafetyNumberBottomSheet .forIdentityRecordsAndDestinations(error.untrustedRecords, error.destinations.toList()) .show(supportFragmentManager) } else { setResult(RESULT_CANCELED) // TODO [alex] - Toast Log.w(TAG, "Failed to send message.", error) finish() overridePendingTransition(R.anim.stationary, R.anim.camera_slide_to_bottom) } } override fun onNoMediaSelected() { Log.w(TAG, "No media selected. Exiting.") setResult(RESULT_CANCELED) finish() overridePendingTransition(R.anim.stationary, R.anim.camera_slide_to_bottom) } override fun onPopFromReview() { if (isCameraFirst()) { viewModel.removeCameraFirstCapture() } if (!navigateToStartDestination()) { finish() } } private fun navigateToStartDestination(navHostFragment: NavHostFragment? = null): Boolean { val hostFragment: NavHostFragment = navHostFragment ?: supportFragmentManager.findFragmentByTag(NAV_HOST_TAG) as NavHostFragment val startDestination: Int = intent.getIntExtra(START_ACTION, -1) return if (startDestination > 0) { hostFragment.navController.safeNavigate( startDestination, Bundle().apply { putBoolean("first", true) } ) true } else { false } } private fun isCameraFirst(): Boolean = intent.getIntExtra(START_ACTION, -1) == R.id.action_directly_to_mediaCaptureFragment override fun openEmojiSearch() { viewModel.sendCommand(HudCommand.OpenEmojiSearch) } override fun onEmojiSelected(emoji: String?) { viewModel.sendCommand(HudCommand.EmojiInsert(emoji)) } override fun onKeyEvent(keyEvent: KeyEvent?) { viewModel.sendCommand(HudCommand.EmojiKeyEvent(keyEvent)) } override fun closeEmojiSearch() { viewModel.sendCommand(HudCommand.CloseEmojiSearch) } private inner class OnBackPressed : OnBackPressedCallback(true) { override fun handleOnBackPressed() { val navController = Navigation.findNavController(this@MediaSelectionActivity, R.id.fragment_container) if (shareToTextStory && navController.currentDestination?.id == R.id.textStoryPostCreationFragment) { finish() } if (!navController.popBackStack()) { finish() } } } companion object { private val TAG = Log.tag(MediaSelectionActivity::class.java) private const val NAV_HOST_TAG = "NAV_HOST" private const val START_ACTION = "start.action" private const val MESSAGE_SEND_TYPE = "message.send.type" private const val MEDIA = "media" private const val MESSAGE = "message" private const val DESTINATION = "destination" private const val IS_REPLY = "is_reply" private const val IS_STORY = "is_story" private const val AS_TEXT_STORY = "as_text_story" @JvmStatic fun camera(context: Context): Intent { return camera(context, false) } @JvmStatic fun camera(context: Context, isStory: Boolean): Intent { return buildIntent( context = context, startAction = R.id.action_directly_to_mediaCaptureFragment, isStory = isStory ) } @JvmStatic fun camera( context: Context, messageSendType: MessageSendType, recipientId: RecipientId, isReply: Boolean ): Intent { return buildIntent( context = context, startAction = R.id.action_directly_to_mediaCaptureFragment, messageSendType = messageSendType, destination = MediaSelectionDestination.SingleRecipient(recipientId), isReply = isReply ) } @JvmStatic fun gallery( context: Context, messageSendType: MessageSendType, media: List<Media>, recipientId: RecipientId, message: CharSequence?, isReply: Boolean ): Intent { return buildIntent( context = context, startAction = R.id.action_directly_to_mediaGalleryFragment, messageSendType = messageSendType, media = media, destination = MediaSelectionDestination.SingleRecipient(recipientId), message = message, isReply = isReply ) } @JvmStatic fun editor( context: Context, messageSendType: MessageSendType, media: List<Media>, recipientId: RecipientId, message: CharSequence? ): Intent { return buildIntent( context = context, messageSendType = messageSendType, media = media, destination = MediaSelectionDestination.SingleRecipient(recipientId), message = message ) } @JvmStatic fun editor( context: Context, media: List<Media>, ): Intent { return buildIntent( context = context, media = media ) } @JvmStatic fun share( context: Context, messageSendType: MessageSendType, media: List<Media>, recipientSearchKeys: List<ContactSearchKey.RecipientSearchKey>, message: CharSequence?, asTextStory: Boolean ): Intent { return buildIntent( context = context, messageSendType = messageSendType, media = media, destination = MediaSelectionDestination.MultipleRecipients(recipientSearchKeys), message = message, asTextStory = asTextStory, startAction = if (asTextStory) R.id.action_directly_to_textPostCreationFragment else -1, isStory = recipientSearchKeys.any { it.isStory } ) } private fun buildIntent( context: Context, startAction: Int = -1, messageSendType: MessageSendType = MessageSendType.SignalMessageSendType, media: List<Media> = listOf(), destination: MediaSelectionDestination = MediaSelectionDestination.ChooseAfterMediaSelection, message: CharSequence? = null, isReply: Boolean = false, isStory: Boolean = false, asTextStory: Boolean = false ): Intent { return Intent(context, MediaSelectionActivity::class.java).apply { putExtra(START_ACTION, startAction) putExtra(MESSAGE_SEND_TYPE, messageSendType) putParcelableArrayListExtra(MEDIA, ArrayList(media)) putExtra(MESSAGE, message) putExtra(DESTINATION, destination.toBundle()) putExtra(IS_REPLY, isReply) putExtra(IS_STORY, isStory) putExtra(AS_TEXT_STORY, asTextStory) } } } }
app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/MediaSelectionActivity.kt
1414796983
// IS_APPLICABLE: true fun foo() { bar(name1 = 3, name2 = 2, name3 = 1) <caret>{ it } } fun bar(name1: Int, name2: Int, name3: Int, name4: (Int) -> Int): Int { return name4(name1) + name2 + name3 }
plugins/kotlin/idea/tests/testData/intentions/moveLambdaInsideParentheses/moveLambda7.kt
2433897903
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui import java.util.* interface GHLoadingModel { val loading: Boolean val resultAvailable: Boolean val error: Throwable? fun addStateChangeListener(listener: StateChangeListener) interface StateChangeListener : EventListener { fun onLoadingStarted() {} fun onLoadingCompleted() {} fun onReset() { onLoadingCompleted() } } }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHLoadingModel.kt
1109231360
// MOVE: down // class A class A { // class B <caret>class B { } // fun foo fun foo() { } }
plugins/kotlin/idea/tests/testData/codeInsight/moveUpDown/classBodyDeclarations/class/classAtFunction1.kt
1024664538
// 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.sealedSubClassToObject import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtPsiFactory.CallableBuilder import org.jetbrains.kotlin.psi.KtPsiFactory.CallableBuilder.Target.FUNCTION import org.jetbrains.kotlin.psi.psiUtil.getParentOfType class GenerateIdentityEqualsFix : LocalQuickFix { override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val klass = descriptor.psiElement.getParentOfType<KtClass>(false) ?: return val factory = KtPsiFactory(klass) val equalsFunction = factory.createFunction( CallableBuilder(FUNCTION).apply { modifier(KtTokens.OVERRIDE_KEYWORD.value) typeParams() name("equals") param("other", "Any?") returnType("Boolean") blockBody("return this === other") }.asString() ) klass.addDeclaration(equalsFunction) val hashCodeFunction = factory.createFunction( CallableBuilder(FUNCTION).apply { modifier(KtTokens.OVERRIDE_KEYWORD.value) typeParams() name("hashCode") returnType("Int") blockBody("return System.identityHashCode(this)") }.asString() ) klass.addDeclaration(hashCodeFunction) } override fun getFamilyName() = KotlinBundle.message("generate.identity.equals.fix.family.name") }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/sealedSubClassToObject/GenerateIdentityEqualsFix.kt
2849553832
// 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.j2k.ast import com.intellij.psi.PsiElement import org.jetbrains.kotlin.j2k.CodeBuilder import org.jetbrains.kotlin.j2k.append class MethodCallExpression( val methodExpression: Expression, val argumentList: ArgumentList, val typeArguments: List<Type>, override val isNullable: Boolean ) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.appendOperand(this, methodExpression).append(typeArguments, ", ", "<", ">") builder.append(argumentList) } companion object { fun buildNonNull( receiver: Expression?, methodName: String, argumentList: ArgumentList = ArgumentList.withNoPrototype(), typeArguments: List<Type> = emptyList(), dotPrototype: PsiElement? = null ): MethodCallExpression = build(receiver, methodName, argumentList, typeArguments, false, dotPrototype) fun buildNullable( receiver: Expression?, methodName: String, argumentList: ArgumentList = ArgumentList.withNoPrototype(), typeArguments: List<Type> = emptyList(), dotPrototype: PsiElement? = null ): MethodCallExpression = build(receiver, methodName, argumentList, typeArguments, true, dotPrototype) fun build( receiver: Expression?, methodName: String, argumentList: ArgumentList, typeArguments: List<Type>, isNullable: Boolean, dotPrototype: PsiElement? = null ): MethodCallExpression { val identifier = Identifier.withNoPrototype(methodName, isNullable = false) val methodExpression = if (receiver != null) QualifiedExpression(receiver, identifier, dotPrototype).assignNoPrototype() else identifier return MethodCallExpression(methodExpression, argumentList, typeArguments, isNullable) } } }
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/MethodCallExpression.kt
2728995272
// "Replace with dot call" "true" // WITH_RUNTIME fun foo(a: String) { a<caret>?.toLowerCase() }
plugins/kotlin/idea/tests/testData/quickfix/replaceWithDotCall/functionCall.kt
4225710824
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * econsim-tr01 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01 import alice.tuprolog.Prolog import cc.altruix.econsimtr01.ch03.ValidationResult import cc.altruix.javaprologinterop.PlUtils import net.sourceforge.plantuml.SourceStringReader import org.fest.assertions.Assertions import org.joda.time.DateTime import org.joda.time.DateTimeConstants import org.joda.time.Duration import org.slf4j.LoggerFactory import java.io.File import java.util.* /** * @author Dmitri Pisarenko ([email protected]) * @version $Id$ * @since 1.0 */ fun secondsToDuration(seconds: Long) = Duration(0, seconds * 1000) fun composeHourMinuteFiringFunction(hours:Int, minutes:Int): (DateTime) -> Boolean { val fire: (DateTime) -> Boolean = { t -> val curHours = t.hourOfDay val curMinutes = t.minuteOfHour val curSeconds = t.secondOfMinute if ((curHours > 0) && (hours > 0) && ((curHours % hours) == 0) && (curMinutes == minutes) && (curSeconds == 0)) { true } else if ((curHours == 0) && (hours == 0) && (curMinutes == minutes) && (curSeconds == 0)) { true } else { false } } return fire } fun StringBuilder.newLine() { this.append('\n') } fun Int.toFixedLengthString(len:Int):String { return String.format("%0" + "$len" + "d", this) } fun dailyAtMidnight() = daily(0, 0) fun daily(hour:Int, minute:Int) = { time:DateTime -> ((time.hourOfDay == hour) && (time.minuteOfHour == minute) && (time.secondOfMinute == 0)) } fun String.removeSingleQuotes():String { return PlUtils.removeSingleQuotes(this) } fun String.toSequenceDiagramFile(file: File) { val reader = SourceStringReader(this) reader.generateImage(file) } fun Long.millisToSimulationDateTime(): DateTime { val period = Duration(0, this).toPeriod() val t0 = t0() val t = t0.plus(period) return t } fun Long.secondsToSimulationDateTime(): DateTime = (this * 1000L).millisToSimulationDateTime() fun t0() = DateTime(0, 1, 1, 0, 0, 0, 0) fun DateTime.isEqualTo(expected:DateTime) { Assertions.assertThat(this).isEqualTo(expected) } fun Long.toSimulationDateTimeString():String = this.millisToSimulationDateTime().toSimulationDateTimeString() fun DateTime.toSimulationDateTimeString():String { val hours = this.hourOfDay.toFixedLengthString(2) val minutes = this.minuteOfHour.toFixedLengthString(2) val year = this.year.toFixedLengthString(4) val months = this.monthOfYear.toFixedLengthString(2) val days = this.dayOfMonth.toFixedLengthString(2) return "$year-$months-$days $hours:$minutes" } fun String.toPrologTheory(): Prolog { val prolog = PlUtils.createEngine() PlUtils.loadPrologTheoryAsText(prolog, this) return prolog } fun Prolog.getResults(query:String, varName:String):List<String> { return PlUtils.getResults(this, query, varName) } fun Prolog.getResults(query: String, vararg varNames:String):List<Map<String, String>> { return PlUtils.getResults(this, query, varNames) } fun String?.emptyIfNull():String { if (this == null) { return "" } return this } fun DateTime.millisSinceT0():Long { return this.minus(t0().millis).millis } fun DateTime.secondsSinceT0():Long { return this.millisSinceT0()/1000L } fun DateTime.toDayOfWeekName():String { when (this.dayOfWeek) { DateTimeConstants.MONDAY -> return "Monday" DateTimeConstants.TUESDAY -> return "Tuesday" DateTimeConstants.WEDNESDAY -> return "Wednesday" DateTimeConstants.THURSDAY -> return "Thursday" DateTimeConstants.FRIDAY -> return "Friday" DateTimeConstants.SATURDAY -> return "Saturday" DateTimeConstants.SUNDAY -> return "Sunday" } return "" } fun Prolog.extractSingleDouble(query: String, varName:String):Double { val result = PlUtils.getResults(this, query, varName)?.firstOrNull() if (result != null) { return result.toDouble() } LoggerFactory.getLogger(Prolog::class.java).error( "Can't find double value. Query: '$query', variable: '$varName" ) return -1.0 } fun Prolog.extractSingleInt(query: String, varName:String):Int { val result = PlUtils.getResults(this, query, varName)?.firstOrNull() if (result != null) { return result.toInt() } LoggerFactory.getLogger(Prolog::class.java).error( "Can't find int value. Query: '$query', variable: '$varName" ) return -1 } fun getSubscriberCount(prolog: Prolog, time: Long, interactions: Int): Double { val resId = String.format("r%02d-pc%d", (5 + interactions), interactions) val subscriberResourceLevel = prolog.extractSingleDouble( "resourceLevel($time, 'list', '$resId', Val).", "Val" ) return subscriberResourceLevel } fun findAgent(id: String, agentList: List<IAgent>) = agentList .filter { x -> x.id().equals(id) } .firstOrNull() fun DateTime.isBusinessDay():Boolean = when (this.dayOfWeek) { DateTimeConstants.SATURDAY, DateTimeConstants.SUNDAY -> false else -> true } fun <T>List<T>.extractRandomElements(percentageToExtract:Double, random:Random):List<T> { val elementsCount = (this.size * percentageToExtract).toInt() val processedIndices = ArrayList<Int>(elementsCount) for (i in 1..elementsCount) { var elemIdx = random.nextInt(this.size) while (processedIndices.contains(elemIdx)) { elemIdx = random.nextInt(this.size) } processedIndices.add(elemIdx) } return processedIndices.map { this.get(it) }.toList() } // We need to set the seed in order to always get the same random numbers fun createRandom():java.util.Random = java.util.Random(8682522807148012L) fun randomEventWithProbability(probability:Double) = Random.nextDouble() <= probability fun createCorrectValidationResult():ValidationResult = ValidationResult(true, "") fun createIncorrectValidationResult(msg:String):ValidationResult = ValidationResult(false, msg) fun String.parseDayMonthString() : DayAndMonth { val parts = this.split(".") return DayAndMonth(parts[0].toInt(), parts[1].toInt()) } fun DayAndMonth.toDateTime() : DateTime { var day = 0L.millisToSimulationDateTime() day = day.plusMonths(this.month - 1) day = day.plusDays(this.day - 1) return day } fun calculateBusinessDays( start: DayAndMonth, end: DayAndMonth ): Int { var day = start.toDateTime() val end = end.toDateTime() var businessDays = 0 do { if ((day.dayOfWeek != DateTimeConstants.SATURDAY) && (day .dayOfWeek != DateTimeConstants.SUNDAY)) { businessDays++ } day = day.plusDays(1) } while (day.isBefore(end) || day.isEqual(end)) return businessDays } fun DayAndMonth.toDateTime(year:Int) = DateTime(year, this.month, this.day, 0, 0) fun DateTime.between(start:DayAndMonth, end:DayAndMonth):Boolean { val startDateTime = start.toDateTime(this.year) val endDateTime = end.toDateTime(this.year) return (startDateTime.isBefore(this) || startDateTime.isEqual(this)) && (endDateTime.isAfter(this) || endDateTime.isEqual(this)) } fun DateTime.evenHourAndMinute(hour:Int, minute:Int):Boolean = (this.hourOfDay == hour) && (this.minuteOfHour == minute)
src/main/java/cc/altruix/econsimtr01/Utils.kt
2543616189
// 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.jps.build import org.jetbrains.jps.model.JpsProject import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService import org.jetbrains.kotlin.incremental.storage.RelativeFileToPathConverter internal class JpsFileToPathConverter( jpsProject: JpsProject ) : RelativeFileToPathConverter(JpsModelSerializationDataService.getBaseDirectory(jpsProject))
plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/jps/build/JpsFileToPathConverter.kt
580808002
package io.github.feelfreelinux.wykopmobilny.api.links import io.github.feelfreelinux.wykopmobilny.api.WykopImageFile import io.github.feelfreelinux.wykopmobilny.models.dataclass.Downvoter import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link import io.github.feelfreelinux.wykopmobilny.models.dataclass.LinkComment import io.github.feelfreelinux.wykopmobilny.models.dataclass.LinkVoteResponsePublishModel import io.github.feelfreelinux.wykopmobilny.models.dataclass.Related import io.github.feelfreelinux.wykopmobilny.models.dataclass.Upvoter import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.DigResponse import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.LinkVoteResponse import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.VoteResponse import io.reactivex.Single import io.reactivex.subjects.PublishSubject interface LinksApi { val burySubject: PublishSubject<LinkVoteResponsePublishModel> val digSubject: PublishSubject<LinkVoteResponsePublishModel> val voteRemoveSubject: PublishSubject<LinkVoteResponsePublishModel> fun getPromoted(page: Int): Single<List<Link>> fun getUpcoming(page: Int, sortBy: String): Single<List<Link>> fun getObserved(page: Int): Single<List<Link>> fun getLinkComments(linkId: Int, sortBy: String): Single<List<LinkComment>> fun getLink(linkId: Int): Single<Link> fun commentVoteUp(linkId: Int): Single<LinkVoteResponse> fun commentVoteDown(linkId: Int): Single<LinkVoteResponse> fun relatedVoteUp(relatedId: Int): Single<VoteResponse> fun relatedVoteDown(relatedId: Int): Single<VoteResponse> fun commentVoteCancel(linkId: Int): Single<LinkVoteResponse> fun commentDelete(commentId: Int): Single<LinkComment> fun commentAdd( body: String, plus18: Boolean, inputStream: WykopImageFile, linkId: Int, linkComment: Int ): Single<LinkComment> fun relatedAdd( title: String, url: String, plus18: Boolean, linkId: Int ): Single<Related> fun commentAdd( body: String, embed: String?, plus18: Boolean, linkId: Int, linkComment: Int ): Single<LinkComment> fun commentAdd( body: String, plus18: Boolean, inputStream: WykopImageFile, linkId: Int ): Single<LinkComment> fun commentAdd( body: String, embed: String?, plus18: Boolean, linkId: Int ): Single<LinkComment> fun commentEdit(body: String, linkId: Int): Single<LinkComment> fun voteUp(linkId: Int, notifyPublisher: Boolean = true): Single<DigResponse> fun voteDown(linkId: Int, reason: Int, notifyPublisher: Boolean = true): Single<DigResponse> fun voteRemove(linkId: Int, notifyPublisher: Boolean = true): Single<DigResponse> fun getUpvoters(linkId: Int): Single<List<Upvoter>> fun getDownvoters(linkId: Int): Single<List<Downvoter>> fun markFavorite(linkId: Int): Single<Boolean> fun getRelated(linkId: Int): Single<List<Related>> }
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/api/links/LinksApi.kt
2261788839
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.fir.low.level.api.file.structure import org.jetbrains.kotlin.fir.declarations.FirDeclaration import org.jetbrains.kotlin.fir.declarations.FirFile import org.jetbrains.kotlin.fir.declarations.FirProperty import org.jetbrains.kotlin.fir.declarations.FirSimpleFunction import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtProperty internal object FileElementFactory { /** * should be consistent with [isReanalyzableContainer] */ fun createFileStructureElement( firDeclaration: FirDeclaration, ktDeclaration: KtDeclaration, firFile: FirFile, ): FileStructureElement = when { ktDeclaration is KtNamedFunction && ktDeclaration.isReanalyzableContainer() -> ReanalyzableFunctionStructureElement( firFile, ktDeclaration, (firDeclaration as FirSimpleFunction).symbol, ktDeclaration.modificationStamp ) ktDeclaration is KtProperty && ktDeclaration.isReanalyzableContainer() -> ReanalyzablePropertyStructureElement( firFile, ktDeclaration, (firDeclaration as FirProperty).symbol, ktDeclaration.modificationStamp ) else -> NonReanalyzableDeclarationStructureElement( firFile, firDeclaration, ktDeclaration, ) } /** * should be consistent with [createFileStructureElement] */ fun isReanalyzableContainer( ktDeclaration: KtDeclaration, ): Boolean = when (ktDeclaration) { is KtNamedFunction -> ktDeclaration.isReanalyzableContainer() is KtProperty -> ktDeclaration.isReanalyzableContainer() else -> false } private fun KtNamedFunction.isReanalyzableContainer() = name != null && hasExplicitTypeOrUnit private fun KtProperty.isReanalyzableContainer() = name != null && typeReference != null private val KtNamedFunction.hasExplicitTypeOrUnit get() = hasBlockBody() || typeReference != null }
plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/file/structure/FileElementFactory.kt
3532455424
// WITH_RUNTIME fun foo() { val listOf = listOf(1, 2, 3) listOf.size<caret> == 0 }
plugins/kotlin/idea/tests/testData/intentions/replaceSizeZeroCheckWithIsEmpty/list.kt
4154972431
package bolone.rp import alraune.* import alraune.entity.* import aplight.GelNew import bolone.nextOrderFileID import vgrechka.* class BoloneRP_CopyOrderFileToBucket(val p: Params) : Dancer<Any> { // TODO:vgrechka b14c4503-0611-42c7-a192-fb1208c1fedd @GelNew class Params { var orderHandle by place<JsonizableOrderHandle>() var fileID by place<Long>() var toBucket by place<String>() } override fun dance(): Any { clog("p", freakingToStringKotlin(p)) rpCheckAdmin() !object : UpdateOrder(p.orderHandle.toNormal(), "Copy file #${p.fileID} to bucket `${p.toBucket}`") { override fun specificUpdates() { val bf = order.bucketAndFileByID(p.fileID) val toBucket = order.bucket(p.toBucket) toBucket.files.add(cloneViaJson(bf.file).also { it.id = nextOrderFileID() it.copiedFrom = new_Order_File_Reference(bucketName = bf.bucket.name, fileID = bf.file.id)}) } override fun makeOperationData(template: Order.Operation) = new_Order_Operation_Generic(template) } return GenericCoolRPResult() } }
alraune/alraune/src/main/java/bolone/rp/BoloneRP_CopyOrderFileToBucket.kt
240587954
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.client import com.intellij.codeWithMe.ClientId import com.intellij.ide.plugins.IdeaPluginDescriptorImpl import com.intellij.openapi.application.Application import com.intellij.openapi.components.ServiceDescriptor import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.ProgressIndicatorProvider import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.serviceContainer.PrecomputedExtensionModel import com.intellij.serviceContainer.throwAlreadyDisposedError import org.jetbrains.annotations.ApiStatus import java.util.concurrent.CompletableFuture @ApiStatus.Internal abstract class ClientAwareComponentManager @JvmOverloads constructor( internal val parent: ComponentManagerImpl?, setExtensionsRootArea: Boolean = parent == null) : ComponentManagerImpl(parent, setExtensionsRootArea) { override fun <T : Any> getService(serviceClass: Class<T>): T? { return getFromSelfOrCurrentSession(serviceClass, true) } override fun <T : Any> getServiceIfCreated(serviceClass: Class<T>): T? { return getFromSelfOrCurrentSession(serviceClass, false) } override fun <T : Any> getServices(serviceClass: Class<T>, includeLocal: Boolean): List<T> { val sessionsManager = super.getService(ClientSessionsManager::class.java)!! return sessionsManager.getSessions(includeLocal) .mapNotNull { (it as? ClientSessionImpl)?.doGetService(serviceClass, true, false) } } private fun <T : Any> getFromSelfOrCurrentSession(serviceClass: Class<T>, createIfNeeded: Boolean): T? { val fromSelf = if (createIfNeeded) { super.getService(serviceClass) } else { super.getServiceIfCreated(serviceClass) } if (fromSelf != null) return fromSelf val sessionsManager = if (containerState.get() == ContainerState.DISPOSE_COMPLETED) { if (createIfNeeded) { throwAlreadyDisposedError(serviceClass.name, this, ProgressIndicatorProvider.getGlobalProgressIndicator()) } super.doGetService(ClientSessionsManager::class.java, false) } else { super.getService(ClientSessionsManager::class.java) } val session = sessionsManager?.getSession(ClientId.current) as? ClientSessionImpl return session?.doGetService(serviceClass, createIfNeeded, false) } override fun registerComponents(modules: Sequence<IdeaPluginDescriptorImpl>, app: Application?, precomputedExtensionModel: PrecomputedExtensionModel?, listenerCallbacks: MutableList<in Runnable>?) { super.registerComponents(modules, app, precomputedExtensionModel, listenerCallbacks) val sessionsManager = super.getService(ClientSessionsManager::class.java)!! for (session in sessionsManager.getSessions(true)) { (session as? ClientSessionImpl)?.registerComponents(modules, app, precomputedExtensionModel, listenerCallbacks) } } override fun unloadServices(services: List<ServiceDescriptor>, pluginId: PluginId) { super.unloadServices(services, pluginId) val sessionsManager = super.getService(ClientSessionsManager::class.java)!! for (session in sessionsManager.getSessions(true)) { (session as? ClientSessionImpl)?.unloadServices(services, pluginId) } } override fun preloadServices(modules: Sequence<IdeaPluginDescriptorImpl>, activityPrefix: String, onlyIfAwait: Boolean): PreloadServicesResult { val result = super.preloadServices(modules, activityPrefix, onlyIfAwait) val sessionsManager = super.getService(ClientSessionsManager::class.java)!! val syncPreloadFutures = mutableListOf<CompletableFuture<*>>() val asyncPreloadFutures = mutableListOf<CompletableFuture<*>>() for (session in sessionsManager.getSessions(true)) { session as? ClientSessionImpl ?: continue val sessionResult = session.preloadServices(modules, activityPrefix, onlyIfAwait) syncPreloadFutures.add(sessionResult.sync) asyncPreloadFutures.add(sessionResult.async) } return PreloadServicesResult( sync = CompletableFuture.allOf(result.sync, *syncPreloadFutures.toTypedArray()), async = CompletableFuture.allOf(result.async, *asyncPreloadFutures.toTypedArray()) ) } override fun isPreInitialized(component: Any): Boolean { return super.isPreInitialized(component) || component is ClientSessionsManager<*> } }
platform/platform-impl/src/com/intellij/openapi/client/ClientAwareComponentManager.kt
3656981520
package net.erikkarlsson.smashapp.base.data.model.tournament data class Participant(val id: Long, val name: String, val seed: Int) { companion object { @JvmField val NO_PARTICIPANT = Participant(0L, "", 0) } }
app/src/main/java/net/erikkarlsson/smashapp/base/data/model/tournament/Participant.kt
3788769773
// 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.jetbrains.python.sdk import com.intellij.icons.AllIcons import com.intellij.openapi.module.Module import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkType import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.io.FileUtil import com.intellij.ui.LayeredIcon import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.SimpleTextAttributes import com.jetbrains.python.PyBundle import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.sdk.flavors.PythonSdkFlavor import org.jetbrains.annotations.Nls import javax.swing.Icon val noInterpreterMarker: String = "<${PyBundle.message("python.sdk.there.is.no.interpreter")}>" fun name(sdk: Sdk): Triple<String?, String, String?> = name(sdk, sdk.name) /** * Returns modifier that shortly describes that is wrong with passed [sdk], [name] and additional info. */ fun name(sdk: Sdk, name: String): Triple<String?, String, String?> { val modifier = when { PythonSdkUtil.isInvalid(sdk) || PythonSdkType.hasInvalidRemoteCredentials(sdk) -> "invalid" PythonSdkType.isIncompleteRemote(sdk) -> "incomplete" !LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) -> "unsupported" else -> null } val providedForSdk = PySdkProvider.EP_NAME.extensions.firstNotNullOfOrNull { it.getSdkAdditionalText(sdk) } val secondary = providedForSdk ?: if (PythonSdkType.isRunAsRootViaSudo(sdk)) "[sudo]" else null return Triple(modifier, name, secondary) } /** * Returns a path to be rendered as the sdk's path. * * Initial value is taken from the [sdk], * then it is converted to a path relative to the user home directory. * * Returns null if the initial path or the relative value are presented in the sdk's name. * * @see FileUtil.getLocationRelativeToUserHome */ fun path(sdk: Sdk): String? { val name = sdk.name val homePath = sdk.homePath ?: return null if (sdk.isTargetBased()) { return homePath.removePrefix("target://") } if (sdk.sdkAdditionalData is PyRemoteSdkAdditionalDataMarker) { return homePath.takeIf { homePath !in name } } return homePath.let { FileUtil.getLocationRelativeToUserHome(it) }.takeIf { homePath !in name && it !in name } } /** * Returns an icon to be used as the sdk's icon. * * Result is wrapped with [AllIcons.Actions.Cancel] * if the sdk is local and does not exist, or remote and incomplete or has invalid credentials, or is not supported. * * @see PythonSdkUtil.isInvalid * @see PythonSdkType.isIncompleteRemote * @see PythonSdkType.hasInvalidRemoteCredentials * @see LanguageLevel.SUPPORTED_LEVELS */ fun icon(sdk: Sdk): Icon? { val flavor: PythonSdkFlavor? = when (sdk.sdkAdditionalData) { !is PyRemoteSdkAdditionalDataMarker -> PythonSdkFlavor.getPlatformIndependentFlavor(sdk.homePath) else -> null } val icon = flavor?.icon ?: ((sdk.sdkType as? SdkType)?.icon ?: return null) val providedIcon = PySdkProvider.EP_NAME.extensions.firstNotNullOfOrNull { it.getSdkIcon(sdk) } return when { PythonSdkUtil.isInvalid(sdk) || PythonSdkType.isIncompleteRemote(sdk) || PythonSdkType.hasInvalidRemoteCredentials(sdk) || !LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) -> wrapIconWithWarningDecorator(icon) sdk is PyDetectedSdk -> IconLoader.getTransparentIcon(icon) providedIcon != null -> providedIcon else -> icon } } /** * Groups valid sdks associated with the [module] by types. * Virtual environments, pipenv and conda environments are considered as [PyRenderedSdkType.VIRTUALENV]. * Remote interpreters are considered as [PyRenderedSdkType.REMOTE]. * All the others are considered as [PyRenderedSdkType.SYSTEM]. * * @see Sdk.isAssociatedWithAnotherModule * @see PythonSdkUtil.isVirtualEnv * @see PythonSdkUtil.isCondaVirtualEnv * @see PythonSdkUtil.isRemote * @see PyRenderedSdkType */ fun groupModuleSdksByTypes(allSdks: List<Sdk>, module: Module?, invalid: (Sdk) -> Boolean): Map<PyRenderedSdkType, List<Sdk>> { return allSdks .asSequence() .filter { !it.isAssociatedWithAnotherModule(module) && !invalid(it) } .groupBy { when { PythonSdkUtil.isVirtualEnv(it) || PythonSdkUtil.isCondaVirtualEnv(it) -> PyRenderedSdkType.VIRTUALENV PythonSdkUtil.isRemote(it) -> PyRenderedSdkType.REMOTE else -> PyRenderedSdkType.SYSTEM } } } /** * Order is important, sdks are rendered in the same order as the types are defined. * * @see groupModuleSdksByTypes */ enum class PyRenderedSdkType { VIRTUALENV, SYSTEM, REMOTE } private fun wrapIconWithWarningDecorator(icon: Icon): LayeredIcon = LayeredIcon(2).apply { setIcon(icon, 0) setIcon(AllIcons.Actions.Cancel, 1) } internal fun SimpleColoredComponent.customizeWithSdkValue(value: Any?, nullSdkName: @Nls String, nullSdkValue: Sdk?) { when (value) { is PySdkToInstall -> { value.renderInList(this) } is Sdk -> { appendName(value, name(value)) icon = icon(value) } is String -> append(value) null -> { if (nullSdkValue != null) { appendName(nullSdkValue, name(nullSdkValue, nullSdkName)) icon = icon(nullSdkValue) } else { append(nullSdkName) } } } } private fun SimpleColoredComponent.appendName(sdk: Sdk, name: Triple<String?, String, String?>) { val (modifier, primary, secondary) = name if (modifier != null) { append("[$modifier] $primary", SimpleTextAttributes.ERROR_ATTRIBUTES) } else { append(primary) } if (secondary != null) { append(" $secondary", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES) } path(sdk)?.let { append(" $it", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES) } }
python/src/com/jetbrains/python/sdk/PySdkRendering.kt
2632665020
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package runtime.text.string_builder0 import kotlin.test.* // Utils ==================================================================================================== fun assertTrue(cond: Boolean) { if (!cond) throw AssertionError("Condition expected to be true") } fun assertFalse(cond: Boolean) { if (cond) throw AssertionError("Condition expected to be false") } fun assertEquals(value1: String, value2: String) { if (value1 != value2) throw AssertionError("FAIL: '" + value1 + "' != '" + value2 + "'") } fun assertEquals(value1: Int, value2: Int) { if (value1 != value2) throw AssertionError("FAIL" + value1.toString() + " != " + value2.toString()) } fun assertEquals(builder: StringBuilder, content: String) = assertEquals(builder.toString(), content) // IndexOutOfBoundsException. fun assertException(body: () -> Unit) { try { body() throw AssertionError ("Test failed: no IndexOutOfBoundsException on wrong indices") } catch (e: IndexOutOfBoundsException) { } catch (e: IllegalArgumentException) {} } // Insert =================================================================================================== fun testInsertString(initial: String, index: Int, toInsert: String, expected: String) { assertEquals(StringBuilder(initial).insert(index, toInsert), expected) assertEquals(StringBuilder(initial).insert(index, toInsert.toCharArray()), expected) assertEquals(StringBuilder(initial).insert(index, toInsert as CharSequence), expected) } fun testInsertStringException(initial: String, index: Int, toInsert: String) { assertException { StringBuilder(initial).insert(index, toInsert) } assertException { StringBuilder(initial).insert(index, toInsert.toCharArray()) } assertException { StringBuilder(initial).insert(index, toInsert as CharSequence) } } fun testInsertSingle(value: Byte) { assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd") assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString()) assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd") assertEquals(StringBuilder("").insert(0, value), value.toString()) } fun testInsertSingle(value: Short) { assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd") assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString()) assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd") assertEquals(StringBuilder("").insert(0, value), value.toString()) } fun testInsertSingle(value: Int) { assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd") assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString()) assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd") assertEquals(StringBuilder("").insert(0, value), value.toString()) } fun testInsertSingle(value: Long) { assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd") assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString()) assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd") assertEquals(StringBuilder("").insert(0, value), value.toString()) } fun testInsertSingle(value: Float) { assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd") assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString()) assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd") assertEquals(StringBuilder("").insert(0, value), value.toString()) } fun testInsertSingle(value: Double) { assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd") assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString()) assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd") assertEquals(StringBuilder("").insert(0, value), value.toString()) } fun testInsertSingle(value: Any?) { assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd") assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString()) assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd") assertEquals(StringBuilder("").insert(0, value), value.toString()) } fun testInsertSingle(value: Char) { assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd") assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString()) assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd") assertEquals(StringBuilder("").insert(0, value), value.toString()) } fun testInsert() { // String/CharSequence/CharArray. testInsertString("abcd", 0, "12", "12abcd") testInsertString("abcd", 4, "12", "abcd12") testInsertString("abcd", 2, "12", "ab12cd") testInsertString("", 0, "12", "12") testInsertStringException("a", -1, "1") testInsertStringException("a", 2, "1") // Null inserting. assertEquals(StringBuilder("abcd").insert(0, null as CharSequence?), "nullabcd") assertEquals(StringBuilder("abcd").insert(4, null as CharSequence?), "abcdnull") assertEquals(StringBuilder("abcd").insert(2, null as CharSequence?), "abnullcd") assertEquals(StringBuilder("").insert(0, null as CharSequence?), "null") // Subsequence of CharSequence. // Insert in the beginning. assertEquals(StringBuilder("abcd").insert(0, "1234", 0, 0), "abcd") // 0 symbols assertEquals(StringBuilder("abcd").insert(0, "1234", 0, 1), "1abcd") // 1 symbol assertEquals(StringBuilder("abcd").insert(0, "1234", 1, 3), "23abcd") // 2 symbols assertEquals(StringBuilder("abcd").insert(0, null as CharSequence?, 1, 3), "ulabcd") // 2 symbols of null // Insert in the end. assertEquals(StringBuilder("abcd").insert(4, "1234", 0, 0), "abcd") assertEquals(StringBuilder("abcd").insert(4, "1234", 0, 1), "abcd1") assertEquals(StringBuilder("abcd").insert(4, "1234", 1, 3), "abcd23") assertEquals(StringBuilder("abcd").insert(4, null as CharSequence?, 1, 3), "abcdul") // Insert in the middle. assertEquals(StringBuilder("abcd").insert(2, "1234", 0, 0), "abcd") assertEquals(StringBuilder("abcd").insert(2, "1234", 0, 1), "ab1cd") assertEquals(StringBuilder("abcd").insert(2, "1234", 1, 3), "ab23cd") assertEquals(StringBuilder("abcd").insert(2, null as CharSequence?, 1, 3), "abulcd") // Incorrect indices. assertException { StringBuilder("a").insert(-1, "1", 0, 0) } assertException { StringBuilder("a").insert(2, "1", 0, 0) } assertException { StringBuilder("a").insert(1, "1", -1, 0) } assertException { StringBuilder("a").insert(1, "1", 0, 2) } assertException { StringBuilder("a").insert(1, "123", 2, 0) } // Other types. testInsertSingle(true) testInsertSingle(42.toByte()) testInsertSingle(42.toShort()) testInsertSingle(42.toInt()) testInsertSingle(42.toLong()) testInsertSingle(42.2.toFloat()) testInsertSingle(42.2.toDouble()) testInsertSingle(object { override fun toString(): String { return "Object" } }) testInsertSingle('a') } // Reverse ================================================================================================== fun testReverse(original: String, reversed: String, reversedBack: String) { assertEquals(StringBuilder(original).reverse(), reversed) assertEquals(StringBuilder(reversed).reverse(), reversedBack) } fun testReverse() { var builder = StringBuilder("123456") assertTrue(builder === builder.reverse()) assertEquals(builder, "654321") builder.setLength(1) assertEquals(builder, "6") builder.setLength(0) assertEquals(builder, "") var str: String = "a" testReverse(str, str, str) str = "ab" testReverse(str, "ba", str) str = "abcdef" testReverse(str, "fedcba", str) str = "abcdefg" testReverse(str, "gfedcba", str) str = "\ud800\udc00" testReverse(str, str, str) str = "\udc00\ud800" testReverse(str, "\ud800\udc00", "\ud800\udc00") str = "a\ud800\udc00" testReverse(str, "\ud800\udc00a", str) str = "ab\ud800\udc00" testReverse(str, "\ud800\udc00ba", str) str = "abc\ud800\udc00" testReverse(str, "\ud800\udc00cba", str) str = "\ud800\udc00\udc01\ud801\ud802\udc02" testReverse(str, "\ud802\udc02\ud801\udc01\ud800\udc00", "\ud800\udc00\ud801\udc01\ud802\udc02") str = "\ud800\udc00\ud801\udc01\ud802\udc02" testReverse(str, "\ud802\udc02\ud801\udc01\ud800\udc00", str) str = "\ud800\udc00\udc01\ud801a" testReverse(str, "a\ud801\udc01\ud800\udc00", "\ud800\udc00\ud801\udc01a") str = "a\ud800\udc00\ud801\udc01" testReverse(str, "\ud801\udc01\ud800\udc00a", str) str = "\ud800\udc00\udc01\ud801ab" testReverse(str, "ba\ud801\udc01\ud800\udc00", "\ud800\udc00\ud801\udc01ab") str = "ab\ud800\udc00\ud801\udc01" testReverse(str, "\ud801\udc01\ud800\udc00ba", str) str = "\ud800\udc00\ud801\udc01" testReverse(str, "\ud801\udc01\ud800\udc00", str) str = "a\ud800\udc00z\ud801\udc01" testReverse(str, "\ud801\udc01z\ud800\udc00a", str) str = "a\ud800\udc00bz\ud801\udc01" testReverse(str, "\ud801\udc01zb\ud800\udc00a", str) str = "abc\ud802\udc02\ud801\udc01\ud800\udc00" testReverse(str, "\ud800\udc00\ud801\udc01\ud802\udc02cba", str) str = "abcd\ud802\udc02\ud801\udc01\ud800\udc00" testReverse(str, "\ud800\udc00\ud801\udc01\ud802\udc02dcba", str) } // Basic ==================================================================================================== fun testBasic() { val sb = StringBuilder() assertEquals(0, sb.length) assertEquals("", sb.toString()) sb.append(1) assertEquals(1, sb.length) assertEquals("1", sb.toString()) sb.append(", ") assertEquals(3, sb.length) assertEquals("1, ", sb.toString()) sb.append(true) assertEquals(7, sb.length) assertEquals("1, true", sb.toString()) sb.append(12345678L) assertEquals(15, sb.length) assertEquals("1, true12345678", sb.toString()) sb.append(null as CharSequence?) assertEquals(19, sb.length) assertEquals("1, true12345678null", sb.toString()) sb.setLength(0) assertEquals(0, sb.length) assertEquals("", sb.toString()) } @Test fun runTest() { testBasic() testInsert() testReverse() println("OK") }
backend.native/tests/runtime/text/string_builder0.kt
5252109
package com.github.kerubistan.kerub.planner.steps.host.startup import com.github.kerubistan.kerub.data.dynamic.HostDynamicDao import com.github.kerubistan.kerub.host.HostManager import com.github.kerubistan.kerub.host.lom.WakeOnLan import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.dynamic.HostStatus import com.github.kerubistan.kerub.planner.execution.AbstractStepExecutor import com.github.kerubistan.kerub.utils.getLogger open class WakeHostExecutor( private val hostManager: HostManager, private val hostDynDao: HostDynamicDao, private val tries: Int = defaultMaxRetries, private val wait: Long = defaultWaitBetweenTries ) : AbstractStepExecutor<AbstractWakeHost, Unit>() { companion object { private val logger = getLogger() private const val defaultMaxRetries = 8 private const val defaultWaitBetweenTries = 30000.toLong() } override fun perform(step: AbstractWakeHost) { var lastException: Exception? = null for (nr in 0..tries) { if (hostDynDao[step.host.id]?.status == HostStatus.Up) { //host connected return } try { logger.debug("attempt {} - waking host {} {}", nr, step.host.address, step.host.id) when (step) { is WolWakeHost -> { wakeOnLoan(step.host) } else -> TODO() } logger.debug("attempt {} - connecting host {} {}", nr, step.host.address, step.host.id) hostManager.connectHost(step.host) logger.debug("attempt {} - host {} {} connected", nr, step.host.address, step.host.id) return } catch (e: Exception) { logger.debug("attempt {} - connecting {} {}: failed - waiting {} ms before retry", nr, step.host.address, step.host.id, wait) Thread.sleep(wait) lastException = e } } throw WakeHostException( "Could not connect host ${step.host.address} ${step.host.id} in $defaultMaxRetries attempts", lastException) } internal open fun wakeOnLoan(host: Host) { WakeOnLan(host).on() } override fun update(step: AbstractWakeHost, updates: Unit) { hostDynDao.update(step.host.id) { dyn -> dyn.copy( status = HostStatus.Up ) } } }
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/host/startup/WakeHostExecutor.kt
1986309974
// "Simplify comparison" "true" // WITH_STDLIB fun test() { val s = "" assert(<caret>s != null && true) }
plugins/kotlin/idea/tests/testData/quickfix/simplifyComparison/withAssertion2.kt
4124985676
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.extensibility import com.intellij.openapi.extensions.AreaInstance import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.jetbrains.packagesearch.intellij.plugin.util.asCoroutine import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval /** * Extension point used to register [Module]s transformations to [ProjectModule]s. */ @Deprecated( "Use the async version instead", ReplaceWith("AsyncModuleTransformer"), DeprecationLevel.WARNING ) @ScheduledForRemoval interface ModuleTransformer { companion object { private val extensionPointName: ExtensionPointName<ModuleTransformer> = ExtensionPointName.create("com.intellij.packagesearch.moduleTransformer") internal fun extensions(areaInstance: AreaInstance) = extensionPointName.getExtensionList(areaInstance).asSequence().map { it.asCoroutine() }.toList() } /** * IMPORTANT: This function is NOT invoked inside a read action. * * Transforms [nativeModules] in a [ProjectModule] module if possible, else returns an empty list. * Its implementation should use the IntelliJ platform APIs for a given build system (eg. * Gradle or Maven), detect if and which [nativeModules] are controlled by said build system * and transform them accordingly. * * NOTE: some [Module]s in [nativeModules] may be already disposed or about to be. Be sure to * handle any exceptions and filter out the ones not working. * * @param nativeModules The native [Module]s that will be transformed. * @return [ProjectModule]s wrapping [nativeModules] or an empty list. */ fun transformModules(project: Project, nativeModules: List<Module>): List<ProjectModule> }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/ModuleTransformer.kt
2772178999
import org.jetbrains.annotations.PropertyKey fun message(@PropertyKey(resourceBundle = "propertyUsages.0") key: String) = key infix fun String.infixMessage(@PropertyKey(resourceBundle = "propertyUsages.0") key: String) = key infix fun @receiver:PropertyKey(resourceBundle = "propertyUsages.0") String.infixMessage2(s: String) = this operator fun @receiver:PropertyKey(resourceBundle = "propertyUsages.0") String.unaryMinus() = this operator fun Int.get(@PropertyKey(resourceBundle = "propertyUsages.0") key: String) = this operator fun @receiver:PropertyKey(resourceBundle = "propertyUsages.0") String.get(s: String) = this fun test() { @PropertyKey(resourceBundle = "propertyUsages.0") val s1 = "foo.bar" @PropertyKey(resourceBundle = "propertyUsages.0") val s2 = "foo.baz" message("foo.bar") message("foo.baz") "test" infixMessage "foo.bar" "foo.bar" infixMessage "test" "foo.bar" infixMessage2 "test" "test" infixMessage2 "foo.bar" "foo.bar".infixMessage2("test") -"foo.bar" 1["foo.bar"] "foo.bar"["test"] "test"["foo.bar"] }
plugins/kotlin/idea/tests/testData/findUsages/propertyFiles/propertyUsages.1.kt
77813375
package extensionMemberProperty fun main(args: Array<String>) { MemberClass().testMember(ExtClass()) MemberClass.testCompanion(ExtClass()) } class MemberClass { fun testMember(extClass: ExtClass) { // EXPRESSION: extClass.testPublic // RESULT: 1: I //Breakpoint! extClass.testPublic with(extClass) { // EXPRESSION: testPublic // RESULT: 1: I //Breakpoint! testPublic } // EXPRESSION: extClass.testPrivate // RESULT: 1: I //Breakpoint! extClass.testPrivate with(extClass) { // EXPRESSION: testPrivate // RESULT: 1: I //Breakpoint! testPrivate } extClass.testExtMember() } fun ExtClass.testExtMember() { // EXPRESSION: testPublic // RESULT: 1: I //Breakpoint! testPublic // EXPRESSION: this.testPublic // RESULT: 1: I //Breakpoint! this.testPublic // EXPRESSION: testPrivate // RESULT: 1: I //Breakpoint! testPrivate // EXPRESSION: this.testPrivate // RESULT: 1: I //Breakpoint! this.testPrivate } public val ExtClass.testPublic: Int get() = a private val ExtClass.testPrivate: Int get() = a companion object { public val ExtClass.testCompPublic: Int get() = a private val ExtClass.testCompPrivate: Int get() = a fun testCompanion(extClass: ExtClass) { // EXPRESSION: extClass.testCompPublic // RESULT: 1: I //Breakpoint! extClass.testCompPublic with(extClass) { // EXPRESSION: testCompPublic // RESULT: 1: I //Breakpoint! testCompPublic } // EXPRESSION: extClass.testCompPrivate // RESULT: 1: I //Breakpoint! extClass.testCompPrivate with(extClass) { // EXPRESSION: testCompPrivate // RESULT: 1: I //Breakpoint! testCompPrivate } extClass.testExtCompanion() } fun ExtClass.testExtCompanion() { // EXPRESSION: testCompPublic // RESULT: 1: I //Breakpoint! testCompPublic // EXPRESSION: this.testCompPublic // RESULT: 1: I //Breakpoint! this.testCompPublic // EXPRESSION: testCompPrivate // RESULT: 1: I //Breakpoint! testCompPrivate // EXPRESSION: this.testCompPrivate // RESULT: 1: I //Breakpoint! this.testCompPrivate } } } class ExtClass { val a = 1 }
plugins/kotlin/jvm-debugger/test/testData/evaluation/multipleBreakpoints/extensionMemberProperty.kt
2482350207
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.testIntegration import com.intellij.CommonBundle import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.FileModificationService import com.intellij.codeInsight.navigation.NavigationUtil import com.intellij.ide.util.PropertiesComponent import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScopesCore import com.intellij.psi.util.PsiUtil import com.intellij.testIntegration.createTest.CreateTestAction import com.intellij.testIntegration.createTest.CreateTestUtils.computeTestRoots import com.intellij.testIntegration.createTest.TestGenerators import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.findFacadeClass import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.actions.JavaToKotlinAction import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.getPackage import org.jetbrains.kotlin.idea.core.util.toPsiDirectory import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.j2k.j2k import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.runWhenSmart import org.jetbrains.kotlin.idea.util.runWithAlternativeResolveEnabled import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier import org.jetbrains.kotlin.psi.psiUtil.startOffset class KotlinCreateTestIntention : SelfTargetingRangeIntention<KtNamedDeclaration>( KtNamedDeclaration::class.java, KotlinBundle.lazyMessage("create.test") ) { override fun applicabilityRange(element: KtNamedDeclaration): TextRange? { if (element.hasExpectModifier() || element.nameIdentifier == null) return null if (ModuleUtilCore.findModuleForPsiElement(element) == null) return null if (element is KtClassOrObject) { if (element.isLocal) return null if (element is KtEnumEntry) return null if (element is KtClass && (element.isAnnotation() || element.isInterface())) return null if (element.resolveToDescriptorIfAny() == null) return null val virtualFile = PsiUtil.getVirtualFile(element) if (virtualFile == null || ProjectRootManager.getInstance(element.project).fileIndex.isInTestSourceContent(virtualFile)) return null return TextRange( element.startOffset, element.getSuperTypeList()?.startOffset ?: element.body?.startOffset ?: element.endOffset ) } if (element.parent !is KtFile) return null if (element is KtNamedFunction) { return TextRange((element.funKeyword ?: element.nameIdentifier!!).startOffset, element.nameIdentifier!!.endOffset) } if (element is KtProperty) { if (element.getter == null && element.delegate == null) return null return TextRange(element.valOrVarKeyword.startOffset, element.nameIdentifier!!.endOffset) } return null } override fun startInWriteAction() = false override fun applyTo(element: KtNamedDeclaration, editor: Editor?) { if (editor == null) throw IllegalArgumentException("This intention requires an editor") val lightClass = when (element) { is KtClassOrObject -> element.toLightClass() else -> element.containingKtFile.findFacadeClass() } ?: return object : CreateTestAction() { // Based on the com.intellij.testIntegration.createTest.JavaTestGenerator.createTestClass() private fun findTestClass(targetDirectory: PsiDirectory, className: String): PsiClass? { val psiPackage = targetDirectory.getPackage() ?: return null val scope = GlobalSearchScopesCore.directoryScope(targetDirectory, false) val klass = psiPackage.findClassByShortName(className, scope).firstOrNull() ?: return null if (!FileModificationService.getInstance().preparePsiElementForWrite(klass)) return null return klass } private fun getTempJavaClassName(project: Project, kotlinFile: VirtualFile): String { val baseName = kotlinFile.nameWithoutExtension val psiDir = kotlinFile.parent!!.toPsiDirectory(project)!! return generateSequence(0) { it + 1 } .map { "$baseName$it" } .first { psiDir.findFile("$it.java") == null && findTestClass(psiDir, it) == null } } // Based on the com.intellij.testIntegration.createTest.CreateTestAction.CreateTestAction.invoke() override fun invoke(project: Project, editor: Editor?, element: PsiElement) { val srcModule = ModuleUtilCore.findModuleForPsiElement(element) ?: return val propertiesComponent = PropertiesComponent.getInstance() val testFolders = computeTestRoots(srcModule) if (testFolders.isEmpty() && !propertiesComponent.getBoolean("create.test.in.the.same.root")) { if (Messages.showOkCancelDialog( project, KotlinBundle.message("test.integration.message.text.create.test.in.the.same.source.root"), KotlinBundle.message("test.integration.title.no.test.roots.found"), Messages.getQuestionIcon() ) != Messages.OK ) return propertiesComponent.setValue("create.test.in.the.same.root", true) } val srcClass = getContainingClass(element) ?: return val srcDir = element.containingFile.containingDirectory val srcPackage = JavaDirectoryService.getInstance().getPackage(srcDir) val dialog = KotlinCreateTestDialog(project, text, srcClass, srcPackage, srcModule) if (!dialog.showAndGet()) return val existingClass = (findTestClass(dialog.targetDirectory, dialog.className) as? KtLightClass)?.kotlinOrigin if (existingClass != null) { // TODO: Override dialog method when it becomes protected val answer = Messages.showYesNoDialog( project, KotlinBundle.message("test.integration.message.text.kotlin.class", existingClass.name.toString()), CommonBundle.getErrorTitle(), KotlinBundle.message("test.integration.button.text.rewrite"), KotlinBundle.message("test.integration.button.text.cancel"), Messages.getErrorIcon() ) if (answer == Messages.NO) return } val generatedClass = project.executeCommand(CodeInsightBundle.message("intention.create.test"), this) { val generator = TestGenerators.INSTANCE.forLanguage(dialog.selectedTestFrameworkDescriptor.language) project.runWithAlternativeResolveEnabled { if (existingClass != null) { dialog.explicitClassName = getTempJavaClassName(project, existingClass.containingFile.virtualFile) } generator.generateTest(project, dialog) } } as? PsiClass ?: return project.runWhenSmart { val generatedFile = generatedClass.containingFile as? PsiJavaFile ?: return@runWhenSmart if (generatedClass.language == JavaLanguage.INSTANCE) { project.executeCommand<Unit>( KotlinBundle.message("convert.class.0.to.kotlin", generatedClass.name.toString()), this ) { runWriteAction { generatedClass.methods.forEach { it.throwsList.referenceElements.forEach { referenceElement -> referenceElement.delete() } } } if (existingClass != null) { runWriteAction { val existingMethodNames = existingClass .declarations .asSequence() .filterIsInstance<KtNamedFunction>() .mapTo(HashSet()) { it.name } generatedClass .methods .filter { it.name !in existingMethodNames } .forEach { it.j2k()?.let { declaration -> existingClass.addDeclaration(declaration) } } generatedClass.delete() } NavigationUtil.activateFileWithPsiElement(existingClass) } else { with(PsiDocumentManager.getInstance(project)) { getDocument(generatedFile)?.let { doPostponedOperationsAndUnblockDocument(it) } } JavaToKotlinAction.convertFiles( listOf(generatedFile), project, srcModule, false, forceUsingOldJ2k = true ).singleOrNull() } } } } } }.invoke(element.project, editor, lightClass) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestIntention.kt
1625063948
// "Add parameter to function 'foo'" "true" // DISABLE-ERRORS fun foo() {} fun bar(f: (String) -> Unit) {} fun test() { bar { foo(it<caret>) } }
plugins/kotlin/idea/tests/testData/quickfix/changeSignature/addFunctionParameterForReferencedArgument4.kt
4294749438
class A { } <caret>}
plugins/kotlin/idea/tests/testData/editor/backspaceHandler/beforeUnpairedBrace.kt
3384126390
// "Create actual class for module testProjectName.mpp-bottom-actual.jsJvm18Main (Native (general)/JS/JVM (JVM_1_8))" "true" // ACTION: Convert to secondary constructor // ACTION: Create subclass package playground.second expect open class PlatformClass() { open fun c(a: Int, b: String) }
plugins/kotlin/idea/tests/testData/gradle/fixes/createActualForGranularSourceSetTarget/after/mpp-bottom-actual/src/commonMain/kotlin/playground/second/PlatformClass.kt
3731069235
// 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.perf.live import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.codeInsight.daemon.impl.IdentifierHighlighterPassFactory import com.intellij.codeInspection.InspectionProfileEntry import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.profile.codeInspection.ProjectInspectionProfileManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.testFramework.* import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl import com.intellij.util.ArrayUtilRt import com.intellij.util.ThrowableRunnable import com.intellij.util.indexing.UnindexedFilesUpdater import com.intellij.util.ui.UIUtil import org.jetbrains.kotlin.idea.testFramework.Stats import org.jetbrains.kotlin.idea.testFramework.Stats.Companion.WARM_UP import org.jetbrains.kotlin.idea.perf.suite.PerformanceSuite.ApplicationScope.Companion.initApp import org.jetbrains.kotlin.idea.perf.suite.PerformanceSuite.ApplicationScope.Companion.initSdk import org.jetbrains.kotlin.idea.perf.util.ProfileTools.Companion.initDefaultProfile import org.jetbrains.kotlin.idea.perf.util.logMessage import org.jetbrains.kotlin.idea.search.usagesSearch.ExpressionsOfTypeProcessor import org.jetbrains.kotlin.idea.test.invalidateLibraryCache import org.jetbrains.kotlin.idea.testFramework.* import org.jetbrains.kotlin.idea.testFramework.Fixture.Companion.openInEditor import org.jetbrains.kotlin.idea.testFramework.Fixture.Companion.openFixture import org.jetbrains.kotlin.test.KotlinRoot import java.io.File abstract class AbstractPerformanceProjectsTest : UsefulTestCase() { // myProject is not required for all potential perf test cases protected var myProject: Project? = null private lateinit var jdk18: Sdk private lateinit var myApplication: TestApplicationManager override fun setUp() { super.setUp() ExpressionsOfTypeProcessor.prodMode() myApplication = initApp(testRootDisposable) jdk18 = initSdk(testRootDisposable) } internal fun warmUpProject(stats: Stats, vararg filesToHighlight: String, openProject: () -> Project) { assertTrue(filesToHighlight.isNotEmpty()) val project = openProject() try { filesToHighlight.forEach { val perfHighlightFile = perfHighlightFile(project, it, stats, note = WARM_UP) assertTrue("kotlin project has been not imported properly", perfHighlightFile.isNotEmpty()) } } finally { closeProject(project) } } override fun tearDown() { RunAll( ThrowableRunnable { commitAllDocuments() }, ThrowableRunnable { ExpressionsOfTypeProcessor.resetMode() }, ThrowableRunnable { super.tearDown() }, ThrowableRunnable { myProject?.let { project -> closeProject(project) myProject = null } }).run() } fun simpleFilename(fileName: String): String { val lastIndexOf = fileName.lastIndexOf('/') return if (lastIndexOf >= 0) fileName.substring(lastIndexOf + 1) else fileName } private fun closeProject(project: Project) = myApplication.closeProject(project) protected fun perfOpenProject( stats: Stats, note: String = "", fast: Boolean = false, initializer: ProjectBuilder.() -> Unit, ): Project { val projectBuilder = ProjectBuilder().apply(initializer) val name = projectBuilder.name val openProjectOperation = projectBuilder.openProjectOperation() val warmUpIterations = if (fast) 0 else 5 val iterations = if (fast) 1 else 5 var lastProject: Project? = null var counter = 0 performanceTest<Unit, Project> { name("open project $name${if (note.isNotEmpty()) " $note" else ""}") stats(stats) warmUpIterations(warmUpIterations) iterations(iterations) stabilityWatermark(25.takeIf { !fast }) test { it.value = openProjectOperation.openProject() } tearDown { it.value?.let { project -> lastProject = project openProjectOperation.postOpenProject(project) logMessage { "project '$name' successfully opened" } // close all project but last - we're going to return and use it further if (counter < warmUpIterations + iterations - 1) { closeProject(project) } counter++ } } } lastProject?.let { doProjectIndexing(it, name) } return lastProject ?: error("unable to open project $name") } protected fun perfOpenProject( name: String, stats: Stats, note: String, path: String, openAction: ProjectOpenAction, fast: Boolean = false ): Project { val projectPath = (if (File(path).exists()) File(path) else KotlinRoot.REPO.resolve(path)).absolutePath assertTrue("path $projectPath does not exist, check README.md", File(projectPath).exists()) val warmUpIterations = if (fast) 0 else 5 val iterations = if (fast) 1 else 5 var lastProject: Project? = null var counter = 0 val openProject = OpenProject( projectPath = projectPath, projectName = name, jdk = jdk18, projectOpenAction = openAction ) performanceTest<Unit, Project> { name("open project $name${if (note.isNotEmpty()) " $note" else ""}") stats(stats) warmUpIterations(warmUpIterations) iterations(iterations) stabilityWatermark(25.takeIf { !fast }) test { it.value = ProjectOpenAction.openProject(openProject) } tearDown { it.value?.let { project -> lastProject = project openAction.postOpenProject(openProject = openProject, project = project) project.initDefaultProfile() logMessage { "project '$name' successfully opened" } // close all project but last - we're going to return and use it further if (counter < warmUpIterations + iterations - 1) { myApplication.closeProject(project) } counter++ } } } lastProject?.let { doProjectIndexing(it, name) } return lastProject ?: error("unable to open project $name at $projectPath") } protected fun openProjectNormal(name: String, path: String, openAction: ProjectOpenAction): Project { val projectPath = (if (File(path).exists()) File(path) else KotlinRoot.REPO.resolve(path)).absolutePath assertTrue("path $projectPath does not exist, check README.md", File(projectPath).exists()) val openProject = OpenProject( projectPath = projectPath, projectName = name, jdk = jdk18, projectOpenAction = openAction ) val project = ProjectOpenAction.openProject(openProject).also { openAction.postOpenProject(openProject = openProject, project = it) it.initDefaultProfile() } return project } private fun doProjectIndexing(project: Project, name: String) { invalidateLibraryCache(project) CodeInsightTestFixtureImpl.ensureIndexesUpToDate(project) dispatchAllInvocationEvents() logMessage { "project $name is ${if (project.isInitialized) "initialized" else "not initialized"}" } with(DumbService.getInstance(project)) { queueTask(UnindexedFilesUpdater(project)) completeJustSubmittedTasks() } dispatchAllInvocationEvents() Fixture.enableAnnotatorsAndLoadDefinitions(project) myApplication.setDataProvider(TestDataProvider(project)) } fun perfTypeAndUndo( project: Project, stats: Stats, fileName: String, marker: String, insertString: String, surroundItems: String = "\n", typeAfterMarker: Boolean = true, revertChangesAtTheEnd: Boolean = true, note: String = "" ) { var fileText: String? = null perfTypeAndDo<Unit>( project, fileName, "typeAndUndo", note, stats, marker, typeAfterMarker, surroundItems, insertString, setupBlock = { fixture: Fixture -> fileText = fixture.document.text }, testBlock = { fixture: Fixture -> fixture.performEditorAction(IdeActions.ACTION_UNDO) UIUtil.dispatchAllInvocationEvents() }, tearDownCheck = { fixture, _ -> val text = fixture.document.text assert(fileText != text) { "undo has to change document text\nbefore undo:\n$fileText\n\nafter undo:\n$text" } }, revertChangesAtTheEnd = revertChangesAtTheEnd ) } private fun <V> perfTypeAndDo( project: Project, fileName: String, typeTestPrefix: String, note: String, stats: Stats, marker: String, typeAfterMarker: Boolean, surroundItems: String, insertString: String, setupBlock: (Fixture) -> Unit, testBlock: (Fixture) -> V, tearDownCheck: (Fixture, V?) -> Unit, revertChangesAtTheEnd: Boolean ) { openFixture(project, fileName).use { fixture -> val editor = fixture.editor val initialText = editor.document.text fixture.updateScriptDependenciesIfNeeded() performanceTest<Unit, V> { name("$typeTestPrefix ${notePrefix(note)}$fileName") stats(stats) warmUpIterations(8) iterations(15) profilerConfig.enabled = true setUp { val markerOffset = editor.document.text.indexOf(marker) assertTrue("marker '$marker' not found in $fileName", markerOffset > 0) if (typeAfterMarker) { editor.caretModel.moveToOffset(markerOffset + marker.length + 1) } else { editor.caretModel.moveToOffset(markerOffset - 1) } for (surroundItem in surroundItems) { EditorTestUtil.performTypingAction(editor, surroundItem) } editor.caretModel.moveToOffset(editor.caretModel.offset - if (typeAfterMarker) 1 else 2) if (!typeAfterMarker) { for (surroundItem in surroundItems) { EditorTestUtil.performTypingAction(editor, surroundItem) } editor.caretModel.moveToOffset(editor.caretModel.offset - 2) } fixture.type(insertString) setupBlock(fixture) } test { it.value = testBlock(fixture) } tearDown { try { tearDownCheck(fixture, it.value) } finally { fixture.revertChanges(revertChangesAtTheEnd, initialText) commitAllDocuments() } } } } } fun perfTypeAndHighlight( stats: Stats, fileName: String, marker: String, insertString: String, surroundItems: String = "\n", typeAfterMarker: Boolean = true, revertChangesAtTheEnd: Boolean = true, note: String = "" ) = perfTypeAndHighlight( project(), stats, fileName, marker, insertString, surroundItems, typeAfterMarker = typeAfterMarker, revertChangesAtTheEnd = revertChangesAtTheEnd, note = note ) fun perfTypeAndHighlight( project: Project, stats: Stats, fileName: String, marker: String, insertString: String, surroundItems: String = "\n", typeAfterMarker: Boolean = true, revertChangesAtTheEnd: Boolean = true, note: String = "" ) { performanceTest<Pair<String, Fixture>, List<HighlightInfo>> { name("typeAndHighlight ${notePrefix(note)}$fileName") stats(stats) warmUpIterations(8) iterations(15) setUp { val fixture = openFixture(project, fileName) val editor = fixture.editor val initialText = editor.document.text fixture.updateScriptDependenciesIfNeeded() val tasksIdx = editor.document.text.indexOf(marker) assertTrue("marker '$marker' not found in $fileName", tasksIdx > 0) if (typeAfterMarker) { editor.caretModel.moveToOffset(tasksIdx + marker.length + 1) } else { editor.caretModel.moveToOffset(tasksIdx - 1) } for (surroundItem in surroundItems) { EditorTestUtil.performTypingAction(editor, surroundItem) } editor.caretModel.moveToOffset(editor.caretModel.offset - if (typeAfterMarker) 1 else 2) if (!typeAfterMarker) { for (surroundItem in surroundItems) { EditorTestUtil.performTypingAction(editor, surroundItem) } editor.caretModel.moveToOffset(editor.caretModel.offset - 2) } fixture.type(insertString) it.setUpValue = Pair(initialText, fixture) } test { val fixture = it.setUpValue!!.second it.value = fixture.doHighlighting() } tearDown { it.value?.let { list -> assertNotEmpty(list) } it.setUpValue?.let { pair -> pair.second.revertChanges(revertChangesAtTheEnd, pair.first) } commitAllDocuments() } profilerConfig.enabled = true } } protected fun perfHighlightFile( name: String, stats: Stats, tools: Array<InspectionProfileEntry>? = null, note: String = "" ): List<HighlightInfo> = perfHighlightFile(project(), name, stats, tools = tools, note = note) protected fun perfHighlightFileEmptyProfile(name: String, stats: Stats): List<HighlightInfo> = perfHighlightFile(project(), name, stats, tools = emptyArray(), note = "empty profile") protected fun perfHighlightFile( project: Project, fileName: String, stats: Stats, tools: Array<InspectionProfileEntry>? = null, note: String = "", warmUpIterations: Int = 3, iterations: Int = 10, stabilityWatermark: Int = 25, filenameSimplifier: (String) -> String = ::simpleFilename ): List<HighlightInfo> { val profileManager = ProjectInspectionProfileManager.getInstance(project) val currentProfile = profileManager.currentProfile tools?.let { configureInspections(it, project, project) } try { return project.highlightFile { val isWarmUp = note == WARM_UP var highlightInfos: List<HighlightInfo> = emptyList() performanceTest<EditorFile, List<HighlightInfo>> { name("highlighting ${notePrefix(note)}${filenameSimplifier(fileName)}") stats(stats) warmUpIterations(if (isWarmUp) 1 else warmUpIterations) iterations(if (isWarmUp) 2 else iterations) stabilityWatermark(stabilityWatermark) setUp { it.setUpValue = openInEditor(project, fileName) } test { val file = it.setUpValue it.value = highlightFile(project, file!!.psiFile) } tearDown { highlightInfos = it.value ?: emptyList() commitAllDocuments() it.setUpValue?.let { editorFile -> val fileEditorManager = FileEditorManager.getInstance(project) fileEditorManager.closeFile(editorFile.psiFile.virtualFile) } PsiManager.getInstance(project).dropPsiCaches() } profilerConfig.enabled = true } highlightInfos } } finally { profileManager.setCurrentProfile(currentProfile) } } internal fun <T> Project.highlightFile(block: () -> T): T { var value: T? = null IdentifierHighlighterPassFactory.doWithHighlightingEnabled(this, this) { value = block() } return value!! } private fun highlightFile(project: Project, psiFile: PsiFile): List<HighlightInfo> { val document = FileDocumentManager.getInstance().getDocument(psiFile.virtualFile)!! val editor = EditorFactory.getInstance().getEditors(document).first() PsiDocumentManager.getInstance(project).commitAllDocuments() return CodeInsightTestFixtureImpl.instantiateAndRun(psiFile, editor, ArrayUtilRt.EMPTY_INT_ARRAY, true) } protected fun project() = myProject ?: error("project has not been initialized") fun notePrefix(note: String) = if (note.isNotEmpty()) { if (note.endsWith("/")) note else "$note " } else "" }
plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/live/AbstractPerformanceProjectsTest.kt
2826386273
fun t() { while (true) { i<caret> } } // ELEMENT: if // CHAR: '('
plugins/kotlin/completion/tests/testData/handlers/keywords/IfLParenth.kt
1925007674
// "Create interface 'A'" "true" // ERROR: Unresolved reference: A fun foo(): J.<caret>A = throw Throwable("")
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/typeReference/traitJavaTypeReceiver.before.Main.kt
823745350
val x = <selection>java.util.TreeMap</selection><java.util.Date, String>(1)
plugins/kotlin/idea/tests/testData/shortenRefs/constructor/WorksForClassNameRange2.kt
3753781820
// WITH_STDLIB // AFTER-WARNING: Parameter 'args' is never used // AFTER-WARNING: Variable 'y' is never used fun main(args: Array<String>){ val x = mapOf("a" to "b") val y = "abcd" +<caret> x["a"] }
plugins/kotlin/idea/tests/testData/intentions/convertToStringTemplate/interpolateMapAccess.kt
3803818901
// "Implement members" "false" // ACTION: Make internal // ACTION: Extract 'A' from current file interface I { fun foo() } @Suppress("UNSUPPORTED_FEATURE") expect <caret>class A : I
plugins/kotlin/idea/tests/testData/quickfix/override/dontOfferToImplementMembersForExpectedClass.kt
839734829
package xyz.nulldev.ts.api.v2.java.model.categories import eu.kanade.tachiyomi.data.database.models.Manga interface CategoryModel : CategoryLikeModel { override val id: Int override var name: String? override var order: Int? override var flags: Int? //TODO Use v2 manga structure override var manga: List<Manga>? }
TachiServer/src/main/java/xyz/nulldev/ts/api/v2/java/model/categories/CategoryModel.kt
2222547751