repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
SirWellington/alchemy-http
src/main/java/tech/sirwellington/alchemy/http/Step6Impl.kt
1
2371
/* * Copyright © 2019. Sir Wellington. * 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 tech.sirwellington.alchemy.http import tech.sirwellington.alchemy.annotations.access.Internal import tech.sirwellington.alchemy.annotations.designs.StepMachineDesign import tech.sirwellington.alchemy.annotations.designs.StepMachineDesign.Role.STEP import tech.sirwellington.alchemy.arguments.Arguments.checkThat import tech.sirwellington.alchemy.http.HttpAssertions.validResponseClass import java.net.URL /** * * @author SirWellington */ @StepMachineDesign(role = STEP) @Internal internal class Step6Impl<ResponseType>(private val stateMachine: AlchemyHttpStateMachine, private val request: HttpRequest, private val classOfResponseType: Class<ResponseType>, private val successCallback: AlchemyRequestSteps.OnSuccess<ResponseType>, private val failureCallback: AlchemyRequestSteps.OnFailure) : AlchemyRequestSteps.Step6<ResponseType> { init { checkThat(classOfResponseType).isA(validResponseClass()) } override fun at(url: URL) { val requestCopy = HttpRequest.Builder .from(request) .usingUrl(url) .build() stateMachine.executeAsync(requestCopy, classOfResponseType, successCallback, failureCallback) } override fun toString(): String { return "Step6Impl{stateMachine=$stateMachine, request=$request, classOfResponseType=$classOfResponseType, successCallback=$successCallback, failureCallback=$failureCallback}" } }
apache-2.0
ab8e3e3f9039cbd57c09f6556a9fb469
38.5
182
0.657806
5.231788
false
false
false
false
Kotlin/kotlinx.serialization
formats/json/commonMain/src/kotlinx/serialization/json/internal/JsonTreeReader.kt
1
4721
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.json.internal import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.* @OptIn(ExperimentalSerializationApi::class) internal class JsonTreeReader( configuration: JsonConfiguration, private val lexer: AbstractJsonLexer ) { private val isLenient = configuration.isLenient private var stackDepth = 0 private fun readObject(): JsonElement = readObjectImpl { read() } private suspend fun DeepRecursiveScope<Unit, JsonElement>.readObject(): JsonElement = readObjectImpl { callRecursive(Unit) } private inline fun readObjectImpl(reader: () -> JsonElement): JsonObject { var lastToken = lexer.consumeNextToken(TC_BEGIN_OBJ) if (lexer.peekNextToken() == TC_COMMA) lexer.fail("Unexpected leading comma") val result = linkedMapOf<String, JsonElement>() while (lexer.canConsumeValue()) { // Read key and value val key = if (isLenient) lexer.consumeStringLenient() else lexer.consumeString() lexer.consumeNextToken(TC_COLON) val element = reader() result[key] = element // Verify the next token lastToken = lexer.consumeNextToken() when (lastToken) { TC_COMMA -> Unit // no-op, can continue with `canConsumeValue` that verifies the token after comma TC_END_OBJ -> break // `canConsumeValue` can return incorrect result, since it checks token _after_ TC_END_OBJ else -> lexer.fail("Expected end of the object or comma") } } // Check for the correct ending if (lastToken == TC_BEGIN_OBJ) { // Case of empty object lexer.consumeNextToken(TC_END_OBJ) } else if (lastToken == TC_COMMA) { // Trailing comma lexer.fail("Unexpected trailing comma") } return JsonObject(result) } private fun readArray(): JsonElement { var lastToken = lexer.consumeNextToken() // Prohibit leading comma if (lexer.peekNextToken() == TC_COMMA) lexer.fail("Unexpected leading comma") val result = arrayListOf<JsonElement>() while (lexer.canConsumeValue()) { val element = read() result.add(element) lastToken = lexer.consumeNextToken() if (lastToken != TC_COMMA) { lexer.require(lastToken == TC_END_LIST) { "Expected end of the array or comma" } } } // Check for the correct ending if (lastToken == TC_BEGIN_LIST) { // Case of empty object lexer.consumeNextToken(TC_END_LIST) } else if (lastToken == TC_COMMA) { // Trailing comma lexer.fail("Unexpected trailing comma") } return JsonArray(result) } private fun readValue(isString: Boolean): JsonPrimitive { val string = if (isLenient || !isString) { lexer.consumeStringLenient() } else { lexer.consumeString() } if (!isString && string == NULL) return JsonNull return JsonLiteral(string, isString) } fun read(): JsonElement { return when (val token = lexer.peekNextToken()) { TC_STRING -> readValue(isString = true) TC_OTHER -> readValue(isString = false) TC_BEGIN_OBJ -> { /* * If the object has the depth of 200 (an arbitrary "good enough" constant), it means * that it's time to switch to stackless recursion to avoid StackOverflowError. * This case is quite rare and specific, so more complex nestings (e.g. through * the chain of JsonArray and JsonElement) are not supported. */ val result = if (++stackDepth == 200) { readDeepRecursive() } else { readObject() } --stackDepth result } TC_BEGIN_LIST -> readArray() else -> lexer.fail("Cannot begin reading element, unexpected token: $token") } } private fun readDeepRecursive(): JsonElement = DeepRecursiveFunction<Unit, JsonElement> { when (lexer.peekNextToken()) { TC_STRING -> readValue(isString = true) TC_OTHER -> readValue(isString = false) TC_BEGIN_OBJ -> readObject() TC_BEGIN_LIST -> readArray() else -> lexer.fail("Can't begin reading element, unexpected token") } }.invoke(Unit) }
apache-2.0
d1626f3fdd003f6950070110eee76b01
39.350427
126
0.59373
4.827198
false
false
false
false
andrei-heidelbacher/algoventure-core
src/main/kotlin/com/aheidelbacher/algoventure/core/generation/MapGenerator.kt
1
3746
/* * Copyright 2016 Andrei Heidelbacher <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aheidelbacher.algoventure.core.generation import com.aheidelbacher.algostorm.state.Color import com.aheidelbacher.algostorm.state.Layer.ObjectGroup import com.aheidelbacher.algostorm.state.Layer.ObjectGroup.DrawOrder import com.aheidelbacher.algostorm.state.Layer.ObjectGroup.DrawOrder.INDEX import com.aheidelbacher.algostorm.state.Layer.TileLayer import com.aheidelbacher.algostorm.state.MapObject import com.aheidelbacher.algostorm.state.TileSet import com.aheidelbacher.algoventure.core.state.FLOOR_TILE_LAYER_NAME import com.aheidelbacher.algoventure.core.state.HEALTH_BAR_OBJECT_GROUP_NAME import com.aheidelbacher.algoventure.core.state.OBJECT_GROUP_NAME abstract class MapGenerator<T : Level>( val width: Int, val height: Int, val tileWidth: Int, val tileHeight: Int, val orientation: MapObject.Orientation, val tileSets: List<TileSet>, val prototypes: kotlin.collections.Map<String, PrototypeObject>, val levelGenerator: LevelGenerator<T> ) { protected lateinit var playerPrototype: PrototypeObject init { require(width > 0 && height > 0) { "Map sizes ($width, $height) must be positive!" } require(tileWidth > 0 && tileHeight > 0) { "Map tile sizes ($tileWidth, $tileHeight) must be positive!" } require(levelGenerator.levelWidth <= width) { "Level generator width is greater than map width!" } require(levelGenerator.levelHeight <= height) { "Level generator height is greater than map height!" } } protected abstract fun MapObject.inflateLevel(level: T): Unit protected abstract fun MapObject.decorate(): Unit fun generate(playerObjectType: String): MapObject { playerPrototype = requireNotNull(prototypes[playerObjectType]) { "Player prototype $playerObjectType not found!" } val map = MapObject( width = width, height = height, tileWidth = tileWidth, tileHeight = tileHeight, orientation = orientation, tileSets = tileSets, layers = listOf( TileLayer( name = FLOOR_TILE_LAYER_NAME, data = LongArray(width * height) { 0L } ), ObjectGroup( name = OBJECT_GROUP_NAME, objects = listOf(), drawOrder = INDEX ), ObjectGroup( name = HEALTH_BAR_OBJECT_GROUP_NAME, color = Color("#ffff0000"), objects = listOf(), drawOrder = DrawOrder.INDEX ) ), nextObjectId = 1 ) map.inflateLevel(levelGenerator.generate()) map.decorate() return map } }
apache-2.0
03a369f622eef748bfad821bf66b0ca5
38.020833
76
0.601975
5.014726
false
false
false
false
mercadopago/px-android
px-checkout/src/main/java/com/mercadopago/android/px/internal/extensions/ParcelExtensions.kt
1
806
package com.mercadopago.android.px.internal.extensions import android.os.Parcel import java.math.BigDecimal import java.util.* internal fun Parcel.writeDate(date: Date?) = writeLong(date?.time ?: -1L) internal fun Parcel.readDate(): Date? { val long = readLong() return if (long != -1L) Date(long) else null } internal fun Parcel.writeBigDecimal(value: BigDecimal?) = value?.let { writeByte(1.toByte()) writeString(it.toString()) } ?: writeByte(0.toByte()) internal fun Parcel.readBigDecimal() = if (readByte().toInt() == 0) null else BigDecimal(readString()) internal fun Parcel.writeNullableInt(value: Int?) = value?.let { writeByte(1.toByte()) writeInt(it) } ?: writeByte(0.toByte()) internal fun Parcel.readNullableInt() = if (readByte().toInt() == 0) null else readInt()
mit
c17033e58ee67d6e2e14efb9aa6e0234
30.038462
102
0.708437
3.647059
false
false
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/ValueObject.kt
1
1445
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.core import java.io.Serializable /** * 값 형식의 데이터를 표현하는 클래스의 기본 인터페이스입니다. * * @author [email protected] */ interface ValueObject : Serializable /** * 값 형식의 데이터를 표현하는 클래스의 추상화 클래스 * * @author [email protected] */ abstract class AbstractValueObject : ValueObject { override fun equals(other: Any?): Boolean = when (other) { null -> false else -> javaClass == other.javaClass && hashCode() == other.hashCode() } override fun hashCode(): Int = System.identityHashCode(this) //HashCodeBuilder.reflectionHashCode(this) override fun toString(): String = buildStringHelper().toString() open protected fun buildStringHelper(): ToStringHelper = ToStringHelper(this) }
apache-2.0
a2f7f04f3bc219696e016f325a0f97dc
28.347826
105
0.72424
3.736842
false
false
false
false
aucd29/common
library/src/main/java/net/sarangnamu/common/BkMedia.kt
1
1429
/* * Copyright 2016 Burke Choi All rights reserved. * http://www.sarangnamu.net * * 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. */ @file:Suppress("NOTHING_TO_INLINE", "unused") package net.sarangnamu.common import android.content.Context import android.media.MediaMetadataRetriever import android.net.Uri import java.io.File import java.io.FileInputStream /** * Created by <a href="mailto:[email protected]">Burke Choi</a> on 2018. 5. 11.. <p/> */ inline fun String.isVideoPath(): Boolean { return File(this).isVideoPath() } inline fun File.isVideoPath(): Boolean { val retriever = MediaMetadataRetriever() try { retriever.setDataSource(FileInputStream(this).fd) val hasVideo = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO) return "yes" == hasVideo } catch (e: Exception) { e.printStackTrace() } return false }
apache-2.0
173473b755f7a04197e0449b0aab88dd
28.770833
95
0.714486
4.025352
false
false
false
false
herolynx/elepantry-android
app/src/main/java/com/herolynx/elepantry/ext/android/Storage.kt
1
3877
package com.herolynx.elepantry.ext.android import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Environment import android.webkit.MimeTypeMap import com.herolynx.elepantry.core.log.debug import com.herolynx.elepantry.core.log.warn import com.herolynx.elepantry.core.rx.subscribeOnDefault import org.funktionale.tries.Try import rx.Observable import rx.schedulers.Schedulers import java.io.File import java.io.FileOutputStream import java.io.OutputStream object Storage { private fun download(a: Activity, fileName: String, download: (OutputStream) -> Long): Observable<File> = Observable.defer { Storage.downloadDirectory(a) .map { downloadDir -> val file = File(downloadDir, fileName) if (file.exists()) { Observable.just(file) } else { Observable.defer { val bytes = FileOutputStream(file).use { outputStream -> download(outputStream) } debug("[Storage][Download] Download status - file: $file, bytes: $bytes") Observable.just(file) } } } .rescue { ex -> Try.Success(Observable.error(ex)) } .get() .map { file -> Storage.notifyAboutNewFile(a, file) file } } fun downloadAndOpen(activity: Activity, fileName: String, download: (OutputStream) -> Long, beforeAction: () -> Unit, afterAction: () -> Unit) { beforeAction() download(activity, fileName, download) .subscribeOnDefault() .observeOn(Schedulers.io()) .subscribe( { f -> activity.runOnUiThread { afterAction() Storage.viewFileInExternalApp(activity, f) } }, { ex -> warn("[Storage][File] Download & open error - $fileName", ex) afterAction() } ) } fun viewFileInExternalApp(a: Activity, f: File): Try<Boolean> = Try { val intent = Intent(Intent.ACTION_VIEW) val mime = MimeTypeMap.getSingleton() val ext = f.name.substring(f.name.indexOf(".") + 1) val type = mime.getMimeTypeFromExtension(ext) intent.setDataAndType(Uri.fromFile(f), type) // Check for a handler first to avoid a crash val manager = a.getPackageManager() val resolveInfo = manager.queryIntentActivities(intent, 0) if (resolveInfo.size > 0) { a.startActivity(intent) true } else { false } } .onFailure { ex -> warn("[Storage] Couldn't display file in external app - ${f.absolutePath}", ex) } fun notifyAboutNewFile(a: Activity, f: File) { val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) intent.data = Uri.fromFile(f) a.sendBroadcast(intent) } fun downloadDirectory(a: Activity): Try<File> = Try { Permissions.assertExternalStoragePermission(a) val downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) if (!downloadDir.exists() && !downloadDir.mkdirs()) { throw RuntimeException("Unable to create directory: $downloadDir") } else if (!downloadDir.isDirectory) { throw IllegalStateException("Download path is not a directory: $downloadDir") } downloadDir } .onFailure { ex -> warn("[Storage] Getting download directory error", ex) } }
gpl-3.0
ad69a93f220d0aca0cc9ca21764b20b3
38.171717
148
0.561001
4.989704
false
false
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/integrations/jei/TheJeiThing.kt
1
2092
package net.ndrei.teslapoweredthingies.integrations.jei import mezz.jei.api.IJeiRuntime import mezz.jei.api.IModPlugin import mezz.jei.api.IModRegistry import mezz.jei.api.JEIPlugin import mezz.jei.api.recipe.IRecipeCategoryRegistration import mezz.jei.api.recipe.VanillaRecipeCategoryUid import net.minecraft.block.Block import net.minecraft.item.ItemStack import net.ndrei.teslapoweredthingies.TeslaThingiesMod import net.ndrei.teslapoweredthingies.machines.poweredkiln.PoweredKilnBlock /** * Created by CF on 2017-06-30. */ @JEIPlugin class TheJeiThing : IModPlugin { override fun register(registry: IModRegistry) { TheJeiThing.blocksMap.values.forEach { it.register(registry) } registry.addRecipeCatalyst(ItemStack(PoweredKilnBlock), VanillaRecipeCategoryUid.SMELTING) } override fun registerCategories(registry: IRecipeCategoryRegistration?) { if (registry != null) { TheJeiThing.blocksMap.values.forEach { it.register(registry) } } else TeslaThingiesMod.logger.warn("TheJeiThing::registerCategories - Null registry received.") } override fun onRuntimeAvailable(jeiRuntime: IJeiRuntime?) { if (jeiRuntime != null) { TheJeiThing.JEI = jeiRuntime } else TeslaThingiesMod.logger.warn("TheJeiThing::onRuntimeAvailable - Null runtime received.") } companion object { var JEI: IJeiRuntime? = null private set private val blocksMap = mutableMapOf<Block, BaseCategory<*>>() fun registerCategory(category: BaseCategory<*>) { blocksMap[category.block] = category } fun isBlockRegistered(block: Block): Boolean = blocksMap.containsKey(block) fun showCategory(block: Block) { if ((JEI != null) && (blocksMap.containsKey(block))) { JEI!!.recipesGui.showCategories(mutableListOf( blocksMap[block]!!.uid )) } } val isJeiAvailable: Boolean get() = (JEI != null) } }
mit
bff9ca1bdde2df9cdb0ac8104016cc70
31.6875
101
0.67304
4.349272
false
false
false
false
grassrootza/grassroot-android-v2
app/src/main/java/za/org/grassroot2/view/fragment/ActionSingleInputFragment.kt
1
3607
package za.org.grassroot2.view.fragment import android.content.Context import android.os.Bundle import android.text.InputType import android.view.Gravity import android.view.inputmethod.EditorInfo import butterknife.OnClick import com.jakewharton.rxbinding2.view.RxView import com.jakewharton.rxbinding2.widget.RxTextView import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.subjects.PublishSubject import kotlinx.android.synthetic.main.fragment_meeting_single_input.* import za.org.grassroot2.R import za.org.grassroot2.dagger.activity.ActivityComponent import java.util.concurrent.TimeUnit class ActionSingleInputFragment : GrassrootFragment() { override val layoutResourceId: Int get() = R.layout.fragment_meeting_single_input private val actionSubject = PublishSubject.create<String>() private var listener: BackNavigationListener? = null var isMultiLine: Boolean = false override fun onAttach(context: Context?) { super.onAttach(context) listener = activity as BackNavigationListener? } @OnClick(R.id.backNav) internal fun back() { listener!!.backPressed() } @OnClick(R.id.cancel) internal fun close() { activity!!.finish() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) inputContainer.hint = getString(arguments!!.getInt(EXTRA_HINT_RES)) setMultilineIfRequired() header.setText(arguments!!.getInt(EXTRA_TITLE_RES)) item_description.setText(arguments!!.getInt(EXTRA_DESC_RES)) if (arguments!!.getBoolean(EXTRA_CAN_SKIP, false)) { cancel.setText(R.string.button_skip) cancel.setOnClickListener { v -> actionSubject.onNext("") } } disposables.add(RxTextView.textChanges(input!!).debounce(500, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ charSequence -> next!!.isEnabled = charSequence.length > 3 }, { it.printStackTrace() })) RxView.clicks(next!!).map { o -> input!!.text.toString() }.subscribe(actionSubject) RxTextView.editorActionEvents(input!!) { textViewEditorActionEvent -> textViewEditorActionEvent.actionId() == EditorInfo.IME_ACTION_DONE && input!!.length() > 3 } .map { _ -> input!!.text.toString() }.subscribe(actionSubject) } private fun setMultilineIfRequired() { if (isMultiLine) { input!!.inputType = InputType.TYPE_TEXT_FLAG_MULTI_LINE input!!.setSingleLine(false) input!!.gravity = Gravity.LEFT or Gravity.TOP input!!.maxLines = 5 input!!.minLines = 5 } } fun inputAdded(): Observable<String> = actionSubject override fun onInject(activityComponent: ActivityComponent) { activityComponent.inject(this) } companion object { private val EXTRA_TITLE_RES = "title_res" private val EXTRA_DESC_RES = "desc_res" private val EXTRA_HINT_RES = "hint_res" private val EXTRA_CAN_SKIP = "can_skip" fun newInstance(resTitle: Int, resDesc: Int, resHint: Int, canSkip: Boolean): ActionSingleInputFragment { val f = ActionSingleInputFragment() val b = Bundle() b.putInt(EXTRA_TITLE_RES, resTitle) b.putInt(EXTRA_DESC_RES, resDesc) b.putInt(EXTRA_HINT_RES, resHint) b.putBoolean(EXTRA_CAN_SKIP, canSkip) f.arguments = b return f } } }
bsd-3-clause
14f57033bbc9e5a1cf6912c759b23984
36.572917
170
0.676185
4.486318
false
false
false
false
nemerosa/ontrack
ontrack-extension-indicators/src/test/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/GQLTypeIndicatorViewProjectReportIT.kt
1
7975
package net.nemerosa.ontrack.extension.indicators.ui.graphql import net.nemerosa.ontrack.extension.indicators.AbstractIndicatorsTestSupport import net.nemerosa.ontrack.extension.indicators.model.Rating import net.nemerosa.ontrack.extension.indicators.support.Percentage import net.nemerosa.ontrack.test.assertJsonNull import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull class GQLTypeIndicatorViewProjectReportIT : AbstractIndicatorsTestSupport() { @Test fun `Getting report for a view`() { // Creating a view with 1 category val category = category() val types = (1..3).map { no -> category.booleanType(id = "${category.id}-$no") } val view = indicatorView(categories = listOf(category)) // Projects with indicator values for this view's category val projects = (1..3).map { project() } projects.forEach { project -> types.forEachIndexed { index, type -> project.indicator(type, index % 2 == 0) // true, false, true ==> 100, 0, 100 ==> 66 avg } } // Projects without indicator values for this view's category val unsetProjects = (1..2).map { project() } // Getting the view report run( """ { indicatorViewList { views(id: "${view.id}") { reports { project { name } viewStats { category { name } stats { min avg max avgRating } } } } } } """ ).let { data -> val reports = data.path("indicatorViewList").path("views").first().path("reports") /** * Reports indexed by project */ val projectReports = reports.associate { report -> report.path("project").path("name").asText() to report.path("viewStats") } // Projects with values projects.forEach { project -> val projectStats = projectReports[project.name] assertNotNull(projectStats) { stats -> assertEquals(1, stats.size()) val categoryStats = stats.first() assertEquals(category.name, categoryStats.path("category").path("name").asText()) assertEquals(0, categoryStats.path("stats").path("min").asInt()) assertEquals(66, categoryStats.path("stats").path("avg").asInt()) assertEquals(100, categoryStats.path("stats").path("max").asInt()) assertEquals("C", categoryStats.path("stats").path("avgRating").asText()) } } // Projects without value unsetProjects.forEach { project -> val projectStats = projectReports[project.name] assertNotNull(projectStats) { stats -> assertEquals(1, stats.size()) val categoryStats = stats.first() assertEquals(category.name, categoryStats.path("category").path("name").asText()) assertJsonNull(categoryStats.path("stats").path("min")) assertJsonNull(categoryStats.path("stats").path("avg")) assertJsonNull(categoryStats.path("stats").path("max")) assertJsonNull(categoryStats.path("stats").path("avgRating")) } } } } @Test fun `Getting report for a view filtered on rate`() { // Creating a view with 1 category val category = category() val types = (1..3).map { no -> category.percentageType(id = "${category.id}-$no", threshold = 100) // Percentage == Compliance } val view = indicatorView(categories = listOf(category)) // Projects with indicator values for this view's category val projects = (1..3).map { project() } projects.forEachIndexed { pi, project -> types.forEachIndexed { ti, type -> project.indicator(type, Percentage((pi * 3 + ti) * 10)) /** * List of values * * Project 0 * Type 0 Value = 0 Rating = F * Type 1 Value = 10 Rating = F * Type 2 Value = 20 Rating = F * Avg Value = 10 Rating = F * Project 1 * Type 0 Value = 30 Rating = E * Type 1 Value = 40 Rating = D * Type 2 Value = 50 Rating = D * Avg Value = 40 Rating = D * Project 2 * Type 0 Value = 60 Rating = C * Type 1 Value = 70 Rating = C * Type 2 Value = 80 Rating = B * Avg Value = 70 Rating = C */ } } // Getting the view report for different rates val expectedRates = mapOf( Rating.A to (0..2), Rating.B to (0..2), Rating.C to (0..2), Rating.D to (0..1), Rating.E to (0..0), Rating.F to (0..0), ) expectedRates.forEach { (rating, expectedProjects) -> run( """ { indicatorViewList { views(id: "${view.id}") { reports(rate: "$rating") { project { name } viewStats { category { name } stats { min avg max avgRating } } } } } } """ ).let { data -> val reports = data.path("indicatorViewList").path("views").first().path("reports") val projectNames = reports.map { it.path("project").path("name").asText() } val actualRatings = reports.map { it.path("viewStats").path(0).path("stats").path("avgRating").asText() }.map { Rating.valueOf(it) } val expectedProjectNames = expectedProjects.map { index -> projects[index].name } println("---- Checking for rate $rating") println("Expecting: $expectedProjectNames") println("Actual : $projectNames") projectNames.zip(actualRatings).forEach { (p, r) -> println("Project $p, rating = $r") } assertEquals( expectedProjectNames, projectNames, "Expecting ${expectedProjectNames.size} projects having rating worse or equal than $rating" ) } } } }
mit
119febfcd0076ab4764f76482f9883f9
39.282828
111
0.427335
5.688302
false
false
false
false
nemerosa/ontrack
ontrack-service/src/test/java/net/nemerosa/ontrack/service/security/TokenHeaderAuthenticationProviderTest.kt
1
4194
package net.nemerosa.ontrack.service.security import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import net.nemerosa.ontrack.common.Time import net.nemerosa.ontrack.model.security.* import net.nemerosa.ontrack.model.structure.ID import net.nemerosa.ontrack.model.structure.Token import net.nemerosa.ontrack.model.structure.TokenAccount import net.nemerosa.ontrack.model.structure.TokensService import net.nemerosa.ontrack.test.assertIs import org.junit.Before import org.junit.Test import org.springframework.security.authentication.CredentialsExpiredException import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import java.time.Duration import kotlin.test.* class TokenHeaderAuthenticationProviderTest { private lateinit var tokensService: TokensService private lateinit var accountService: AccountService private lateinit var provider: TokenHeaderAuthenticationProvider private lateinit var source: AuthenticationSource @Before fun before() { tokensService = mock() accountService = mock() provider = TokenHeaderAuthenticationProvider( tokensService, accountService ) source = AuthenticationSource( provider = BuiltinAuthenticationSourceProvider.ID, key = "", name = "Built-in", isEnabled = true, isAllowingPasswordChange = true ) } @Test fun `Requires token`() { assertTrue(provider.supports(TokenAuthenticationToken::class.java)) } @Test fun `Authenticating something else than a token`() { val authentication = provider.authenticate(UsernamePasswordAuthenticationToken("user", "xxx")) assertNull(authentication) } @Test fun `Token not found`() { val auth = TokenAuthenticationToken("xxx") val result = provider.authenticate(auth) assertNull(result) } @Test fun `Token found but invalid`() { val auth = TokenAuthenticationToken("xxx") val tokenAccount = TokenAccount( account = Account( ID.of(1), "user", "User", "[email protected]", source, SecurityRole.USER, disabled = false, locked = false, ), token = Token( "xxx", Time.now() - Duration.ofHours(24), Time.now() - Duration.ofHours(12) // Stopped being valid 12 hours ago ) ) whenever(tokensService.findAccountByToken("xxx")).thenReturn(tokenAccount) assertFailsWith<CredentialsExpiredException> { provider.authenticate(auth) } } @Test fun `Token found`() { val auth = TokenAuthenticationToken("xxx") val tokenAccount = TokenAccount( account = Account( ID.of(1), "user", "User", "[email protected]", source, SecurityRole.USER, disabled = false, locked = false, ), token = Token( "xxx", Time.now(), null ) ) whenever(tokensService.findAccountByToken("xxx")).thenReturn(tokenAccount) val user = mock<OntrackAuthenticatedUser>() whenever(accountService.withACL(any())).thenReturn(user) val result = provider.authenticate(auth) assertNotNull(result) { authenticated -> assertIs<TokenAuthenticationToken>(authenticated) { u -> assertSame(u.principal, user, "Authenticated user is set") assertEquals("", u.credentials, "Credentials gone") assertTrue(u.isAuthenticated, "Authentication OK") } } } }
mit
ef6588b8a2c70627884d663bb61103a6
33.669421
102
0.58083
5.503937
false
true
false
false
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/dvr/RecordingUtils.kt
1
6129
package org.tvheadend.tvhclient.ui.features.dvr import android.content.Context import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.list.customListAdapter import com.afollestad.materialdialogs.list.listItemsMultiChoice import com.afollestad.materialdialogs.list.listItemsSingleChoice import org.tvheadend.data.entity.Channel import org.tvheadend.data.entity.ServerProfile import org.tvheadend.tvhclient.R import timber.log.Timber import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.CopyOnWriteArrayList fun getPriorityName(context: Context, priority: Int): String { val priorityNames = context.resources.getStringArray(R.array.dvr_priority_names) return when (priority) { in 0..4 -> priorityNames[priority] 6 -> priorityNames[5] else -> "" } } fun getDateStringFromTimeInMillis(milliSeconds: Long): String { val sdf = SimpleDateFormat("dd.MM", Locale.US) return sdf.format(milliSeconds) } fun getTimeStringFromTimeInMillis(milliSeconds: Long): String { val sdf = SimpleDateFormat("HH:mm", Locale.US) return sdf.format(milliSeconds) } fun getSelectedDaysOfWeekText(context: Context, daysOfWeek: Int): String { val daysOfWeekList = context.resources.getStringArray(R.array.day_short_names) val text = StringBuilder() for (i in 0..6) { val s = if (daysOfWeek shr i and 1 == 1) daysOfWeekList[i] else "" if (text.isNotEmpty() && s.isNotEmpty()) { text.append(", ") } text.append(s) } return text.toString() } fun handleDayOfWeekSelection(context: Context, daysOfWeek: Int, callback: RecordingConfigSelectedListener?) { // Get the selected indices by storing the bits with 1 positions in a list // This list then needs to be converted to an Integer[] because the // material dialog requires this val list = ArrayList<Int>() for (i in 0..6) { val value = daysOfWeek shr i and 1 if (value == 1) { list.add(i) } } MaterialDialog(context).show { title(R.string.days_of_week) positiveButton(R.string.select) listItemsMultiChoice(R.array.day_long_names, initialSelection = list.toMutableList().toIntArray()) { _, index, _ -> var selectedDays = 0 for (i in index) { selectedDays += 1 shl i } callback?.onDaysSelected(selectedDays) } } } fun handleChannelListSelection(context: Context, channelList: List<Channel>, showAllChannelsListEntry: Boolean, callback: RecordingConfigSelectedListener?) { // Fill the channel tag adapter with the available channel tags val channels = CopyOnWriteArrayList(channelList) // Add the default channel (all channels) // to the list after it has been sorted if (showAllChannelsListEntry) { val channel = Channel() channel.id = 0 channel.name = context.getString(R.string.all_channels) channels.add(0, channel) } val channelListSelectionAdapter = ChannelListSelectionAdapter(context, channels) // Show the dialog that shows all available channel tags. When the // user has selected a tag, restart the loader to loadRecordingById the updated channel list val dialog: MaterialDialog = MaterialDialog(context).show { title(R.string.tags) customListAdapter(channelListSelectionAdapter) } // Set the callback to handle clicks. This needs to be done after the // dialog creation so that the inner method has access to the dialog variable channelListSelectionAdapter.setCallback(object : ChannelListSelectionAdapter.Callback { override fun onItemClicked(channel: Channel) { callback?.onChannelSelected(channel) dialog.dismiss() } }) } fun handlePrioritySelection(context: Context, selectedPriority: Int, callback: RecordingConfigSelectedListener?) { Timber.d("Selected priority is ${if (selectedPriority == 6) 5 else selectedPriority}") MaterialDialog(context).show { title(R.string.select_priority) listItemsSingleChoice(R.array.dvr_priority_names, initialSelection = if (selectedPriority == 6) 5 else selectedPriority) { _, index, _ -> Timber.d("New selected priority is ${if (index == 5) 6 else index}") callback?.onPrioritySelected(if (index == 5) 6 else index) } } } fun handleRecordingProfileSelection(context: Context, recordingProfilesList: Array<String>, selectedProfile: Int, callback: RecordingConfigSelectedListener?) { MaterialDialog(context).show { title(R.string.select_dvr_config) listItemsSingleChoice(items = recordingProfilesList.toList(), initialSelection = selectedProfile) { _, index, _ -> callback?.onProfileSelected(index) } } } fun getSelectedProfileId(profile: ServerProfile?, recordingProfilesList: Array<String>): Int { if (profile != null) { for (i in recordingProfilesList.indices) { if (recordingProfilesList[i] == profile.name) { return i } } } return 0 } fun handleDateSelection(activity: FragmentActivity?, milliSeconds: Long, callback: Fragment, tag: String) { activity?.let { val newFragment = DatePickerFragment() val bundle = Bundle() bundle.putLong("milliSeconds", milliSeconds) newFragment.arguments = bundle newFragment.setTargetFragment(callback, 1) newFragment.show(activity.supportFragmentManager, tag) } } fun handleTimeSelection(activity: FragmentActivity?, milliSeconds: Long, callback: Fragment, tag: String) { activity?.let { val newFragment = TimePickerFragment() val bundle = Bundle() bundle.putLong("milliSeconds", milliSeconds) newFragment.arguments = bundle newFragment.setTargetFragment(callback, 1) newFragment.show(activity.supportFragmentManager, tag) } }
gpl-3.0
54c1744631daea370d275f62b05e3bd3
38.038217
159
0.696688
4.546736
false
false
false
false
whoww/SneakPeek
app/src/main/java/de/sneakpeek/ui/main/fragment/StudiosFragment.kt
1
2497
package de.sneakpeek.ui.main.fragment import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import de.sneakpeek.R import de.sneakpeek.adapter.StudiosAdapter import de.sneakpeek.service.MovieRepository import de.sneakpeek.util.DividerItemDecoration import de.sneakpeek.util.inflate import de.sneakpeek.view.FastScroll import de.sneakpeek.view.FastScrollItemDecorator import io.reactivex.disposables.CompositeDisposable class StudiosFragment : Fragment() { private var subscriptions: CompositeDisposable = CompositeDisposable() private val studiosAdapter: StudiosAdapter by lazy { StudiosAdapter(emptyList()) } var fastScroll: FastScroll? = null override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { fastScroll = container?.inflate(R.layout.fragment_studios) as FastScroll fastScroll?.let { it.setHasFixedSize(true) it.layoutManager = LinearLayoutManager(context) it.adapter = studiosAdapter it.addItemDecoration(FastScrollItemDecorator(context)) it.itemAnimator = DefaultItemAnimator() val itemDecoration = DividerItemDecoration(activity, DividerItemDecoration.VERTICAL_LIST) it.addItemDecoration(itemDecoration) } return fastScroll } override fun onStart() { super.onStart() subscriptions = CompositeDisposable() loadStudios() } override fun onStop() { super.onStop() subscriptions.dispose() } fun loadStudios() { val subscription = MovieRepository(context).getStudios() ?.subscribe({ studiosAdapter.addAll(it) fastScroll?.forceReSetup() }) { throwable -> Toast.makeText(context, "Failed to fetch movies", Toast.LENGTH_SHORT).show() Log.e(TAG, "Failed to fetch movie moviePredictions", throwable) } subscriptions.add(subscription) } companion object { private val TAG = StudiosFragment::class.java.simpleName fun newInstance(): StudiosFragment { return StudiosFragment() } } }
mit
beb140166b36fadca5b96d9e75daea30
31.441558
117
0.690429
5.064909
false
false
false
false
google-pay/loyalty-api-kotlin
app/src/main/java/com/example/loyaltyapidemo/data/SignUpRepository.kt
1
2508
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.example.loyaltyapidemo.data import com.android.volley.RequestQueue import com.android.volley.toolbox.BasicNetwork import com.android.volley.toolbox.HurlStack import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.NoCache import org.json.JSONObject import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine class SignUpRepository { private val requestQueue: RequestQueue init { // Instantiate the cache val cache = NoCache() // Set up the network to use HttpURLConnection as the HTTP client. val network = BasicNetwork(HurlStack()) // Instantiate the RequestQueue with the cache and network. Start the queue. requestQueue = RequestQueue(cache, network).apply { start() } } /** * Calls the sample app's backend API to create a loyalty pass. * * The API returns a token in the form of a JWT which is returned by this method * * @return A JWT that can be used to save the pass with Google Pay */ suspend fun signUp(name: String, email: String): String { // Step 1: call our API to create a loyalty pass throw NotImplementedError("TODO: implement me") // Step 2: return the JWT from the token field throw NotImplementedError("TODO: implement me") } private suspend fun executeJsonRequest(method: Int, url: String, body: JSONObject? = null) = suspendCoroutine<JSONObject> { cont -> val request = JsonObjectRequest( method, url, body, { response -> cont.resume(response) }, { error -> cont.resumeWithException(error) } ) requestQueue.add(request) } }
apache-2.0
e9ffe982581c2e871dd75069c53f54f2
32.891892
96
0.658293
4.732075
false
false
false
false
alaminopu/IST-Syllabus
app/src/main/java/org/istbd/IST_Syllabus/App.kt
1
1132
package org.istbd.IST_Syllabus import androidx.compose.material.Scaffold import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.res.colorResource import androidx.navigation.compose.rememberNavController import com.google.accompanist.insets.ProvideWindowInsets import com.google.accompanist.pager.ExperimentalPagerApi import org.istbd.IST_Syllabus.db.CourseEntity import org.istbd.IST_Syllabus.ui.theme.ISTTheme @ExperimentalPagerApi @Composable fun App(courses: List<CourseEntity>) { ProvideWindowInsets { ISTTheme { val tabs = remember { TabSections.values() } val navController = rememberNavController() Scaffold( bottomBar = { Surface(color = colorResource(id = R.color.ist)) { BottomBar(navController = navController, tabs = tabs) } } ) { innerPaddingModifier -> PrepareNavHost(navController, innerPaddingModifier, courses) } } } }
gpl-2.0
20b4118c9fa7c08569d16ca4c44858c4
33.30303
77
0.680212
4.697095
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/view/tween/ViewTween.kt
1
2591
package com.soywiz.korge.view.tween import com.soywiz.klock.* import com.soywiz.korge.tween.* import com.soywiz.korge.view.* import com.soywiz.korma.geom.* import com.soywiz.korma.interpolation.* suspend fun View.show(time: TimeSpan = DEFAULT_TIME, easing: Easing = DEFAULT_EASING) = tween(this::alpha[1.0], time = time, easing = easing) { this.visible = true } suspend fun View.hide(time: TimeSpan = DEFAULT_TIME, easing: Easing = DEFAULT_EASING) = tween(this::alpha[0.0], time = time, easing = easing) suspend inline fun View.moveTo(x: Double, y: Double, time: TimeSpan = DEFAULT_TIME, easing: Easing = DEFAULT_EASING) = tween(this::x[x], this::y[y], time = time, easing = easing) suspend inline fun View.moveTo(x: Float, y: Float, time: TimeSpan = DEFAULT_TIME, easing: Easing = DEFAULT_EASING) = tween(this::x[x], this::y[y], time = time, easing = easing) suspend inline fun View.moveTo(x: Int, y: Int, time: TimeSpan = DEFAULT_TIME, easing: Easing = DEFAULT_EASING) = tween(this::x[x], this::y[y], time = time, easing = easing) suspend inline fun View.moveBy(dx: Double, dy: Double, time: TimeSpan = DEFAULT_TIME, easing: Easing = DEFAULT_EASING) = tween(this::x[this.x + dx], this::y[this.y + dy], time = time, easing = easing) suspend inline fun View.moveBy(dx: Float, dy: Float, time: TimeSpan = DEFAULT_TIME, easing: Easing = DEFAULT_EASING) = tween(this::x[this.x + dx], this::y[this.y + dy], time = time, easing = easing) suspend inline fun View.moveBy(dx: Int, dy: Int, time: TimeSpan = DEFAULT_TIME, easing: Easing = DEFAULT_EASING) = tween(this::x[this.x + dx], this::y[this.y + dy], time = time, easing = easing) suspend inline fun View.scaleTo(sx: Double, sy: Double, time: TimeSpan = DEFAULT_TIME, easing: Easing = DEFAULT_EASING) = tween(this::scaleX[sx], this::scaleY[sy], time = time, easing = easing) suspend inline fun View.scaleTo(sx: Float, sy: Float, time: TimeSpan = DEFAULT_TIME, easing: Easing = DEFAULT_EASING) = tween(this::scaleX[sx], this::scaleY[sy], time = time, easing = easing) suspend inline fun View.scaleTo(sx: Int, sy: Int, time: TimeSpan = DEFAULT_TIME, easing: Easing = DEFAULT_EASING) = tween(this::scaleX[sx], this::scaleY[sy], time = time, easing = easing) suspend inline fun View.rotateTo(angle: Angle, time: TimeSpan = DEFAULT_TIME, easing: Easing = DEFAULT_EASING) = tween(this::rotation[angle], time = time, easing = easing) suspend inline fun View.rotateBy(deltaAngle: Angle, time: TimeSpan = DEFAULT_TIME, easing: Easing = DEFAULT_EASING) = tween(this::rotation[rotation + deltaAngle], time = time, easing = easing)
apache-2.0
cb63bdd90434f2c253eaa86457931d50
82.580645
200
0.708993
3.22665
false
false
false
false
Orchextra/orchextra-android-sdk
core/src/main/java/com/gigigo/orchextra/core/data/datasources/db/models/DbTrigger.kt
1
1695
/* * Created by Orchextra * * Copyright (C) 2017 Gigigo Mobile Services SL * * 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.gigigo.orchextra.core.data.datasources.db.models import com.gigigo.orchextra.core.data.datasources.db.caching.strategy.ttl.TtlCachingObject import com.j256.ormlite.field.DatabaseField import com.j256.ormlite.table.DatabaseTable @DatabaseTable(tableName = "trigger") class DbTrigger : TtlCachingObject { @DatabaseField(generatedId = true, columnName = "id") var id: Int = 0 @DatabaseField var type: String = "" @DatabaseField(columnName = "value") var value: String = "" @DatabaseField var lat: Double? = null @DatabaseField var lng: Double? = null @DatabaseField var event: String? = null @DatabaseField var phoneStatus: String? = null @DatabaseField var distance: String? = null @DatabaseField var temperature: Float? = null @DatabaseField var battery: Long? = null @DatabaseField var uptime: Long? = null @DatabaseField var detectedTime: Long = System.currentTimeMillis() @DatabaseField var dbPersistedTime: Long = 0 override fun getPersistedTime(): Long = dbPersistedTime }
apache-2.0
aca07b81dc1c6a699ca6bd3902125f3f
23.941176
90
0.735693
3.951049
false
false
false
false
konfko/konfko
konfko-core/src/main/kotlin/com/github/konfko/core/derived/PrefixedSettings.kt
1
1198
package com.github.konfko.core.derived import com.github.konfko.core.Settings import com.github.konfko.core.structured.SettingKey /** * @author markopi */ class PrefixedSettings(override val parent: Settings, prefix: String) : DerivedValueSettings<Any?>() { private val prefix = prefix.removeSuffix(".") override fun makeParentKey(key: String): String { if (prefix == "") return key check(key.startsWith(prefix)) { "Tried to retrieve setting with key [$key] which does not start with prefix [$prefix]" } if (key==prefix) return "" return key.substring(prefix.length+1) } override val derivedValue: Any? = prependPrefixed(this.prefix, parent.toNestedMap()) private fun prependPrefixed(prefix: String, value: Map<String, Any>): Any? { if (prefix == "") return value val key = SettingKey.parse(prefix) val result: Map<String, Any> = key.segments.foldRight(value, { segment, map -> mutableMapOf<String, Any>().apply { set(segment.property, map) } }) return result } } fun Settings.prefixBy(prefix: String ): DerivedSettings = PrefixedSettings(this, prefix)
apache-2.0
1f11442bc32190a66bd86b59d4600134
34.235294
128
0.659432
4.07483
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/iface/IControlBarActivity.kt
1
4628
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.activity.iface import android.animation.Animator import android.animation.Animator.AnimatorListener import android.animation.ObjectAnimator import android.util.Property import android.view.animation.DecelerateInterpolator interface IControlBarActivity { /** * 0: invisible, 1: visible */ var controlBarOffset: Float get() = 0f set(value) {} val controlBarHeight: Int get() = 0 fun setControlBarVisibleAnimate(visible: Boolean, listener: ControlBarShowHideHelper.ControlBarAnimationListener? = null) {} fun registerControlBarOffsetListener(listener: ControlBarOffsetListener) {} fun unregisterControlBarOffsetListener(listener: ControlBarOffsetListener) {} fun notifyControlBarOffsetChanged() {} interface ControlBarOffsetListener { fun onControlBarOffsetChanged(activity: IControlBarActivity, offset: Float) } class ControlBarShowHideHelper(private val activity: IControlBarActivity) { private var controlAnimationDirection: Int = 0 private var currentControlAnimation: ObjectAnimator? = null private object ControlBarOffsetProperty : Property<IControlBarActivity, Float>(Float::class.java, null) { override fun set(obj: IControlBarActivity, value: Float) { obj.controlBarOffset = (value) } override fun get(obj: IControlBarActivity): Float { return obj.controlBarOffset } } interface ControlBarAnimationListener { fun onControlBarVisibleAnimationStart(visible: Boolean) {} fun onControlBarVisibleAnimationFinish(visible: Boolean) {} } fun setControlBarVisibleAnimate(visible: Boolean, listener: ControlBarAnimationListener? = null) { val newDirection = if (visible) 1 else -1 if (controlAnimationDirection == newDirection) return if (currentControlAnimation != null && controlAnimationDirection != 0) { currentControlAnimation!!.cancel() currentControlAnimation = null controlAnimationDirection = newDirection } val animator: ObjectAnimator val offset = activity.controlBarOffset if (visible) { if (offset >= 1) return animator = ObjectAnimator.ofFloat(activity, ControlBarOffsetProperty, offset, 1f) } else { if (offset <= 0) return animator = ObjectAnimator.ofFloat(activity, ControlBarOffsetProperty, offset, 0f) } animator.interpolator = DecelerateInterpolator() animator.addListener(object : AnimatorListener { override fun onAnimationStart(animation: Animator) { listener?.onControlBarVisibleAnimationStart(visible) } override fun onAnimationEnd(animation: Animator) { controlAnimationDirection = 0 currentControlAnimation = null listener?.onControlBarVisibleAnimationFinish(visible) } override fun onAnimationCancel(animation: Animator) { controlAnimationDirection = 0 currentControlAnimation = null } override fun onAnimationRepeat(animation: Animator) { } }) animator.duration = DURATION animator.start() currentControlAnimation = animator controlAnimationDirection = newDirection } companion object { private const val DURATION = 200L } } }
gpl-3.0
c3bd162d8de006573cc47a1940e1c378
36.330645
128
0.65471
5.125138
false
false
false
false
lchli/MiNote
host/src/main/java/com/lch/menote/kotlinext/ContextExt.kt
1
1821
package com.lch.menote.kotlinext import android.R import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.Paint import android.util.Log import android.widget.ArrayAdapter import android.widget.Toast import com.lch.menote.BuildConfig import com.lchli.utils.tool.UiHandler import com.orhanobut.dialogplus.DialogPlus import com.orhanobut.dialogplus.OnItemClickListener /** * Created by Administrator on 2017/9/21. */ private val GLOBAL_TAG = "MiNote" private val LOG_ENABLE = BuildConfig.DEBUG fun Context.launchActivity(clazz: Class<out Activity>) { val it = Intent(this, clazz) it.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(it) } fun Context.toast(msg: String?, duration: Int = Toast.LENGTH_SHORT) { if (msg == null) { return } UiHandler.post({ Toast.makeText(this, msg, duration).show() }) } fun Context.launchActivity(it: Intent) { if (this !is Activity) { it.flags = Intent.FLAG_ACTIVITY_NEW_TASK } startActivity(it) } fun Context.evalFontHeight(p: Paint): Float { return Math.ceil((p.fontMetrics.descent - p.fontMetrics.ascent).toDouble()).toFloat() } fun Context.log(tag: String, msg: String) { Log.e(tag, msg) } fun Context.log(msg: String) { log(GLOBAL_TAG, msg) } fun Context.logIfDebug(msg: String) { if (LOG_ENABLE) { log(msg) } } fun Context.showListDialog(listener: OnItemClickListener, expand: Boolean = false, items: List<String>): DialogPlus { val adp = ArrayAdapter<String>(this, R.layout.simple_expandable_list_item_1, items) val dia = DialogPlus.newDialog(this) .setAdapter(adp) .setOnItemClickListener(listener) .setExpanded(expand) .create() dia.show() return dia }
gpl-3.0
8123a4beab518d4b809c6c96d0965df4
23.945205
117
0.697419
3.584646
false
false
false
false
AndroidX/androidx
compose/material/material/src/commonMain/kotlin/androidx/compose/material/Badge.kt
3
7039
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.FirstBaseline import androidx.compose.ui.layout.LastBaseline import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.layoutId import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp /** * A BadgeBox is used to decorate [content] with a [badge] that can contain dynamic information, * such * as the presence of a new notification or a number of pending requests. Badges can be icon only * or contain short text. * * A common use case is to display a badge with bottom navigation items. * For more information, see [Bottom Navigation](https://material.io/components/bottom-navigation#behavior) * * A simple icon with badge example looks like: * @sample androidx.compose.material.samples.BottomNavigationItemWithBadge * * @param badge the badge to be displayed - typically a [Badge] * @param modifier optional [Modifier] for this item * @param content the anchor to which this badge will be positioned * */ @Composable fun BadgedBox( badge: @Composable BoxScope.() -> Unit, modifier: Modifier = Modifier, content: @Composable BoxScope.() -> Unit, ) { Layout( { Box( modifier = Modifier.layoutId("anchor"), contentAlignment = Alignment.Center, content = content ) Box( modifier = Modifier.layoutId("badge"), content = badge ) }, modifier = modifier ) { measurables, constraints -> val badgePlaceable = measurables.first { it.layoutId == "badge" }.measure( // Measure with loose constraints for height as we don't want the text to take up more // space than it needs. constraints.copy(minHeight = 0) ) val anchorPlaceable = measurables.first { it.layoutId == "anchor" }.measure(constraints) val firstBaseline = anchorPlaceable[FirstBaseline] val lastBaseline = anchorPlaceable[LastBaseline] val totalWidth = anchorPlaceable.width val totalHeight = anchorPlaceable.height layout( totalWidth, totalHeight, // Provide custom baselines based only on the anchor content to avoid default baseline // calculations from including by any badge content. mapOf( FirstBaseline to firstBaseline, LastBaseline to lastBaseline ) ) { // Use the width of the badge to infer whether it has any content (based on radius used // in [Badge]) and determine its horizontal offset. val hasContent = badgePlaceable.width > (2 * BadgeRadius.roundToPx()) val badgeHorizontalOffset = if (hasContent) BadgeWithContentHorizontalOffset else BadgeHorizontalOffset anchorPlaceable.placeRelative(0, 0) val badgeX = anchorPlaceable.width + badgeHorizontalOffset.roundToPx() val badgeY = -badgePlaceable.height / 2 badgePlaceable.placeRelative(badgeX, badgeY) } } } /** * Badge is a component that can contain dynamic information, such as the presence of a new * notification or a number of pending requests. Badges can be icon only or contain short text. * * See [BadgedBox] for a top level layout that will properly place the badge relative to content * such as text or an icon. * * @param modifier optional [Modifier] for this item * @param backgroundColor the background color for the badge * @param contentColor the color of label text rendered in the badge * @param content optional content to be rendered inside the badge * */ @Composable fun Badge( modifier: Modifier = Modifier, backgroundColor: Color = MaterialTheme.colors.error, contentColor: Color = contentColorFor(backgroundColor), content: @Composable (RowScope.() -> Unit)? = null, ) { val radius = if (content != null) BadgeWithContentRadius else BadgeRadius val shape = RoundedCornerShape(radius) // Draw badge container. Row( modifier = modifier .defaultMinSize(minWidth = radius * 2, minHeight = radius * 2) .background( color = backgroundColor, shape = shape ) .clip(shape) .padding( horizontal = BadgeWithContentHorizontalPadding ), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { if (content != null) { CompositionLocalProvider( LocalContentColor provides contentColor ) { val style = MaterialTheme.typography.button.copy(fontSize = BadgeContentFontSize) ProvideTextStyle( value = style, content = { content() } ) } } } } /*@VisibleForTesting*/ internal val BadgeRadius = 4.dp /*@VisibleForTesting*/ internal val BadgeWithContentRadius = 8.dp private val BadgeContentFontSize = 10.sp /*@VisibleForTesting*/ // Leading and trailing text padding when a badge is displaying text that is too long to fit in // a circular badge, e.g. if badge number is greater than 9. internal val BadgeWithContentHorizontalPadding = 4.dp /*@VisibleForTesting*/ // Horizontally align start/end of text badge 6dp from the end/start edge of its anchor internal val BadgeWithContentHorizontalOffset = -6.dp /*@VisibleForTesting*/ // Horizontally align start/end of icon only badge 4dp from the end/start edge of anchor internal val BadgeHorizontalOffset = -4.dp
apache-2.0
6884ba1e73144c8486bd58a84fc06f60
36.844086
107
0.688308
4.824537
false
false
false
false
AndroidX/androidx
window/window/src/testUtil/java/androidx/window/layout/TestWindowMetricsCalculator.kt
3
2704
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.window.layout import android.app.Activity import android.graphics.Rect /** * Implementation of [WindowMetricsCalculator] for testing. * * @see WindowMetricsCalculator */ internal class TestWindowMetricsCalculator : WindowMetricsCalculator { private var globalOverriddenBounds: Rect? = null private val overriddenBounds = mutableMapOf<Activity, Rect?>() private val overriddenMaximumBounds = mutableMapOf<Activity, Rect?>() /** * Overrides the bounds returned from this helper for the given context. Passing `null` [bounds] * has the effect of clearing the bounds override. * * Note: A global override set as a result of [.setCurrentBounds] takes precedence * over the value set with this method. */ fun setCurrentBoundsForActivity(activity: Activity, bounds: Rect?) { overriddenBounds[activity] = bounds } /** * Overrides the max bounds returned from this helper for the given context. Passing `null` * [bounds] has the effect of clearing the bounds override. */ fun setMaximumBoundsForActivity(activity: Activity, bounds: Rect?) { overriddenMaximumBounds[activity] = bounds } /** * Overrides the bounds returned from this helper for all supplied contexts. Passing null * [bounds] has the effect of clearing the global override. */ fun setCurrentBounds(bounds: Rect?) { globalOverriddenBounds = bounds } override fun computeCurrentWindowMetrics(activity: Activity): WindowMetrics { val bounds = globalOverriddenBounds ?: overriddenBounds[activity] ?: Rect() return WindowMetrics(bounds) } override fun computeMaximumWindowMetrics(activity: Activity): WindowMetrics { return WindowMetrics(overriddenMaximumBounds[activity] ?: Rect()) } /** * Clears any overrides set with [.setCurrentBounds] or * [.setCurrentBoundsForActivity]. */ fun reset() { globalOverriddenBounds = null overriddenBounds.clear() overriddenMaximumBounds.clear() } }
apache-2.0
60bd15410ae14327b3b74cc7fe6a628d
34.578947
100
0.710059
4.854578
false
false
false
false
pyamsoft/padlock
padlock/src/main/java/com/pyamsoft/padlock/list/info/LockInfoGroupViewImpl.kt
1
1950
/* * Copyright 2019 Peter Kenji Yamanaka * * 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.pyamsoft.padlock.list.info import android.graphics.drawable.ColorDrawable import android.view.View import androidx.core.content.ContextCompat import com.pyamsoft.padlock.R import com.pyamsoft.padlock.databinding.AdapterItemLockinfoGroupBinding import com.pyamsoft.padlock.model.list.ActivityEntry.Group import com.pyamsoft.pydroid.ui.theme.Theming import javax.inject.Inject internal class LockInfoGroupViewImpl @Inject internal constructor( itemView: View, theming: Theming ) : LockInfoGroupView { private val binding = AdapterItemLockinfoGroupBinding.bind(itemView) init { val color: Int if (theming.isDarkTheme()) { color = R.color.dark_lock_group_background } else { color = R.color.lock_group_background } binding.root.background = ColorDrawable(ContextCompat.getColor(itemView.context, color)) } override fun bind( model: Group, packageName: String ) { binding.apply { val text: String val modelName = model.name if (modelName != packageName && modelName.startsWith(packageName)) { text = modelName.replaceFirst(packageName, "") } else { text = modelName } lockInfoGroupName.text = text } } override fun unbind() { binding.apply { lockInfoGroupName.text = null unbind() } } }
apache-2.0
d91b673ad6c5a8067675a5b44e0885ee
26.857143
92
0.718974
4.220779
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/dfa/ControlFlowGraph.kt
2
9834
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.dfa import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.types.regions.ScopeTree import org.rust.lang.core.types.ty.TyNever import org.rust.lang.core.types.type import org.rust.lang.utils.Node import org.rust.lang.utils.PresentableGraph import org.rust.lang.utils.PresentableNodeData import org.rust.stdext.buildSet sealed class CFGNodeData(val element: RsElement? = null) : PresentableNodeData { /** Any execution unit (e.g. expression, statement) */ class AST(element: RsElement) : CFGNodeData(element) /** Execution start */ object Entry : CFGNodeData() /** Normal execution end (e.g. after `main` function block) */ object Exit : CFGNodeData() /** Any real (e.g. `panic!()` call) or imaginary (e.g. after infinite loop) execution end */ object Termination : CFGNodeData() /** Supplementary node to build complex control flow (e.g. loops and pattern matching) */ object Dummy : CFGNodeData() /** Start of any unreachable code (e.g. after `return`) */ object Unreachable : CFGNodeData() override val text: String get() = when (this) { is AST -> element!!.cfgText().trim() Entry -> "Entry" Exit -> "Exit" Termination -> "Termination" Dummy -> "Dummy" Unreachable -> "Unreachable" } private fun RsElement.cfgText(): String = when (this) { is RsBlock, is RsBlockExpr -> "BLOCK" is RsIfExpr -> "IF" is RsWhileExpr -> "WHILE" is RsLoopExpr -> "LOOP" is RsForExpr -> "FOR" is RsMatchExpr -> "MATCH" is RsLambdaExpr -> "CLOSURE" is RsExprStmt -> outerAttrList.joinToString(postfix = " ") { it.text } + expr.cfgText() + ";" else -> this.text } } class CFGEdgeData(val exitingScopes: List<RsElement>) typealias CFGNode = Node<CFGNodeData, CFGEdgeData> typealias CFGGraph = PresentableGraph<CFGNodeData, CFGEdgeData> /** * The control-flow graph we use is built on the top of the PSI tree. * We do not operate with basic blocks, and therefore each tiny execution unit is represented in the graph as a separate node. * * For illustration, consider the following program: * ``` * fn main() { * let x = 42; * } * ``` * The corresponding control-flow graph we build will consist of the following edges: * ``` * `Entry` -> `42` * `42` -> `x` * `x` -> `x` * `x` -> `let x = 42` * `let x = 42;` -> `BLOCK` * `BLOCK` -> `Exit` * `Exit` -> `Termination` * ``` * * You may see that the pattern bindings are duplicated here (`x` -> `x` edge). * This occurs because `x` nodes correspond to both `RsPatIdent` (parent) and `RsPatBinding` (child). * * Please refer to [org.rust.lang.core.dfa.RsControlFlowGraphTest] for more examples. */ class ControlFlowGraph private constructor( val owner: RsElement, val graph: CFGGraph, val body: RsBlock, val regionScopeTree: ScopeTree, val entry: CFGNode, val exit: CFGNode, val unreachableElements: Set<RsElement> ) { companion object { fun buildFor(body: RsBlock, regionScopeTree: ScopeTree): ControlFlowGraph { val owner = body.parent as RsElement val graph = PresentableGraph<CFGNodeData, CFGEdgeData>() val entry = graph.addNode(CFGNodeData.Entry) val fnExit = graph.addNode(CFGNodeData.Exit) val termination = graph.addNode(CFGNodeData.Termination) val cfgBuilder = CFGBuilder(regionScopeTree, graph, entry, fnExit, termination) val bodyExit = cfgBuilder.process(body, entry) cfgBuilder.addContainedEdge(bodyExit, fnExit) cfgBuilder.addContainedEdge(fnExit, termination) val unreachableElements = collectUnreachableElements(graph, entry) return ControlFlowGraph(owner, graph, body, regionScopeTree, entry, fnExit, unreachableElements) } /** * Collects unreachable elements, i.e. elements cannot be reached by execution of [body]. * * Only collects [RsExprStmt]s, [RsLetDecl]s and tail expressions, ignoring conditionally disabled. */ private fun collectUnreachableElements(graph: CFGGraph, entry: CFGNode): Set<RsElement> { /** * In terms of our control-flow graph, a [RsElement]'s node is not reachable if it cannot be fully executed, * since [CFGBuilder] processes elements in post-order. * But partially executed elements should not be treated as unreachable because the execution * actually reaches them; only some parts of such elements should be treated as unreachable instead. * * So, first of all, collect all the unexecuted [RsElement]s (including partially executed) */ val unexecutedElements = buildSet<RsElement> { val fullyExecutedNodeIndices = graph.depthFirstTraversal(entry).map { it.index }.toSet() graph.forEachNode { node -> if (node.index !in fullyExecutedNodeIndices) { val element = node.data.element ?: return@forEachNode add(element) } } } val unexecutedStmts = unexecutedElements .filterIsInstance<RsStmt>() val unexecutedTailExprs = unexecutedElements .filterIsInstance<RsBlock>() .mapNotNull { block -> block.expandedTailExpr?.takeIf { expr -> when (expr) { is RsMacroExpr -> expr.macroCall in unexecutedElements else -> expr in unexecutedElements } } } /** * If [unexecuted] produces termination by itself * (which means its inner expression type is [TyNever], see the corresponding checks below), * it should be treated as unreachable only if the execution does not reach the beginning of [unexecuted]. * The latter means that previous statement is not fully executed. * This is needed in order not to treat the first, basically reachable, `return` as unreachable */ fun isUnreachable(unexecuted: RsElement, innerExpr: RsExpr?): Boolean { // Ignore conditionally disabled elements if (!unexecuted.existsAfterExpansion) { return false } if (innerExpr != null && !innerExpr.existsAfterExpansion) { return false } // Unexecuted element is definitely unreachable if its inner expression does not produce termination if (innerExpr != null && innerExpr.type !is TyNever) { return true } // Otherwise, unexecuted element's child produces termination and therefore // we should check if it is really unreachable or just not fully executed val parentBlock = unexecuted.ancestorStrict<RsBlock>() ?: return false val blockStmts = parentBlock.stmtList.takeIf { it.isNotEmpty() } ?: return false val blockTailExpr = parentBlock.expandedTailExpr val index = blockStmts.indexOf(unexecuted) return when { index >= 1 -> { // `{ ... <unreachable>; <element>; ... }` blockStmts[index - 1] in unexecutedElements } unexecuted == blockTailExpr -> { // `{ ... <unreachable>; <element> }` blockStmts.last() in unexecutedElements } else -> false } } val unreachableElements = mutableSetOf<RsElement>() for (stmt in unexecutedStmts) { when { stmt is RsExprStmt && isUnreachable(stmt, stmt.expr) -> { unreachableElements.add(stmt) } stmt is RsLetDecl && isUnreachable(stmt, stmt.expr) -> { unreachableElements.add(stmt) } } } for (tailExpr in unexecutedTailExprs) { if (isUnreachable(tailExpr, tailExpr)) { unreachableElements.add(tailExpr) } } return unreachableElements } } fun buildLocalIndex(): HashMap<RsElement, MutableList<CFGNode>> { val table = hashMapOf<RsElement, MutableList<CFGNode>>() val func = body.parent if (func is RsFunction) { val formals = object : RsVisitor() { override fun visitPatBinding(binding: RsPatBinding) { table.getOrPut(binding, ::mutableListOf).add(entry) } override fun visitPatField(field: RsPatField) { field.acceptChildren(this) } override fun visitPat(pat: RsPat) { pat.acceptChildren(this) } } func.valueParameters.mapNotNull { it.pat }.forEach { formals.visitPat(it) } } graph.forEachNode { node -> val element = node.data.element if (element != null) table.getOrPut(element, ::mutableListOf).add(node) } return table } }
mit
a56a6aaa482f4b2cd2a5bfcccb55415a
38.653226
126
0.577283
4.71881
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/inspections/lints/RsUnusedImportInspection.kt
2
11043
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections.lints import com.intellij.codeInsight.daemon.HighlightDisplayKey import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel import com.intellij.openapi.project.Project import com.intellij.profile.codeInspection.InspectionProjectProfileManager import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.SearchScope import com.intellij.psi.search.UsageSearchContext import org.rust.ide.injected.isDoctestInjection import org.rust.ide.inspections.RsProblemsHolder import org.rust.ide.inspections.fixes.RemoveImportFix import org.rust.lang.core.crate.asNotFake import org.rust.lang.core.crate.impl.DoctestCrate import org.rust.lang.core.macros.findExpansionElements import org.rust.lang.core.macros.proc.ProcMacroApplicationService import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve2.* import org.rust.openapiext.isUnitTestMode import javax.swing.JComponent class RsUnusedImportInspection : RsLintInspection() { var ignoreDoctest: Boolean = true var enableOnlyIfProcMacrosEnabled: Boolean = true override fun getLint(element: PsiElement): RsLint = RsLint.UnusedImports override fun getShortName(): String = SHORT_NAME override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitUseItem(item: RsUseItem) { if (!isApplicableForUseItem(item)) return // It's common to include more imports than needed in doctest sample code if (ignoreDoctest && item.containingCrate is DoctestCrate) return if (enableOnlyIfProcMacrosEnabled && !ProcMacroApplicationService.isFullyEnabled() && !isUnitTestMode) return val owner = item.parent as? RsItemsOwner ?: return val usage = owner.pathUsage val speck = item.useSpeck ?: return val unusedSpeckSet = HashSet<RsUseSpeck>() storeUseSpeckUsage(speck, usage, unusedSpeckSet) markUnusedSpecks(speck, unusedSpeckSet, holder) } } /** * Traverse all use specks recursively and store information about their usage. */ private fun storeUseSpeckUsage( useSpeck: RsUseSpeck, usage: PathUsageMap, unusedSpeckSet: MutableSet<RsUseSpeck> ) { val group = useSpeck.useGroup val isUsed = if (group == null) { isUseSpeckUsed(useSpeck, usage) } else { group.useSpeckList.forEach { storeUseSpeckUsage(it, usage, unusedSpeckSet) } group.useSpeckList.any { it !in unusedSpeckSet } } if (!isUsed) { unusedSpeckSet.add(useSpeck) } } private fun markUnusedSpecks( useSpeck: RsUseSpeck, unusedSpeckSet: Set<RsUseSpeck>, holder: RsProblemsHolder ) { val used = useSpeck !in unusedSpeckSet if (!used) { markAsUnused(useSpeck, holder) } else { useSpeck.useGroup?.useSpeckList?.forEach { markUnusedSpecks(it, unusedSpeckSet, holder) } } } private fun markAsUnused(useSpeck: RsUseSpeck, holder: RsProblemsHolder) { val element = getHighlightElement(useSpeck) // https://github.com/intellij-rust/intellij-rust/issues/7565 val fixes = if (useSpeck.isDoctestInjection) emptyList() else listOf((RemoveImportFix(element))) holder.registerLintProblem( element, "Unused import: `${useSpeck.text}`", RsLintHighlightingType.UNUSED_SYMBOL, fixes ) } override fun createOptionsPanel(): JComponent = MultipleCheckboxOptionsPanel(this).apply { addCheckbox("Ignore unused imports in doctests", "ignoreDoctest") addCheckbox("Enable inspection only if procedural macros are enabled", "enableOnlyIfProcMacrosEnabled") } companion object { fun isEnabled(project: Project): Boolean { val profile = InspectionProjectProfileManager.getInstance(project).currentProfile return profile.isToolEnabled(HighlightDisplayKey.find(SHORT_NAME)) && checkProcMacrosMatch(profile, project) } private fun checkProcMacrosMatch(profile: InspectionProfileImpl, project: Project): Boolean { if (isUnitTestMode) return true val toolWrapper = profile.getInspectionTool(SHORT_NAME, project) val tool = toolWrapper?.tool as? RsUnusedImportInspection ?: return true if (!tool.enableOnlyIfProcMacrosEnabled) return true return ProcMacroApplicationService.isFullyEnabled() } const val SHORT_NAME: String = "RsUnusedImport" } } private fun getHighlightElement(useSpeck: RsUseSpeck): PsiElement { if (useSpeck.parent is RsUseItem) { return useSpeck.parent } return useSpeck } private fun isApplicableForUseItem(item: RsUseItem): Boolean { val crate = item.containingCrate if (item.visibility == RsVisibility.Public && crate.kind.isLib) return false if (!item.existsAfterExpansion(crate)) return false return true } /** * Returns true if this use speck has at least one usage in its containing owner (module or function). * A usage can be either a path that uses the import of the use speck or a method call/associated item available through * a trait that is imported by this use speck. */ fun RsUseSpeck.isUsed(pathUsage: PathUsageMap): Boolean { val useItem = ancestorStrict<RsUseItem>() ?: return true if (!isApplicableForUseItem(useItem)) return true return isUseSpeckUsed(this, pathUsage) } private fun isUseSpeckUsed(useSpeck: RsUseSpeck, usage: PathUsageMap): Boolean { if (useSpeck.path?.resolveStatus != PathResolveStatus.RESOLVED) return true val items = if (useSpeck.isStarImport) { val module = useSpeck.path?.reference?.resolve() as? RsMod ?: return true module.exportedItems(useSpeck.containingMod) } else { val path = useSpeck.path ?: return true val items = path.reference?.multiResolve() ?: return true val name = useSpeck.itemName(withAlias = true) ?: return true items.filterIsInstance<RsNamedElement>().map { NamedItem(name, it) } } return items.any { (importName, item) -> isItemUsedInSameMod(item, importName, usage) || isItemUsedInOtherMods(item, importName, useSpeck) } } private fun isItemUsedInSameMod(item: RsNamedElement, importName: String, usage: PathUsageMap): Boolean { val used = item in usage.pathUsages[importName].orEmpty() || item in usage.traitUsages val probablyUsed = importName in usage.unresolvedPaths || (item as? RsTraitItem)?.expandedMembers.orEmpty().any { it.name in usage.unresolvedMethods } return used || probablyUsed } private fun isItemUsedInOtherMods(item: RsNamedElement, importName: String, useSpeck: RsUseSpeck): Boolean { val useItem = useSpeck.ancestorStrict<RsUseItem>() ?: return true val importMod = useItem.containingMod val useItemVisibility = when (val visibility = useItem.visibility) { RsVisibility.Private -> { if (!importMod.hasChildModules) return false RsVisibility.Restricted(importMod) } is RsVisibility.Restricted -> visibility // we handle public imports in binary crates only, so this is effectively `pub(crate)` import RsVisibility.Public -> RsVisibility.Restricted(importMod.crateRoot ?: return true) } if (item is RsTraitItem) { // TODO we should search usages for all methods of the trait return true } val searchScope = RsPsiImplUtil.getDeclarationUseScope(useItem) return !item.processReferencesWithAliases(searchScope, importName) { element -> !isImportNeededForReference(element, useItemVisibility, importMod) } } private fun isImportNeededForReference( reference: RsReferenceElement, importVisibility: RsVisibility.Restricted, importMod: RsMod ): Boolean { if (reference.containingMod == importMod) { // References from same mod are already checked // Note that this check should be performed after `findExpansionElements` return false } if (importVisibility.inMod !in reference.containingMod.superMods) { // We should check references only from mods inside use item visibility scope return false } return when (reference) { is RsPath -> { val qualifier = reference.qualifier if (qualifier == null) { reference.containingMod.hasTransitiveGlobImportTo(importMod) } else { val qualifierTarget = qualifier.reference?.resolve() as? RsMod ?: return false qualifierTarget.hasTransitiveGlobImportTo(importMod) } } is RsPatBinding -> { reference.containingMod.hasTransitiveGlobImportTo(importMod) } else -> false } } private fun RsMod.hasTransitiveGlobImportTo(target: RsMod): Boolean { if (this == target) return true val crateId = containingCrate.asNotFake?.id ?: return false if (crateId != target.containingCrate.id) { // we consider `pub` imports as always used, // so any possible usage of import will be in same crate return false } val defMap = project.defMapService.getOrUpdateIfNeeded(crateId) ?: return false return defMap.hasTransitiveGlobImport(this, target) } /** * Like [RsElement.searchReferences], but takes into account reexports with aliases. * Returns `true` if [originalProcessor] returns `true` for all references */ fun RsElement.processReferencesWithAliases( searchScope: SearchScope?, identifier: String, originalProcessor: (RsReferenceElement) -> Boolean ): Boolean { // returning `false` stops the processing fun processor(element: PsiElement): Boolean { if (element !is RsReferenceElementBase || element.referenceName != identifier) return true element.findExpansionElements()?.let { expansionElements -> return expansionElements .mapNotNull { it.ancestorStrict<RsElement>() } // PsiElement(identifier) .all(::processor) } return if (element is RsReferenceElement && element.reference?.isReferenceTo(this) == true) { originalProcessor(element) } else { true } } return PsiSearchHelper.getInstance(project).processElementsWithWord( { element, _ -> processor(element) }, searchScope ?: GlobalSearchScope.allScope(project), identifier, UsageSearchContext.IN_CODE, true ) }
mit
fb84b3c54ad64b7c89278079ce136943
38.298932
121
0.690845
4.693158
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/formatter/RsAlignmentStrategy.kt
3
2966
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter import com.intellij.formatting.Alignment import com.intellij.lang.ASTNode import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet interface RsAlignmentStrategy { /** * Requests current strategy for alignment to use for given child. */ fun getAlignment(child: ASTNode, parent: ASTNode?, childCtx: RsFmtContext): Alignment? /** * Always returns `null`. */ object NullStrategy : RsAlignmentStrategy { override fun getAlignment(child: ASTNode, parent: ASTNode?, childCtx: RsFmtContext): Alignment? = null } /** * Apply this strategy only when child element is in [tt]. */ fun alignIf(vararg tt: IElementType): RsAlignmentStrategy = alignIf(TokenSet.create(*tt)) /** * Apply this strategy only when child element type matches [filterSet]. */ fun alignIf(filterSet: TokenSet): RsAlignmentStrategy = object : RsAlignmentStrategy { override fun getAlignment(child: ASTNode, parent: ASTNode?, childCtx: RsFmtContext): Alignment? = if (child.elementType in filterSet) { [email protected](child, parent, childCtx) } else { null } } /** * Apply this strategy only when [predicate] passes. */ fun alignIf(predicate: (child: ASTNode, parent: ASTNode?, ctx: RsFmtContext) -> Boolean): RsAlignmentStrategy = object : RsAlignmentStrategy { override fun getAlignment(child: ASTNode, parent: ASTNode?, childCtx: RsFmtContext): Alignment? = if (predicate(child, parent, childCtx)) { [email protected](child, parent, childCtx) } else { null } } /** * Returns [NullStrategy] if [condition] is `false`. Useful for making strategies configurable. */ fun alignIf(condition: Boolean): RsAlignmentStrategy = if (condition) { this } else { NullStrategy } companion object { /** * Always returns [alignment]. */ fun wrap(alignment: Alignment = Alignment.createAlignment()): RsAlignmentStrategy = object : RsAlignmentStrategy { override fun getAlignment(child: ASTNode, parent: ASTNode?, childCtx: RsFmtContext): Alignment = alignment } /** * Always returns [RsFmtContext.sharedAlignment] */ fun shared(): RsAlignmentStrategy = object : RsAlignmentStrategy { override fun getAlignment(child: ASTNode, parent: ASTNode?, childCtx: RsFmtContext): Alignment? = childCtx.sharedAlignment } } }
mit
01a14a639940b57fd2b4fe672e372f6c
33.488372
115
0.608901
5.185315
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/completion/LookupElements.kt
2
19983
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.completion import com.intellij.codeInsight.AutoPopupController import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.completion.PrioritizedLookupElement import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.EditorModificationUtil import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.rust.ide.icons.RsIcons import org.rust.ide.presentation.getStubOnlyText import org.rust.ide.refactoring.RsNamesValidator import org.rust.lang.core.completion.RsLookupElementProperties.KeywordKind import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve.* import org.rust.lang.core.resolve.ref.FieldResolveVariant import org.rust.lang.core.types.Substitution import org.rust.lang.core.types.emptySubstitution import org.rust.lang.core.types.infer.ExpectedType import org.rust.lang.core.types.infer.RsInferenceContext import org.rust.lang.core.types.infer.TypeFolder import org.rust.lang.core.types.normType import org.rust.lang.core.types.ty.* import org.rust.lang.core.types.type import org.rust.lang.doc.psi.RsDocPathLinkParent import org.rust.openapiext.Testmark import org.rust.stdext.mapToSet const val DEFAULT_PRIORITY = 0.0 interface CompletionEntity { fun retTy(items: KnownItems): Ty? fun getBaseLookupElementProperties(context: RsCompletionContext): RsLookupElementProperties fun createBaseLookupElement(context: RsCompletionContext): LookupElementBuilder } class ScopedBaseCompletionEntity(private val scopeEntry: ScopeEntry) : CompletionEntity { private val element = checkNotNull(scopeEntry.element) { "Invalid scope entry" } override fun retTy(items: KnownItems): Ty? = element.asTy(items) override fun getBaseLookupElementProperties(context: RsCompletionContext): RsLookupElementProperties { val isMethodSelfTypeIncompatible = element is RsFunction && element.isMethod && isMutableMethodOnConstReference(element, context.context) // It's visible and can't be exported = it's local val isLocal = context.isSimplePath && !element.canBeExported val elementKind = when { element is RsDocAndAttributeOwner && element.queryAttributes.deprecatedAttribute != null -> { RsLookupElementProperties.ElementKind.DEPRECATED } element is RsMacro -> RsLookupElementProperties.ElementKind.MACRO element is RsPatBinding -> RsLookupElementProperties.ElementKind.VARIABLE element is RsEnumVariant -> RsLookupElementProperties.ElementKind.ENUM_VARIANT element is RsFieldDecl -> RsLookupElementProperties.ElementKind.FIELD_DECL element is RsFunction && element.isAssocFn -> RsLookupElementProperties.ElementKind.ASSOC_FN else -> RsLookupElementProperties.ElementKind.DEFAULT } val isInherentImplMember = element is RsAbstractable && element.owner.isInherentImpl val isOperatorMethod = element is RsFunction && scopeEntry is AssocItemScopeEntryBase<*> && scopeEntry.source.implementedTrait?.element?.langAttribute in OPERATOR_TRAIT_LANG_ITEMS val isBlanketImplMember = if (scopeEntry is AssocItemScopeEntryBase<*>) { val source = scopeEntry.source source is TraitImplSource.ExplicitImpl && source.type is TyTypeParameter } else { false } return RsLookupElementProperties( isSelfTypeCompatible = !isMethodSelfTypeIncompatible, isLocal = isLocal, elementKind = elementKind, isInherentImplMember = isInherentImplMember, isOperatorMethod = isOperatorMethod, isBlanketImplMember = isBlanketImplMember, isUnsafeFn = element is RsFunction && element.isActuallyUnsafe, isAsyncFn = element is RsFunction && element.isAsync, isConstFnOrConst = element is RsFunction && element.isConst || element is RsConstant && element.isConst, isExternFn = element is RsFunction && element.isExtern, ) } override fun createBaseLookupElement(context: RsCompletionContext): LookupElementBuilder { val subst = context.lookup?.ctx?.getSubstitution(scopeEntry) ?: emptySubstitution return element.getLookupElementBuilder(scopeEntry.name, subst) } companion object { private val OPERATOR_TRAIT_LANG_ITEMS = OverloadableBinaryOperator.values().mapToSet { it.itemName } } } private fun isMutableMethodOnConstReference(method: RsFunction, call: RsElement?): Boolean { if (call == null) return false val self = method.selfParameter ?: return false if (!self.isRef || !self.mutability.isMut) return false // now we know that the method takes &mut self val fieldLookup = call as? RsFieldLookup ?: return false val expr = fieldLookup.receiver val isMutable = when (val type = expr.type) { is TyReference -> type.mutability.isMut else -> hasMutBinding(expr) } return !isMutable } private fun hasMutBinding(expr: RsExpr): Boolean { val pathExpr = expr as? RsPathExpr ?: return true val binding = pathExpr.path.reference?.resolve() as? RsPatBinding ?: return true return binding.mutability.isMut } fun createLookupElement( scopeEntry: ScopeEntry, context: RsCompletionContext, locationString: String? = null, insertHandler: InsertHandler<LookupElement> = RsDefaultInsertHandler() ): LookupElement { val completionEntity = ScopedBaseCompletionEntity(scopeEntry) return createLookupElement(completionEntity, context, locationString, insertHandler) } fun createLookupElement( completionEntity: CompletionEntity, context: RsCompletionContext, locationString: String? = null, insertHandler: InsertHandler<LookupElement> = RsDefaultInsertHandler() ): LookupElement { val lookup = completionEntity.createBaseLookupElement(context) .withInsertHandler(insertHandler) .let { if (locationString != null) it.appendTailText(" ($locationString)", true) else it } val implLookup = context.lookup val isCompatibleTypes = implLookup != null && isCompatibleTypes(implLookup, completionEntity.retTy(implLookup.items), context.expectedTy) val properties = completionEntity.getBaseLookupElementProperties(context) .copy(isReturnTypeConformsToExpectedType = isCompatibleTypes) return lookup.toRsLookupElement(properties) } private fun RsInferenceContext.getSubstitution(scopeEntry: ScopeEntry): Substitution = when (scopeEntry) { is AssocItemScopeEntryBase<*> -> instantiateMethodOwnerSubstitution(scopeEntry) .mapTypeValues { (_, v) -> resolveTypeVarsIfPossible(v) } .mapConstValues { (_, v) -> resolveTypeVarsIfPossible(v) } is FieldResolveVariant -> scopeEntry.selfTy.typeParameterValues else -> emptySubstitution } private fun RsElement.asTy(items: KnownItems): Ty? = when (this) { is RsConstant -> typeReference?.normType is RsConstParameter -> typeReference?.normType is RsFieldDecl -> typeReference?.normType is RsFunction -> retType?.typeReference?.normType is RsStructItem -> declaredType is RsEnumVariant -> parentEnum.declaredType is RsPatBinding -> type is RsMacroDefinitionBase -> KnownMacro.of(this)?.retTy(items) else -> null } fun LookupElementBuilder.withPriority(priority: Double): LookupElement = if (priority == DEFAULT_PRIORITY) this else PrioritizedLookupElement.withPriority(this, priority) fun LookupElementBuilder.toRsLookupElement(properties: RsLookupElementProperties): LookupElement { return RsLookupElement(this, properties) } fun LookupElementBuilder.toKeywordElement(keywordKind: KeywordKind = KeywordKind.KEYWORD): LookupElement = toRsLookupElement(RsLookupElementProperties(keywordKind = keywordKind)) private fun RsElement.getLookupElementBuilder(scopeName: String, subst: Substitution): LookupElementBuilder { val isProcMacroDef = this is RsFunction && isProcMacroDef val base = LookupElementBuilder.createWithSmartPointer(scopeName, this) .withIcon(if (this is RsFile) RsIcons.MODULE else this.getIcon(0)) .withStrikeoutness(this is RsDocAndAttributeOwner && queryAttributes.deprecatedAttribute != null) return when (this) { is RsMod -> if (scopeName == "self" || scopeName == "super" || scopeName == "crate") { base.withTailText("::") } else { base } is RsConstant -> base .withTypeText(typeReference?.getStubOnlyText(subst)) is RsConstParameter -> base .withTypeText(typeReference?.getStubOnlyText(subst)) is RsFieldDecl -> base .bold() .withTypeText(typeReference?.getStubOnlyText(subst)) is RsTraitItem -> base is RsFunction -> when { !isProcMacroDef -> base .withTypeText(retType?.typeReference?.getStubOnlyText(subst) ?: "()") .withTailText(valueParameterList?.getStubOnlyText(subst) ?: "()") .appendTailText(getExtraTailText(subst), true) isBangProcMacroDef -> base .withTailText("!") else -> base // attr proc macro } is RsStructItem -> base .withTailText(getFieldsOwnerTailText(this, subst)) is RsEnumVariant -> base .withTypeText(stubAncestorStrict<RsEnumItem>()?.name ?: "") .withTailText(getFieldsOwnerTailText(this, subst)) is RsPatBinding -> base .withTypeText(type.let { when (it) { is TyUnknown -> "" else -> it.toString() } }) is RsMacroBinding -> base.withTypeText(fragmentSpecifier) is RsMacroDefinitionBase -> base.withTailText("!") else -> base } } private fun getFieldsOwnerTailText(owner: RsFieldsOwner, subst: Substitution): String = when { owner.blockFields != null -> " { ... }" owner.tupleFields != null -> owner.positionalFields.joinToString(prefix = "(", postfix = ")") { it.typeReference.getStubOnlyText(subst) } else -> "" } open class RsDefaultInsertHandler : InsertHandler<LookupElement> { final override fun handleInsert(context: InsertionContext, item: LookupElement) { val element = item.psiElement as? RsElement ?: return val scopeName = item.lookupString handleInsert(element, scopeName, context, item) } protected open fun handleInsert( element: RsElement, scopeName: String, context: InsertionContext, item: LookupElement ) { val document = context.document if (element is RsNameIdentifierOwner && !RsNamesValidator.isIdentifier(scopeName) && scopeName !in CAN_NOT_BE_ESCAPED) { document.insertString(context.startOffset, RS_RAW_PREFIX) context.commitDocument() // Fixed PSI element escape } if (element is RsGenericDeclaration) { addGenericTypeCompletion(element, document, context) } if (context.getElementOfType<RsDocPathLinkParent>() != null) return val curUseItem = context.getElementOfType<RsUseItem>() when (element) { is RsMod -> { when (scopeName) { "self", "super" -> { val inSelfParam = context.getElementOfType<RsSelfParameter>() != null if (!(context.isInUseGroup || inSelfParam)) { context.addSuffix("::") } } "crate" -> context.addSuffix("::") } } is RsConstant -> appendSemicolon(context, curUseItem) is RsTraitItem -> appendSemicolon(context, curUseItem) is RsStructItem -> appendSemicolon(context, curUseItem) is RsFunction -> when { curUseItem != null -> { appendSemicolon(context, curUseItem) } element.isProcMacroDef -> { if (element.isBangProcMacroDef) { appendMacroBraces(context, document) { element.preferredBraces } } } else -> { val isMethodCall = context.getElementOfType<RsMethodOrField>() != null if (!context.alreadyHasCallParens) { document.insertString(context.selectionEndOffset, "()") context.doNotAddOpenParenCompletionChar() } val caretShift = if (element.valueParameters.isEmpty() && (isMethodCall || !element.hasSelfParameters)) 2 else 1 EditorModificationUtil.moveCaretRelatively(context.editor, caretShift) if (element.valueParameters.isNotEmpty()) { AutoPopupController.getInstance(element.project)?.autoPopupParameterInfo(context.editor, element) } } } is RsEnumVariant -> { if (curUseItem == null) { // Currently this works only for enum variants (and not for structs). It's because in the case of // struct you may want to append an associated function call after a struct name (e.g. `::new()`) val (text, shift) = when { element.tupleFields != null -> { context.doNotAddOpenParenCompletionChar() Pair("()", 1) } element.blockFields != null -> Pair(" {}", 2) else -> Pair("", 0) } if (!(context.alreadyHasStructBraces || context.alreadyHasCallParens)) { document.insertString(context.selectionEndOffset, text) } EditorModificationUtil.moveCaretRelatively(context.editor, shift) } } is RsMacroDefinitionBase -> { if (curUseItem == null) { appendMacroBraces(context, document) { element.preferredBraces } } else { appendSemicolon(context, curUseItem) } } } } private fun appendMacroBraces(context: InsertionContext, document: Document, getBraces: () -> MacroBraces) { var caretShift = 2 if (!context.nextCharIs('!')) { val braces = getBraces() val text = buildString { append("!") if (braces == MacroBraces.BRACES) { append(" ") caretShift = 3 } append(braces.openText) append(braces.closeText) } document.insertString(context.selectionEndOffset, text) } EditorModificationUtil.moveCaretRelatively(context.editor, caretShift) } } private fun appendSemicolon(context: InsertionContext, curUseItem: RsUseItem?) { if (curUseItem != null) { val hasSemicolon = curUseItem.lastChild!!.elementType == RsElementTypes.SEMICOLON if (!(hasSemicolon || context.isInUseGroup)) { context.addSuffix(";") } } } private fun addGenericTypeCompletion(element: RsGenericDeclaration, document: Document, context: InsertionContext) { // complete only types that have at least one generic parameter without a default if (element.typeParameters.all { it.typeReference != null } && element.constParameters.all { it.expr != null }) return // complete angle brackets only in a type context val path = context.getElementOfType<RsPath>() if (path == null || path.parent !is RsTypeReference) return if (element.isFnLikeTrait) { if (!context.alreadyHasCallParens) { document.insertString(context.selectionEndOffset, "()") context.doNotAddOpenParenCompletionChar() } } else { if (!context.alreadyHasAngleBrackets) { document.insertString(context.selectionEndOffset, "<>") } } EditorModificationUtil.moveCaretRelatively(context.editor, 1) } // When a user types `(` while completion, // `com.intellij.codeInsight.completion.DefaultCharFilter` invokes completion with selected item. // And if we insert `()` for the item (for example, function), a user get double parentheses private fun InsertionContext.doNotAddOpenParenCompletionChar() { if (completionChar == '(') { setAddCompletionChar(false) Testmarks.DoNotAddOpenParenCompletionChar.hit() } } inline fun <reified T : PsiElement> InsertionContext.getElementOfType(strict: Boolean = false): T? = PsiTreeUtil.findElementOfClassAtOffset(file, tailOffset - 1, T::class.java, strict) private val InsertionContext.isInUseGroup: Boolean get() = getElementOfType<RsUseGroup>() != null val InsertionContext.alreadyHasCallParens: Boolean get() = nextCharIs('(') private val InsertionContext.alreadyHasAngleBrackets: Boolean get() = nextCharIs('<') private val InsertionContext.alreadyHasStructBraces: Boolean get() = nextCharIs('{') val RsElement.isFnLikeTrait: Boolean get() { val knownItems = knownItems return this == knownItems.Fn || this == knownItems.FnMut || this == knownItems.FnOnce } private fun RsFunction.getExtraTailText(subst: Substitution): String { val traitRef = stubAncestorStrict<RsImplItem>()?.traitRef ?: return "" return " of ${traitRef.getStubOnlyText(subst)}" } fun InsertionContext.nextCharIs(c: Char): Boolean = document.charsSequence.indexOfSkippingSpace(c, tailOffset) != null private fun CharSequence.indexOfSkippingSpace(c: Char, startIndex: Int): Int? { for (i in startIndex until this.length) { val currentChar = this[i] if (c == currentChar) return i if (currentChar != ' ' && currentChar != '\t') return null } return null } private val RsElement.canBeExported: Boolean get() { if (this is RsEnumVariant) return true val context = PsiTreeUtil.getContextOfType(this, true, RsItemElement::class.java, RsFile::class.java) return context == null || context is RsMod } private fun isCompatibleTypes(lookup: ImplLookup, actualTy: Ty?, expectedType: ExpectedType?): Boolean { if (actualTy == null || expectedType == null) return false val expectedTy = expectedType.ty if ( actualTy is TyUnknown || expectedTy is TyUnknown || actualTy is TyNever || expectedTy is TyNever || actualTy is TyTypeParameter || expectedTy is TyTypeParameter ) return false // Replace `TyUnknown` and `TyTypeParameter` with `TyNever` to ignore them when combining types val folder = object : TypeFolder { override fun foldTy(ty: Ty): Ty = when (ty) { is TyUnknown -> TyNever is TyTypeParameter -> TyNever else -> ty.superFoldWith(this) } } // TODO coerce val ty1 = actualTy.foldWith(folder) val ty2 = expectedTy.foldWith(folder) return if (expectedType.coercable) { lookup.ctx.tryCoerce(ty1, ty2) } else { lookup.ctx.combineTypesNoVars(ty1, ty2) }.isOk } object Testmarks { object DoNotAddOpenParenCompletionChar : Testmark() }
mit
f47d39e6323d1bf33b5b75a73f3a5ee8
39.451417
132
0.65896
4.974608
false
false
false
false
arcuri82/testing_security_development_enterprise_systems
advanced/rest/pagination-offset/src/main/kotlin/org/tsdes/advanced/rest/pagination/DtoTransformer.kt
1
2177
package org.tsdes.advanced.rest.pagination import org.springframework.web.util.UriComponentsBuilder import org.tsdes.advanced.rest.pagination.dto.hal.PageDto import org.tsdes.advanced.rest.pagination.dto.CommentDto import org.tsdes.advanced.rest.pagination.dto.NewsDto import org.tsdes.advanced.rest.pagination.dto.VoteDto import org.tsdes.advanced.rest.pagination.entity.Comment import org.tsdes.advanced.rest.pagination.entity.News import org.tsdes.advanced.rest.pagination.entity.Vote object DtoTransformer { fun transform(vote: Vote): VoteDto { return VoteDto(vote.id.toString(), vote.user) } fun transform(comment: Comment): CommentDto { return CommentDto(comment.id.toString(), comment.text) } fun transform(news: News, withComments: Boolean, withVotes: Boolean): NewsDto { val dto = NewsDto(news.id.toString(), news.text, news.country) if (withComments) { news.comments.stream() .map { transform(it) } .forEach { dto.comments.add(it) } } if (withVotes) { news.votes.stream() .map { transform(it) } .forEach { dto.votes.add(it) } } return dto } /** * This creates a HAL dto, but with the links (self, next, previous) * that still have to be set */ fun transform(newsList: List<News>, offset: Int, limit: Int, onDb: Long, maxFromDb: Int, withComments: Boolean, withVotes: Boolean, baseUri: UriComponentsBuilder): PageDto<NewsDto> { val dtoList: MutableList<NewsDto> = newsList .map { transform(it, withComments, withVotes) } .toMutableList() return PageDto.withLinksBasedOnOffsetAndLimitParameters( list = dtoList, rangeMin = offset, rangeMax = offset + limit - 1, onDb = onDb, maxFromDb = maxFromDb, baseUri = baseUri ) } }
lgpl-3.0
d28ae314de3a960d9aab0f0618e1c2e7
29.25
72
0.578319
4.371486
false
false
false
false
Guardiola31337/uiagesturegen
uiagesturegen/src/androidTest/kotlin/com/pguardiola/uiagesturegen/RotateTest.kt
1
6331
/* * Copyright (C) 2017 Pablo Guardiola Sánchez. * * 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.pguardiola.uiagesturegen import android.content.Intent import android.content.pm.PackageManager import android.graphics.Point import android.support.test.InstrumentationRegistry import android.support.test.uiautomator.* import android.view.MotionEvent import org.hamcrest.CoreMatchers import org.hamcrest.CoreMatchers.notNullValue import org.junit.Assert.assertThat import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test class RotateTest { companion object { private val BASIC_SAMPLE_PACKAGE = "com.pguardiola.uiagesturegen" private val LAUNCH_TIMEOUT = 5000 } lateinit private var device: UiDevice @Before fun startMainActivityFromHomeScreen() { // Initialize UiDevice instance device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) // Start from the home screen device.pressHome() // Wait for launcher val launcherPackage = obtainLauncherPackageName() assertThat(launcherPackage, CoreMatchers.notNullValue()) device.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT.toLong()) // Launch the blueprint app val context = InstrumentationRegistry.getContext() val intent = context.packageManager.getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) // Clear out any previous instances context.startActivity(intent) // Wait for the app to appear device.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT.toLong()) } @Test fun checksPreconditions() { assertThat(device, notNullValue()) try { val mapViewSelector = UiSelector().description("map view container") val mapView = device.findObject(mapViewSelector) val firstPointer = obtainFromZeroToOneHundredAndEightyCircleCoordinates(200, mapView.bounds.centerX(), mapView.bounds.centerY()) val secondPointer = obtainFromOneHundredAndEightyToZeroCircleCoordinates(200, mapView.bounds.centerX(), mapView.bounds.centerY()) // TODO Not working properly assertTrue(mapView.performMultiPointerGesture(firstPointer, secondPointer)) } catch (e: UiObjectNotFoundException) { e.printStackTrace() } } private fun obtainLauncherPackageName(): String { // Create launcher Intent val intent = Intent(Intent.ACTION_MAIN) intent.addCategory(Intent.CATEGORY_HOME) // Use PackageManager to get the launcher package name val pm = InstrumentationRegistry.getContext().packageManager val resolveInfo = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) return resolveInfo.activityInfo.packageName } private fun obtainFromZeroToOneHundredAndEightyCircleCoordinates(radius: Int, xc: Int, yc: Int): Array<MotionEvent.PointerCoords?> { // Variation angle var theta = Math.toRadians(0.0) // Initial point var x = radius var y = 0 val pointer = arrayOfNulls<MotionEvent.PointerCoords>(73) var i = 0 // While angle less than 360 degrees while (theta <= Math.PI) { addPoint(x + xc, y + yc, i, pointer) // Increase angle by 5 degrees theta = theta + Math.toRadians(2.5) // Obtain x and y parametric values val xd = radius * Math.cos(theta) x = Math.round(xd).toInt() val yd = radius * Math.sin(theta) y = yd.toInt() i++ } return pointer } private fun obtainFromOneHundredAndEightyToZeroCircleCoordinates(radius: Int, xc: Int, yc: Int): Array<MotionEvent.PointerCoords?> { // Variation angle var theta = Math.toRadians(180.0) // Initial point var x = -radius var y = 0 val pointer = arrayOfNulls<MotionEvent.PointerCoords>(73) var i = 0 // While angle less than 360 degrees while (theta <= 2 * Math.PI) { addPoint(x + xc, y + yc, i, pointer) // Increase angle by 5 degrees theta = theta + Math.toRadians(2.5) // Obtain x and y parametric values val xd = radius * Math.cos(theta) x = Math.round(xd).toInt() val yd = radius * Math.sin(theta) y = yd.toInt() i++ } return pointer } private fun obtainPolarCircleCoordinates(radius: Int, xc: Int, yc: Int): Array<MotionEvent.PointerCoords?> { // Variation angle var theta = Math.toRadians(0.0) // Initial point var x = radius var y = 0 val pointer = arrayOfNulls<MotionEvent.PointerCoords>(73) var i = 0 // While angle less than 360 degrees while (theta <= 2 * Math.PI) { addPoint(x + xc, y + yc, i, pointer) // Increase angle by 5 degrees theta = theta + Math.toRadians(5.0) // Obtain x and y parametric values val xd = radius * Math.cos(theta) x = Math.round(xd).toInt() val yd = radius * Math.sin(theta) y = yd.toInt() i++ } return pointer } private fun addPoint(x: Int, y: Int, counter: Int, pointer: Array<MotionEvent.PointerCoords?>) { val point = MotionEvent.PointerCoords() point.x = x.toFloat() point.y = y.toFloat() point.pressure = 1f point.size = 1f pointer[counter] = point } }
apache-2.0
380885c25fa0f448329564375065172c
36.017544
136
0.635071
4.514979
false
false
false
false
petropavel13/2photo-android
TwoPhoto/app/src/main/java/com/github/petropavel13/twophoto/extensions/PostPersistentStore.kt
1
8112
package com.github.petropavel13.twophoto.extensions import android.content.Context import android.database.sqlite.SQLiteException import android.net.Uri import android.os.Environment import com.facebook.common.executors.CallerThreadExecutor import com.facebook.common.references.CloseableReference import com.facebook.datasource.BaseDataSubscriber import com.facebook.datasource.DataSource import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.imagepipeline.memory.PooledByteBuffer import com.facebook.imagepipeline.request.ImageRequest import com.github.petropavel13.twophoto.db.DatabaseOpenHelper import com.github.petropavel13.twophoto.model.PostArtist import com.github.petropavel13.twophoto.model.PostCategory import com.github.petropavel13.twophoto.model.PostDetail import com.github.petropavel13.twophoto.model.PostTag import com.j256.ormlite.misc.TransactionManager import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException /** * Created by petropavel on 11/06/15. */ @Throws(SQLiteException::class) fun PostDetail.createInDatabase(dbHelper: DatabaseOpenHelper) { val post = this TransactionManager.callInTransaction(dbHelper.connectionSource, { with(dbHelper.tagsDao()) { tags.forEach { createIfNotExists(it) } } with(dbHelper.categoriesDao()) { categories.forEach { createIfNotExists(it) } } with(dbHelper.artistsDao()) { artists.forEach { createIfNotExists(it) } } dbHelper.authorsDao().createIfNotExists(author) dbHelper.postsDao().create(post) with(dbHelper.entriesDao()) { entries.forEach { it.dbPost = post create(it) } } with(dbHelper.commentsDao()) { comments.forEach { it.dbPost = post it.saveInDatabase(dbHelper, comments) } } with(dbHelper.postTagsDao()) { tags.forEach { create(PostTag(post, it)) } } with(dbHelper.postCategoryDao()) { categories.forEach { create(PostCategory(post, it)) } } with(dbHelper.postArtistDao()) { artists.forEach { create(PostArtist(post, it)) } } }) } class ImageSaver(val imageFile: File): BaseDataSubscriber<CloseableReference<PooledByteBuffer>>() { var exception: Throwable? = null private set companion object { private val MAX_BUFFER_SIZE = 1024 * 128 // 128 KB } override fun onFailureImpl(dataSource: DataSource<CloseableReference<PooledByteBuffer>>) { exception = dataSource.failureCause } override fun onNewResultImpl(dataSource: DataSource<CloseableReference<PooledByteBuffer>>) { if (dataSource.isFinished) { if(dataSource.hasResult()) { val imageReference = dataSource.result var fos: FileOutputStream? = null try { val image = imageReference.get() val total = image.size() val realBufferSize = if(total < MAX_BUFFER_SIZE) total else MAX_BUFFER_SIZE var bytesForRead = realBufferSize val ba = ByteArray(realBufferSize) fos = FileOutputStream(imageFile) var offset = 0 while(bytesForRead > 0) { image.read(offset, ba, 0, bytesForRead) fos.write(ba, 0, bytesForRead) offset += realBufferSize val estimated = total - offset bytesForRead = if(estimated > realBufferSize) realBufferSize else estimated } } catch(fnfe: FileNotFoundException) { exception = fnfe } catch(ioe: IOException) { exception = ioe } finally { fos?.close() imageReference.close() } } } } } private fun PostDetail.postFolderPath(ctx: Context) = ctx.getExternalFilesDir(null).path + "/post_${id}" //throws(PostSaveException::class) fun PostDetail.savePostImages(ctx: Context) { when(Environment.getExternalStorageState()) { Environment.MEDIA_MOUNTED -> { val postFolder = File(postFolderPath(ctx)) if(postFolder.exists() == false) { if(postFolder.mkdir() == false) { // throw PostSaveException("Failed to create post directory in ${postFolder.path}") } } with(Fresco.getImagePipeline()) { val faceImageUri = Uri.parse(face_image_url) val faceImageFile = File(postFolder, faceImageUri.lastPathSegment) if (faceImageFile.exists()) { if (faceImageFile.delete() == false) { // throw } } val faceImageSaver = ImageSaver(faceImageFile) fetchEncodedImage(ImageRequest.fromUri(faceImageUri), null) .subscribe(faceImageSaver, CallerThreadExecutor.getInstance()) if (faceImageSaver.exception != null) { // throw } face_image_url = faceImageFile.toURI().toURL().toString() entries.forEach { val mediumUri = Uri.parse(it.medium_img_url) val bigUri = Uri.parse(it.big_img_url) val mediumImageFile = File(postFolder, mediumUri.lastPathSegment) val bigImageFile = File(postFolder, bigUri.lastPathSegment) if (mediumImageFile.exists()) { if (mediumImageFile.delete() == false) { // throw } } if (bigImageFile.exists()) { if (bigImageFile.delete() == false) { // throw } } val mediumSaver = ImageSaver(mediumImageFile) val bigSaver = ImageSaver(bigImageFile) fetchEncodedImage(ImageRequest.fromUri(mediumUri), null) .subscribe(mediumSaver, CallerThreadExecutor.getInstance()) fetchEncodedImage(ImageRequest.fromUri(bigUri), null) .subscribe(bigSaver, CallerThreadExecutor.getInstance()) if (mediumSaver.exception != null) { // throw } it.medium_img_url = mediumImageFile.toURI().toURL().toString() if (bigSaver.exception != null) { // throw } it.big_img_url = bigImageFile.toURI().toURL().toString() } } } else -> { // throw } } } @Throws(SQLiteException::class) fun PostDetail.deleteFromDatabase(dbHelper: DatabaseOpenHelper) { TransactionManager.callInTransaction(dbHelper.connectionSource, { dbHelper.postArtistDao().deleteIds(artists.map { it.id }) dbHelper.postCategoryDao().deleteIds(categories.map { it.id }) dbHelper.postTagsDao().deleteIds(tags.map { it.id }) if(dbComments != null) { dbHelper.commentsDao().deleteIds(dbComments!!.map { it.id }) } dbHelper.postsDao().delete(this) }) } fun PostDetail.deletePostImages(ctx: Context) { when(Environment.getExternalStorageState()) { Environment.MEDIA_MOUNTED -> { val postFolder = File(postFolderPath(ctx)) if(postFolder.exists()) { if(postFolder.deleteRecursively() == false) { // throw } } } else -> { // throw } } }
mit
7f8695337dcc0271f24fe22203bb1f86
31.067194
104
0.563979
5.066833
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/jobs/FetchRemoteMegaphoneImageJob.kt
1
2646
package org.thoughtcrime.securesms.jobs import okhttp3.ResponseBody import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.jobmanager.Data import org.thoughtcrime.securesms.jobmanager.Job import org.thoughtcrime.securesms.jobmanager.impl.AutoDownloadEmojiConstraint import org.thoughtcrime.securesms.providers.BlobProvider import org.thoughtcrime.securesms.s3.S3 import org.thoughtcrime.securesms.transport.RetryLaterException import java.io.IOException import java.util.concurrent.TimeUnit /** * Fetch an image associated with a remote megaphone. */ class FetchRemoteMegaphoneImageJob(parameters: Parameters, private val uuid: String, private val imageUrl: String) : BaseJob(parameters) { constructor(uuid: String, imageUrl: String) : this( parameters = Parameters.Builder() .setQueue(KEY) .addConstraint(AutoDownloadEmojiConstraint.KEY) .setMaxAttempts(Parameters.UNLIMITED) .setLifespan(TimeUnit.DAYS.toMillis(7)) .build(), uuid = uuid, imageUrl = imageUrl ) override fun serialize(): Data { return Data.Builder() .putString(KEY_UUID, uuid) .putString(KEY_IMAGE_URL, imageUrl) .build() } override fun getFactoryKey(): String { return KEY } override fun onRun() { try { S3.getObject(imageUrl).use { response -> val body: ResponseBody? = response.body() if (body != null) { val uri = BlobProvider.getInstance() .forData(body.byteStream(), body.contentLength()) .createForMultipleSessionsOnDisk(context) SignalDatabase.remoteMegaphones.setImageUri(uuid, uri) } } } catch (e: IOException) { Log.i(TAG, "Encountered unknown IO error while fetching image for $uuid", e) throw RetryLaterException(e) } } override fun onShouldRetry(e: Exception): Boolean = e is RetryLaterException override fun onFailure() { Log.i(TAG, "Failed to fetch image for $uuid, clearing to present without one") SignalDatabase.remoteMegaphones.clearImageUrl(uuid) } class Factory : Job.Factory<FetchRemoteMegaphoneImageJob> { override fun create(parameters: Parameters, data: Data): FetchRemoteMegaphoneImageJob { return FetchRemoteMegaphoneImageJob(parameters, data.getString(KEY_UUID), data.getString(KEY_IMAGE_URL)) } } companion object { const val KEY = "FetchRemoteMegaphoneImageJob" private val TAG = Log.tag(FetchRemoteMegaphoneImageJob::class.java) private const val KEY_UUID = "uuid" private const val KEY_IMAGE_URL = "image_url" } }
gpl-3.0
73364ab7ac61420f13b1f7a55558954f
31.666667
138
0.72449
4.064516
false
false
false
false
eyesniper2/skRayFall
src/main/java/net/rayfall/eyesniper2/skrayfall/effectlibsupport/EffEffectLibText.kt
1
3437
package net.rayfall.eyesniper2.skrayfall.effectlibsupport import ch.njol.skript.Skript import ch.njol.skript.doc.Description import ch.njol.skript.doc.Examples import ch.njol.skript.doc.Name import ch.njol.skript.lang.Effect import ch.njol.skript.lang.Expression import ch.njol.skript.lang.SkriptParser import ch.njol.skript.util.VisualEffect import ch.njol.util.Kleenean import de.slikey.effectlib.effect.TextEffect import de.slikey.effectlib.util.DynamicLocation import net.rayfall.eyesniper2.skrayfall.Core import org.bukkit.Location import org.bukkit.Particle import org.bukkit.entity.Entity import org.bukkit.event.Event @Name("Text Effect") @Description("Creates an EffectLib text effect.") @Examples("command /texteffect:", "\ttrigger:", "\t\tapply the text effect with text \"Text Effect\" as Redstone to player with id \"texteffecttest\"") class EffEffectLibText : Effect() { // create a text (effect|formation) with text %string% as %visualeffects% (at|on|for) %% with // id %string% [and %number% large] private var targetExpression: Expression<*>? = null private var textExpression: Expression<String>? = null private var particleExpression: Expression<VisualEffect>? = null private var idExpression: Expression<String>? = null private var sizeExpression: Expression<Number?>? = null @Suppress("UNCHECKED_CAST") override fun init(exp: Array<Expression<*>?>, arg1: Int, arg2: Kleenean, arg3: SkriptParser.ParseResult): Boolean { textExpression = exp[0] as Expression<String>? particleExpression = exp[1] as Expression<VisualEffect>? targetExpression = exp[2] idExpression = exp[3] as Expression<String>? sizeExpression = exp[4] as Expression<Number?>? return true } override fun toString(arg0: Event?, arg1: Boolean): String { return "" } override fun execute(evt: Event) { val target = targetExpression?.getSingle(evt) val text = textExpression?.getSingle(evt) val id = idExpression?.getSingle(evt) val particle = EffectLibUtils.getParticleFromVisualEffect(particleExpression?.getSingle(evt)) val size = sizeExpression?.getSingle(evt) val baseEffect = TextEffect(Core.effectManager) if (id == null) { Skript.warning("Id was null for EffectLib Text") return } when (target) { is Entity -> { baseEffect.setDynamicOrigin(DynamicLocation(target as Entity?)) } is Location -> { baseEffect.setDynamicOrigin(DynamicLocation(target as Location?)) } else -> { assert(false) } } if (particle != null) { baseEffect.particle = particle } else { Skript.warning("Particle was null for Effect Lib Text") return } if (text != null) { baseEffect.text = text } else { Skript.warning("Text was null for Effect Lib Text") return } if (size != null) { baseEffect.size = size.toFloat() } baseEffect.infinite() baseEffect.start() val setEffectSuccess = Core.rayfallEffectManager.setEffect(baseEffect, id.replace("\"", "")) if (!setEffectSuccess) { baseEffect.cancel() } } }
gpl-3.0
9b55c58f1281d52165b19e1ef29dcc22
32.378641
119
0.641548
4.248455
false
false
false
false
vincentvalenlee/nineshop
src/main/kotlin/org/open/openstore/file/internal/selector/Selectors.kt
1
1002
package org.open.openstore.file.internal.selector import org.open.openstore.file.FileSelector import org.open.openstore.file.FileType /** * 默认的选择器集 */ object Selectors { /** * 只选择自身的选择器 */ val SELECT_SELF: FileSelector = FileDepthSelector() /** * 选择自身以及一级子对象 */ val SELECT_SELF_AND_CHILDREN: FileSelector = FileDepthSelector(0, 1) /** * 选择一级子对象 */ val SELECT_CHILDREN: FileSelector = FileDepthSelector(1) /** * 选择所有的子对象,但不包括自己 */ val EXCLUDE_SELF: FileSelector = FileDepthSelector(1, Integer.MAX_VALUE) /** * 只选择文件 */ val SELECT_FILES: FileSelector = FileTypeSelector(FileType.FILE) /** * 只选择文件夹 */ val SELECT_FOLDERS: FileSelector = FileTypeSelector(FileType.FOLDER) /** * 所有的选择器 */ val SELECT_ALL: FileSelector = AllFileSelector() }
gpl-3.0
736ba91dbdb9e82bafeb77612d0b1636
18.795455
76
0.631034
3.425197
false
false
false
false
androidx/androidx
buildSrc/private/src/main/kotlin/androidx/build/AndroidXImplPlugin.kt
3
46571
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build import androidx.benchmark.gradle.BenchmarkPlugin import androidx.build.AndroidXImplPlugin.Companion.TASK_TIMEOUT_MINUTES import androidx.build.Release.DEFAULT_PUBLISH_CONFIG import androidx.build.SupportConfig.BUILD_TOOLS_VERSION import androidx.build.SupportConfig.COMPILE_SDK_VERSION import androidx.build.SupportConfig.DEFAULT_MIN_SDK_VERSION import androidx.build.SupportConfig.INSTRUMENTATION_RUNNER import androidx.build.SupportConfig.TARGET_SDK_VERSION import androidx.build.buildInfo.addCreateLibraryBuildInfoFileTasks import androidx.build.checkapi.JavaApiTaskConfig import androidx.build.checkapi.KmpApiTaskConfig import androidx.build.checkapi.LibraryApiTaskConfig import androidx.build.checkapi.configureProjectForApiTasks import androidx.build.dependencyTracker.AffectedModuleDetector import androidx.build.docs.AndroidXKmpDocsImplPlugin import androidx.build.gradle.isRoot import androidx.build.license.configureExternalDependencyLicenseCheck import androidx.build.resources.configurePublicResourcesStub import androidx.build.studio.StudioTask import androidx.build.testConfiguration.addAppApkToTestConfigGeneration import androidx.build.testConfiguration.addToTestZips import androidx.build.testConfiguration.configureTestConfigGeneration import com.android.build.api.artifact.SingleArtifact import com.android.build.api.dsl.ManagedVirtualDevice import com.android.build.api.dsl.TestOptions import com.android.build.api.variant.ApplicationAndroidComponentsExtension import com.android.build.api.variant.HasAndroidTest import com.android.build.api.variant.LibraryAndroidComponentsExtension import com.android.build.gradle.AppExtension import com.android.build.gradle.AppPlugin import com.android.build.gradle.BaseExtension import com.android.build.gradle.LibraryExtension import com.android.build.gradle.LibraryPlugin import com.android.build.gradle.TestExtension import com.android.build.gradle.TestPlugin import com.android.build.gradle.TestedExtension import com.android.build.gradle.internal.tasks.AnalyticsRecordingTask import com.android.build.gradle.internal.tasks.ListingFileRedirectTask import java.io.File import java.time.Duration import java.util.Locale import java.util.concurrent.ConcurrentHashMap import javax.inject.Inject import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.JavaVersion.VERSION_11 import org.gradle.api.JavaVersion.VERSION_1_8 import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.component.SoftwareComponentFactory import org.gradle.api.file.DuplicatesStrategy import org.gradle.api.plugins.JavaPlugin import org.gradle.api.plugins.JavaPluginExtension import org.gradle.api.tasks.Copy import org.gradle.api.tasks.TaskProvider import org.gradle.api.tasks.bundling.Jar import org.gradle.api.tasks.bundling.Zip import org.gradle.api.tasks.compile.JavaCompile import org.gradle.api.tasks.javadoc.Javadoc import org.gradle.api.tasks.testing.AbstractTestTask import org.gradle.api.tasks.testing.Test import org.gradle.api.tasks.testing.logging.TestExceptionFormat import org.gradle.api.tasks.testing.logging.TestLogEvent import org.gradle.kotlin.dsl.KotlinClosure1 import org.gradle.kotlin.dsl.create import org.gradle.kotlin.dsl.extra import org.gradle.kotlin.dsl.findByType import org.gradle.kotlin.dsl.getByType import org.gradle.kotlin.dsl.register import org.jetbrains.kotlin.gradle.dsl.KotlinAndroidProjectExtension import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension import org.jetbrains.kotlin.gradle.plugin.KotlinBasePluginWrapper import org.jetbrains.kotlin.gradle.plugin.KotlinMultiplatformPluginWrapper import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTargetWithSimulatorTests import org.jetbrains.kotlin.gradle.tasks.CInteropProcess import org.jetbrains.kotlin.gradle.tasks.KotlinCompile import org.jetbrains.kotlin.gradle.tasks.KotlinNativeCompile /** * A plugin which enables all of the Gradle customizations for AndroidX. * This plugin reacts to other plugins being added and adds required and optional functionality. */ class AndroidXImplPlugin @Inject constructor(val componentFactory: SoftwareComponentFactory) : Plugin<Project> { override fun apply(project: Project) { if (project.isRoot) throw Exception("Root project should use AndroidXRootImplPlugin instead") val extension = project.extensions.create<AndroidXExtension>(EXTENSION_NAME, project) project.extensions.create<AndroidXMultiplatformExtension>( AndroidXMultiplatformExtension.EXTENSION_NAME, project ) project.tasks.register(BUILD_ON_SERVER_TASK, DefaultTask::class.java) // Perform different actions based on which plugins have been applied to the project. // Many of the actions overlap, ex. API tracking. project.plugins.all { plugin -> when (plugin) { is JavaPlugin -> configureWithJavaPlugin(project, extension) is LibraryPlugin -> configureWithLibraryPlugin(project, extension) is AppPlugin -> configureWithAppPlugin(project, extension) is TestPlugin -> configureWithTestPlugin(project, extension) is KotlinBasePluginWrapper -> configureWithKotlinPlugin(project, extension, plugin) } } project.configureKtlint() // Configure all Jar-packing tasks for hermetic builds. project.tasks.withType(Jar::class.java).configureEach { it.configureForHermeticBuild() } project.tasks.withType(Copy::class.java).configureEach { it.configureForHermeticBuild() } // copy host side test results to DIST project.tasks.withType(AbstractTestTask::class.java) { task -> configureTestTask(project, task) } project.tasks.withType(Test::class.java) { task -> configureJvmTestTask(project, task) } project.configureTaskTimeouts() project.configureMavenArtifactUpload(extension, componentFactory) project.configureExternalDependencyLicenseCheck() project.configureProjectStructureValidation(extension) project.configureProjectVersionValidation(extension) project.registerProjectOrArtifact() project.addCreateLibraryBuildInfoFileTasks(extension) project.configurations.create("samples") project.validateMultiplatformPluginHasNotBeenApplied() if (!ProjectLayoutType.isPlayground(project)) { project.whenChangingOutputTextValidationMustInvalidateAllTasks() } } private fun Project.registerProjectOrArtifact() { // Add a method for each sub project where they can declare an optional // dependency on a project or its latest snapshot artifact. if (!ProjectLayoutType.isPlayground(this)) { // In AndroidX build, this is always enforced to the project extra.set( PROJECT_OR_ARTIFACT_EXT_NAME, KotlinClosure1<String, Project>( function = { // this refers to the first parameter of the closure. project.resolveProject(this) } ) ) } else { // In Playground builds, they are converted to the latest SNAPSHOT artifact if the // project is not included in that playground. extra.set( PROJECT_OR_ARTIFACT_EXT_NAME, KotlinClosure1<String, Any>( function = { AndroidXPlaygroundRootImplPlugin.projectOrArtifact(rootProject, this) } ) ) } } /** * Disables timestamps and ensures filesystem-independent archive ordering to maximize * cross-machine byte-for-byte reproducibility of artifacts. */ private fun Jar.configureForHermeticBuild() { isReproducibleFileOrder = true isPreserveFileTimestamps = false } private fun Copy.configureForHermeticBuild() { duplicatesStrategy = DuplicatesStrategy.FAIL } private fun configureJvmTestTask(project: Project, task: Test) { // Robolectric 1.7 increased heap size requirements, see b/207169653. task.maxHeapSize = "3g" // For non-playground setup use robolectric offline if (!ProjectLayoutType.isPlayground(project)) { task.systemProperty("robolectric.offline", "true") val robolectricDependencies = File( project.getPrebuiltsRoot(), "androidx/external/org/robolectric/android-all-instrumented" ) task.systemProperty( "robolectric.dependency.dir", robolectricDependencies.relativeTo(project.projectDir) ) } } private fun configureTestTask(project: Project, task: AbstractTestTask) { val ignoreFailuresProperty = project.providers.gradleProperty( TEST_FAILURES_DO_NOT_FAIL_TEST_TASK ) val ignoreFailures = ignoreFailuresProperty.isPresent if (ignoreFailures) { task.ignoreFailures = true } task.inputs.property("ignoreFailures", ignoreFailures) val xmlReportDestDir = project.getHostTestResultDirectory() val archiveName = "${project.path}:${task.name}.zip" if (project.isDisplayTestOutput()) { // Enable tracing to see results in command line task.testLogging.apply { events = hashSetOf( TestLogEvent.FAILED, TestLogEvent.PASSED, TestLogEvent.SKIPPED, TestLogEvent.STANDARD_OUT ) showExceptions = true showCauses = true showStackTraces = true exceptionFormat = TestExceptionFormat.FULL } } else { task.testLogging.apply { showExceptions = false // Disable all output, including the names of the failing tests, by specifying // that the minimum granularity we're interested in is this very high number // (which is higher than the current maximum granularity that Gradle offers (3)) minGranularity = 1000 } val testTaskName = task.name val capitalizedTestTaskName = testTaskName.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } val zipHtmlTask = project.tasks.register( "zipHtmlResultsOf$capitalizedTestTaskName", Zip::class.java ) { val destinationDirectory = File("$xmlReportDestDir-html") it.destinationDirectory.set(destinationDirectory) it.archiveFileName.set(archiveName) it.from(project.file(task.reports.html.outputLocation)) it.doLast { zip -> // If the test itself didn't display output, then the report task should // remind the user where to find its output zip.logger.lifecycle( "Html results of $testTaskName zipped into " + "$destinationDirectory/$archiveName" ) } } task.finalizedBy(zipHtmlTask) val xmlReport = task.reports.junitXml if (xmlReport.required.get()) { val zipXmlTask = project.tasks.register( "zipXmlResultsOf$capitalizedTestTaskName", Zip::class.java ) { it.destinationDirectory.set(xmlReportDestDir) it.archiveFileName.set(archiveName) it.from(project.file(xmlReport.outputLocation)) } task.finalizedBy(zipXmlTask) } } } private fun configureWithKotlinPlugin( project: Project, extension: AndroidXExtension, plugin: KotlinBasePluginWrapper ) { project.afterEvaluate { project.tasks.withType(KotlinCompile::class.java).configureEach { task -> if (extension.type.compilationTarget == CompilationTarget.HOST && extension.type != LibraryType.ANNOTATION_PROCESSOR_UTILS ) { task.kotlinOptions.jvmTarget = "11" } else { task.kotlinOptions.jvmTarget = "1.8" } val kotlinCompilerArgs = mutableListOf( "-Xskip-metadata-version-check", ) // TODO (b/259578592): enable -Xjvm-default=all for camera-camera2-pipe projects if (!project.name.contains("camera-camera2-pipe")) { kotlinCompilerArgs += "-Xjvm-default=all" } task.kotlinOptions.freeCompilerArgs += kotlinCompilerArgs } // If no one else is going to register a source jar, then we should. // This cross-plugin hands-off logic shouldn't be necessary once we clean up sourceSet // logic (b/235828421) if (!project.plugins.hasPlugin(LibraryPlugin::class.java) && !project.plugins.hasPlugin(JavaPlugin::class.java)) { project.configureSourceJarForJava() } val isAndroidProject = project.plugins.hasPlugin(LibraryPlugin::class.java) || project.plugins.hasPlugin(AppPlugin::class.java) // Explicit API mode is broken for Android projects // https://youtrack.jetbrains.com/issue/KT-37652 if (extension.shouldEnforceKotlinStrictApiMode() && !isAndroidProject) { project.tasks.withType(KotlinCompile::class.java).configureEach { task -> // Workaround for https://youtrack.jetbrains.com/issue/KT-37652 if (task.name.endsWith("TestKotlin")) return@configureEach if (task.name.endsWith("TestKotlinJvm")) return@configureEach task.kotlinOptions.freeCompilerArgs += listOf("-Xexplicit-api=strict") } } } // setup a partial docs artifact that can be used to generate offline docs, if requested. AndroidXKmpDocsImplPlugin.setupPartialDocsArtifact(project) if (plugin is KotlinMultiplatformPluginWrapper) { project.configureKonanDirectory() project.extensions.findByType<LibraryExtension>()?.apply { configureAndroidLibraryWithMultiplatformPluginOptions() } project.configureKmpTests() project.configureSourceJarForMultiplatform() } } @Suppress("UnstableApiUsage") // AGP DSL APIs private fun configureWithAppPlugin(project: Project, androidXExtension: AndroidXExtension) { project.extensions.getByType<AppExtension>().apply { configureAndroidBaseOptions(project, androidXExtension) configureAndroidApplicationOptions(project) } project.extensions.getByType<ApplicationAndroidComponentsExtension>().apply { onVariants { it.configureLicensePackaging() } finalizeDsl { project.configureAndroidProjectForLint( it.lint, androidXExtension, isLibrary = false ) } } } private fun configureWithTestPlugin( project: Project, androidXExtension: AndroidXExtension ) { project.extensions.getByType<TestExtension>().apply { configureAndroidBaseOptions(project, androidXExtension) } project.configureJavaCompilationWarnings(androidXExtension) project.addToProjectMap(androidXExtension) } private fun HasAndroidTest.configureLicensePackaging() { androidTest?.packaging?.resources?.apply { // Workaround a limitation in AGP that fails to merge these META-INF license files. pickFirsts.add("/META-INF/AL2.0") // In addition to working around the above issue, we exclude the LGPL2.1 license as we're // approved to distribute code via AL2.0 and the only dependencies which pull in LGPL2.1 // are currently dual-licensed with AL2.0 and LGPL2.1. The affected dependencies are: // - net.java.dev.jna:jna:5.5.0 excludes.add("/META-INF/LGPL2.1") } } @Suppress("UnstableApiUsage", "DEPRECATION") // AGP DSL APIs private fun configureWithLibraryPlugin( project: Project, androidXExtension: AndroidXExtension ) { val libraryExtension = project.extensions.getByType<LibraryExtension>().apply { configureAndroidBaseOptions(project, androidXExtension) configureAndroidLibraryOptions(project, androidXExtension) // Make sure the main Kotlin source set doesn't contain anything under src/main/kotlin. val mainKotlinSrcDir = (sourceSets.findByName("main")?.kotlin as com.android.build.gradle.api.AndroidSourceDirectorySet) .srcDirs .filter { it.name == "kotlin" } .getOrNull(0) if (mainKotlinSrcDir?.isDirectory == true) { throw GradleException( "Invalid project structure! AndroidX does not support \"kotlin\" as a " + "top-level source directory for libraries, use \"java\" instead: " + mainKotlinSrcDir.path ) } } // Remove the android:targetSdkVersion element from the manifest used for AARs. project.extensions.getByType<LibraryAndroidComponentsExtension>().onVariants { variant -> project.tasks.register( variant.name + "AarManifestTransformer", AarManifestTransformerTask::class.java ).let { taskProvider -> variant.artifacts.use(taskProvider) .wiredWithFiles( AarManifestTransformerTask::aarFile, AarManifestTransformerTask::updatedAarFile ) .toTransform(SingleArtifact.AAR) } } project.extensions.getByType<com.android.build.api.dsl.LibraryExtension>().apply { publishing { singleVariant(DEFAULT_PUBLISH_CONFIG) } } project.extensions.getByType<LibraryAndroidComponentsExtension>().apply { beforeVariants(selector().withBuildType("release")) { variant -> variant.enableUnitTest = false } onVariants { it.configureLicensePackaging() } finalizeDsl { project.configureAndroidProjectForLint(it.lint, androidXExtension, isLibrary = true) } } project.configurePublicResourcesStub(libraryExtension) project.configureSourceJarForAndroid(libraryExtension) project.configureVersionFileWriter(libraryExtension, androidXExtension) project.configureJavaCompilationWarnings(androidXExtension) project.configureDependencyVerification(androidXExtension) { taskProvider -> libraryExtension.defaultPublishVariant { libraryVariant -> taskProvider.configure { task -> task.dependsOn(libraryVariant.javaCompileProvider) } } } val reportLibraryMetrics = project.configureReportLibraryMetricsTask() project.addToBuildOnServer(reportLibraryMetrics) libraryExtension.defaultPublishVariant { libraryVariant -> reportLibraryMetrics.configure { it.jarFiles.from( libraryVariant.packageLibraryProvider.map { zip -> zip.inputs.files } ) } } // Standard docs, resource API, and Metalava configuration for AndroidX projects. project.configureProjectForApiTasks( LibraryApiTaskConfig(libraryExtension), androidXExtension ) project.addToProjectMap(androidXExtension) } private fun configureWithJavaPlugin(project: Project, extension: AndroidXExtension) { project.configureErrorProneForJava() project.configureSourceJarForJava() // Force Java 1.8 source- and target-compatibility for all Java libraries. val javaExtension = project.extensions.getByType<JavaPluginExtension>() project.afterEvaluate { if (extension.type.compilationTarget == CompilationTarget.HOST && extension.type != LibraryType.ANNOTATION_PROCESSOR_UTILS ) { javaExtension.apply { sourceCompatibility = VERSION_11 targetCompatibility = VERSION_11 } } else { javaExtension.apply { sourceCompatibility = VERSION_1_8 targetCompatibility = VERSION_1_8 } } } project.configureJavaCompilationWarnings(extension) project.hideJavadocTask() project.configureDependencyVerification(extension) { taskProvider -> taskProvider.configure { task -> task.dependsOn(project.tasks.named(JavaPlugin.COMPILE_JAVA_TASK_NAME)) } } // Standard lint, docs, and Metalava configuration for AndroidX projects. project.configureNonAndroidProjectForLint(extension) val apiTaskConfig = if (project.multiplatformExtension != null) { KmpApiTaskConfig } else { JavaApiTaskConfig } project.configureProjectForApiTasks(apiTaskConfig, extension) project.afterEvaluate { if (extension.shouldRelease()) { project.extra.set("publish", true) } } // Workaround for b/120487939 wherein Gradle's default resolution strategy prefers external // modules with lower versions over local projects with higher versions. project.configurations.all { configuration -> configuration.resolutionStrategy.preferProjectModules() } project.addToProjectMap(extension) } private fun Project.configureProjectStructureValidation( extension: AndroidXExtension ) { // AndroidXExtension.mavenGroup is not readable until afterEvaluate. afterEvaluate { val mavenGroup = extension.mavenGroup val isProbablyPublished = extension.type == LibraryType.PUBLISHED_LIBRARY || extension.type == LibraryType.UNSET if (mavenGroup != null && isProbablyPublished) { validateProjectStructure(mavenGroup.group) } } } private fun Project.configureProjectVersionValidation( extension: AndroidXExtension ) { // AndroidXExtension.mavenGroup is not readable until afterEvaluate. afterEvaluate { extension.validateMavenVersion() } } @Suppress("UnstableApiUsage") // Usage of ManagedVirtualDevice private fun TestOptions.configureVirtualDevices() { managedDevices.devices.register<ManagedVirtualDevice>("pixel2api29") { device = "Pixel 2" apiLevel = 29 systemImageSource = "aosp" } managedDevices.devices.register<ManagedVirtualDevice>("pixel2api30") { device = "Pixel 2" apiLevel = 30 systemImageSource = "aosp" } managedDevices.devices.register<ManagedVirtualDevice>("pixel2api31") { device = "Pixel 2" apiLevel = 31 systemImageSource = "aosp" } } private fun BaseExtension.configureAndroidBaseOptions( project: Project, androidXExtension: AndroidXExtension ) { compileOptions.apply { sourceCompatibility = VERSION_1_8 targetCompatibility = VERSION_1_8 } compileSdkVersion(COMPILE_SDK_VERSION) buildToolsVersion = BUILD_TOOLS_VERSION defaultConfig.targetSdk = TARGET_SDK_VERSION ndkVersion = SupportConfig.NDK_VERSION defaultConfig.testInstrumentationRunner = INSTRUMENTATION_RUNNER testOptions.animationsDisabled = true testOptions.unitTests.isReturnDefaultValues = true testOptions.unitTests.all { task -> // https://github.com/robolectric/robolectric/issues/7456 task.jvmArgs = listOf( "--add-opens=java.base/java.lang=ALL-UNNAMED", "--add-opens=java.base/java.util=ALL-UNNAMED", "--add-opens=java.base/java.io=ALL-UNNAMED", ) // Robolectric 1.7 increased heap size requirements, see b/207169653. task.maxHeapSize = "3g" } testOptions.configureVirtualDevices() // Include resources in Robolectric tests as a workaround for b/184641296 and // ensure the build directory exists as a workaround for b/187970292. testOptions.unitTests.isIncludeAndroidResources = true if (!project.buildDir.exists()) project.buildDir.mkdirs() defaultConfig.minSdk = DEFAULT_MIN_SDK_VERSION project.afterEvaluate { val minSdkVersion = defaultConfig.minSdk!! check(minSdkVersion >= DEFAULT_MIN_SDK_VERSION) { "minSdkVersion $minSdkVersion lower than the default of $DEFAULT_MIN_SDK_VERSION" } check(compileSdkVersion == COMPILE_SDK_VERSION || project.isCustomCompileSdkAllowed() ) { "compileSdkVersion must not be explicitly specified, was \"$compileSdkVersion\"" } project.configurations.all { configuration -> configuration.resolutionStrategy.eachDependency { dep -> val target = dep.target val version = target.version // Enforce the ban on declaring dependencies with version ranges. // Note: In playground, this ban is exempted to allow unresolvable prebuilts // to automatically get bumped to snapshot versions via version range // substitution. if (version != null && Version.isDependencyRange(version) && project.rootProject.rootDir == project.getSupportRootFolder() ) { throw IllegalArgumentException( "Dependency ${dep.target} declares its version as " + "version range ${dep.target.version} however the use of " + "version ranges is not allowed, please update the " + "dependency to list a fixed version." ) } } } if (androidXExtension.type.compilationTarget != CompilationTarget.DEVICE) { throw IllegalStateException( "${androidXExtension.type.name} libraries cannot apply the android plugin, as" + " they do not target android devices" ) } } val debugSigningConfig = signingConfigs.getByName("debug") // Use a local debug keystore to avoid build server issues. debugSigningConfig.storeFile = project.getKeystore() buildTypes.all { buildType -> // Sign all the builds (including release) with debug key buildType.signingConfig = debugSigningConfig } project.configureErrorProneForAndroid(variants) // workaround for b/120487939 project.configurations.all { configuration -> // Gradle seems to crash on androidtest configurations // preferring project modules... if (!configuration.name.lowercase(Locale.US).contains("androidtest")) { configuration.resolutionStrategy.preferProjectModules() } } project.configureTestConfigGeneration(this) val buildTestApksTask = project.rootProject.tasks.named(BUILD_TEST_APKS_TASK) when (this) { is TestedExtension -> testVariants // app module defines variants for test module is TestExtension -> applicationVariants else -> throw IllegalStateException("Unsupported plugin type") }.all { variant -> buildTestApksTask.configure { it.dependsOn(variant.assembleProvider) } variant.configureApkZipping(project, true) } // AGP warns if we use project.buildDir (or subdirs) for CMake's generated // build files (ninja build files, CMakeCache.txt, etc.). Use a staging directory that // lives alongside the project's buildDir. externalNativeBuild.cmake.buildStagingDirectory = File(project.buildDir, "../nativeBuildStaging") // disable analytics recording // It's always out-of-date, and we don't release any apps in this repo project.tasks.withType(AnalyticsRecordingTask::class.java).configureEach { task -> task.enabled = false } } /** * Configures the ZIP_TEST_CONFIGS_WITH_APKS_TASK to include the test apk if applicable */ @Suppress("DEPRECATION") // ApkVariant private fun com.android.build.gradle.api.ApkVariant.configureApkZipping( project: Project, testApk: Boolean ) { packageApplicationProvider.get().let { packageTask -> AffectedModuleDetector.configureTaskGuard(packageTask) // Skip copying AndroidTest apks if they have no source code (no tests to run). if (!testApk || project.hasAndroidTestSourceCode()) { addToTestZips(project, packageTask) } } // This task needs to be guarded by AffectedModuleDetector due to guarding test // APK building above. It can only be removed if we stop using AMD for test APKs. project.tasks.withType(ListingFileRedirectTask::class.java).forEach { AffectedModuleDetector.configureTaskGuard(it) } } private fun LibraryExtension.configureAndroidLibraryOptions( project: Project, androidXExtension: AndroidXExtension ) { // Note, this should really match COMPILE_SDK_VERSION, however // this API takes an integer and we are unable to set it to a // pre-release SDK. defaultConfig.aarMetadata.minCompileSdk = TARGET_SDK_VERSION project.configurations.all { config -> val isTestConfig = config.name.lowercase(Locale.US).contains("test") config.dependencyConstraints.configureEach { dependencyConstraint -> dependencyConstraint.apply { // Remove strict constraints on test dependencies and listenablefuture:1.0 if (isTestConfig || group == "com.google.guava" && name == "listenablefuture" && version == "1.0" ) { version { versionConstraint -> versionConstraint.strictly("") } } } } } project.afterEvaluate { if (androidXExtension.shouldRelease()) { project.extra.set("publish", true) } } } private fun TestedExtension.configureAndroidLibraryWithMultiplatformPluginOptions() { sourceSets.findByName("main")!!.manifest.srcFile("src/androidMain/AndroidManifest.xml") sourceSets.findByName("androidTest")!! .manifest.srcFile("src/androidAndroidTest/AndroidManifest.xml") } /** * Sets the konan distribution url to the prebuilts directory. */ private fun Project.configureKonanDirectory() { if (ProjectLayoutType.isPlayground(this)) { return // playground does not use prebuilts } overrideKotlinNativeDistributionUrlToLocalDirectory() overrideKotlinNativeDependenciesUrlToLocalDirectory() } private fun Project.overrideKotlinNativeDependenciesUrlToLocalDirectory() { val konanPrebuiltsFolder = getKonanPrebuiltsFolder() // use relative path so it doesn't affect gradle remote cache. val relativeRootPath = konanPrebuiltsFolder.relativeTo(rootProject.projectDir).path val relativeProjectPath = konanPrebuiltsFolder.relativeTo(projectDir).path tasks.withType(KotlinNativeCompile::class.java).configureEach { it.kotlinOptions.freeCompilerArgs += listOf( "-Xoverride-konan-properties=dependenciesUrl=file:$relativeRootPath" ) } tasks.withType(CInteropProcess::class.java).configureEach { it.settings.extraOpts += listOf( "-Xoverride-konan-properties", "dependenciesUrl=file:$relativeProjectPath" ) } } private fun Project.overrideKotlinNativeDistributionUrlToLocalDirectory() { val relativePath = getKonanPrebuiltsFolder() .resolve("nativeCompilerPrebuilts") .relativeTo(projectDir) .path val url = "file:$relativePath" extensions.extraProperties["kotlin.native.distribution.baseDownloadUrl"] = url } private fun Project.configureKmpTests() { val kmpExtension = checkNotNull( project.extensions.findByType<KotlinMultiplatformExtension>() ) { """ Project ${project.path} applies kotlin multiplatform plugin but we cannot find the KotlinMultiplatformExtension. """.trimIndent() } kmpExtension.testableTargets.all { kotlinTarget -> if (kotlinTarget is KotlinNativeTargetWithSimulatorTests) { kotlinTarget.binaries.all { // Use std allocator to avoid the following warning: // w: Mimalloc allocator isn't supported on target <target>. Used standard mode. it.freeCompilerArgs += "-Xallocator=std" } } } } private fun AppExtension.configureAndroidApplicationOptions(project: Project) { defaultConfig.apply { versionCode = 1 versionName = "1.0" } project.addAppApkToTestConfigGeneration() val buildTestApksTask = project.rootProject.tasks.named(BUILD_TEST_APKS_TASK) applicationVariants.all { variant -> // Using getName() instead of name due to b/150427408 if (variant.buildType.name == "debug") { buildTestApksTask.configure { it.dependsOn(variant.assembleProvider) } } variant.configureApkZipping(project, false) } } private fun Project.configureDependencyVerification( extension: AndroidXExtension, taskConfigurator: (TaskProvider<VerifyDependencyVersionsTask>) -> Unit ) { afterEvaluate { if (extension.type != LibraryType.SAMPLES) { val verifyDependencyVersionsTask = project.createVerifyDependencyVersionsTask() if (verifyDependencyVersionsTask != null) { taskConfigurator(verifyDependencyVersionsTask) } } } } companion object { const val BUILD_TEST_APKS_TASK = "buildTestApks" const val CREATE_LIBRARY_BUILD_INFO_FILES_TASK = "createLibraryBuildInfoFiles" const val GENERATE_TEST_CONFIGURATION_TASK = "GenerateTestConfiguration" const val ZIP_TEST_CONFIGS_WITH_APKS_TASK = "zipTestConfigsWithApks" const val ZIP_CONSTRAINED_TEST_CONFIGS_WITH_APKS_TASK = "zipConstrainedTestConfigsWithApks" const val TASK_GROUP_API = "API" const val EXTENSION_NAME = "androidx" /** * Fail the build if a non-Studio task runs longer than expected */ const val TASK_TIMEOUT_MINUTES = 60L } } private const val PROJECTS_MAP_KEY = "projects" private const val ACCESSED_PROJECTS_MAP_KEY = "accessedProjectsMap" /** * Hides a project's Javadoc tasks from the output of `./gradlew tasks` by setting their group to * `null`. * * AndroidX projects do not use the Javadoc task for docs generation, so we don't want them * cluttering up the task overview. */ private fun Project.hideJavadocTask() { tasks.withType(Javadoc::class.java).configureEach { if (it.name == "javadoc") { it.group = null } } } private fun Project.addToProjectMap(extension: AndroidXExtension) { // TODO(alanv): Move this out of afterEvaluate afterEvaluate { if (extension.shouldRelease()) { val group = extension.mavenGroup?.group if (group != null) { val module = "$group:$name" if (project.rootProject.extra.has(ACCESSED_PROJECTS_MAP_KEY)) { throw GradleException( "Attempted to add $project to project map after " + "the contents of the map were accessed" ) } @Suppress("UNCHECKED_CAST") val projectModules = project.rootProject.extra.get(PROJECTS_MAP_KEY) as ConcurrentHashMap<String, String> projectModules[module] = path } } } } val Project.multiplatformExtension get() = extensions.findByType(KotlinMultiplatformExtension::class.java) @Suppress("UNCHECKED_CAST") fun Project.getProjectsMap(): ConcurrentHashMap<String, String> { project.rootProject.extra.set(ACCESSED_PROJECTS_MAP_KEY, true) return rootProject.extra.get(PROJECTS_MAP_KEY) as ConcurrentHashMap<String, String> } /** * Configures all non-Studio tasks in a project (see b/153193718 for background) to time out after * [TASK_TIMEOUT_MINUTES]. */ private fun Project.configureTaskTimeouts() { tasks.configureEach { t -> // skip adding a timeout for some tasks that both take a long time and // that we can count on the user to monitor if (t !is StudioTask) { t.timeout.set(Duration.ofMinutes(TASK_TIMEOUT_MINUTES)) } } } private fun Project.configureJavaCompilationWarnings(androidXExtension: AndroidXExtension) { afterEvaluate { project.tasks.withType(JavaCompile::class.java).configureEach { task -> // If we're running a hypothetical test build confirming that tip-of-tree versions // are compatible, then we're not concerned about warnings if (!project.usingMaxDepVersions()) { task.options.compilerArgs.add("-Xlint:unchecked") if (androidXExtension.failOnDeprecationWarnings) { task.options.compilerArgs.add("-Xlint:deprecation") } } } } } /** * Guarantees unique names for the APKs, and modifies some of the suffixes. The APK name is used * to determine what gets run by our test runner */ fun String.renameApkForTesting(projectPath: String, hasBenchmarkPlugin: Boolean): String { val name = if (projectPath.contains("media") && projectPath.contains("version-compat-tests")) { // Exclude media*:version-compat-tests modules from // existing support library presubmit tests. this.replace("-debug-androidTest", "") } else if (hasBenchmarkPlugin) { this.replace("-androidTest", "-androidBenchmark") } else if (projectPath.endsWith("macrobenchmark")) { this.replace("-androidTest", "-androidMacrobenchmark") } else { this } return "${projectPath.asFilenamePrefix()}_$name" } fun Project.hasBenchmarkPlugin(): Boolean { return this.plugins.hasPlugin(BenchmarkPlugin::class.java) } /** * Returns a string that is a valid filename and loosely based on the project name * The value returned for each project will be distinct */ fun String.asFilenamePrefix(): String { return this.substring(1).replace(':', '-') } /** * Sets the specified [task] as a dependency of the top-level `check` task, ensuring that it runs * as part of `./gradlew check`. */ fun <T : Task> Project.addToCheckTask(task: TaskProvider<T>) { project.tasks.named("check").configure { it.dependsOn(task) } } /** * Expected to be called in afterEvaluate when all extensions are available */ internal fun Project.hasAndroidTestSourceCode(): Boolean { // com.android.test modules keep test code in main sourceset extensions.findByType(TestExtension::class.java)?.let { extension -> extension.sourceSets.findByName("main")?.let { sourceSet -> if (!sourceSet.java.getSourceFiles().isEmpty) return true } // check kotlin-android main source set extensions.findByType(KotlinAndroidProjectExtension::class.java) ?.sourceSets?.findByName("main")?.let { if (it.kotlin.files.isNotEmpty()) return true } // Note, don't have to check for kotlin-multiplatform as it is not compatible with // com.android.test modules } // check Java androidTest source set extensions.findByType(TestedExtension::class.java) ?.sourceSets ?.findByName("androidTest") ?.let { sourceSet -> // using getSourceFiles() instead of sourceFiles due to b/150800094 if (!sourceSet.java.getSourceFiles().isEmpty) return true } // check kotlin-android androidTest source set extensions.findByType(KotlinAndroidProjectExtension::class.java) ?.sourceSets?.findByName("androidTest")?.let { if (it.kotlin.files.isNotEmpty()) return true } // check kotlin-multiplatform androidAndroidTest source set multiplatformExtension?.apply { sourceSets.findByName("androidAndroidTest")?.let { if (it.kotlin.files.isNotEmpty()) return true } } return false } private const val GROUP_PREFIX = "androidx." /** * Validates the project structure against Jetpack guidelines. */ fun Project.validateProjectStructure(groupId: String) { if (!project.isValidateProjectStructureEnabled()) { return } val shortGroupId = if (groupId.startsWith(GROUP_PREFIX)) { groupId.substring(GROUP_PREFIX.length) } else { groupId } // Fully-qualified Gradle project name should match the Maven coordinate. val expectName = ":${shortGroupId.replace(".",":")}:${project.name}" val actualName = project.path if (expectName != actualName) { throw GradleException( "Invalid project structure! Expected $expectName as project name, found $actualName" ) } // Project directory should match the Maven coordinate. val expectDir = shortGroupId.replace(".", File.separator) + "${File.separator}${project.name}" // Canonical projectDir is needed because sometimes, at least in tests, on OSX, supportRoot // starts with /var, and projectDir starts with /private/var (which are the same thing) val canonicalProjectDir = project.projectDir.canonicalFile val actualDir = canonicalProjectDir.toRelativeString(project.getSupportRootFolder().canonicalFile) if (expectDir != actualDir) { throw GradleException( "Invalid project structure! Expected $expectDir as project directory, found $actualDir" ) } } fun Project.validateMultiplatformPluginHasNotBeenApplied() { if (plugins.hasPlugin(KotlinMultiplatformPluginWrapper::class.java)) { throw GradleException( "The Kotlin multiplatform plugin should only be applied by the AndroidX plugin." ) } } // If our output message validation configuration changes, invalidate all tasks to make sure // all output messages get regenerated and re-validated private fun Project.whenChangingOutputTextValidationMustInvalidateAllTasks() { val configFile = project.rootProject.file("development/build_log_simplifier/messages.ignore") if (configFile.exists()) { project.tasks.configureEach { task -> task.inputs.file(configFile) } } } /** * Validates the Maven version against Jetpack guidelines. */ fun AndroidXExtension.validateMavenVersion() { val mavenGroup = mavenGroup val mavenVersion = mavenVersion val forcedVersion = mavenGroup?.atomicGroupVersion if (forcedVersion != null && forcedVersion == mavenVersion) { throw GradleException( """ Unnecessary override of same-group library version Project version is already set to $forcedVersion by same-version group ${mavenGroup.group}. To fix this error, remove "mavenVersion = ..." from your build.gradle configuration. """.trimIndent() ) } } /** * Removes the line and column attributes from the [baseline]. */ fun removeLineAndColumnAttributes(baseline: String): String = baseline.replace( "\\s*(line|column)=\"\\d+?\"".toRegex(), "" ) const val PROJECT_OR_ARTIFACT_EXT_NAME = "projectOrArtifact"
apache-2.0
c4b91efb4ab89af14f7c361246c50ace
40.50713
101
0.644629
5.059316
false
true
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/push/SignalServiceNetworkAccess.kt
1
13949
package org.thoughtcrime.securesms.push import android.content.Context import okhttp3.CipherSuite import okhttp3.ConnectionSpec import okhttp3.Dns import okhttp3.Interceptor import okhttp3.TlsVersion import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.BuildConfig import org.thoughtcrime.securesms.keyvalue.SettingsValues import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.net.CustomDns import org.thoughtcrime.securesms.net.DeprecatedClientPreventionInterceptor import org.thoughtcrime.securesms.net.DeviceTransferBlockingInterceptor import org.thoughtcrime.securesms.net.RemoteDeprecationDetectorInterceptor import org.thoughtcrime.securesms.net.SequentialDns import org.thoughtcrime.securesms.net.StandardUserAgentInterceptor import org.thoughtcrime.securesms.net.StaticDns import org.thoughtcrime.securesms.phonenumbers.PhoneNumberFormatter import org.thoughtcrime.securesms.util.Base64 import org.whispersystems.signalservice.api.push.TrustStore import org.whispersystems.signalservice.internal.configuration.SignalCdnUrl import org.whispersystems.signalservice.internal.configuration.SignalCdsiUrl import org.whispersystems.signalservice.internal.configuration.SignalContactDiscoveryUrl import org.whispersystems.signalservice.internal.configuration.SignalKeyBackupServiceUrl import org.whispersystems.signalservice.internal.configuration.SignalServiceConfiguration import org.whispersystems.signalservice.internal.configuration.SignalServiceUrl import org.whispersystems.signalservice.internal.configuration.SignalStorageUrl import java.io.IOException import java.util.Optional /** * Provides a [SignalServiceConfiguration] to be used with our service layer. * If you're looking for a place to start, look at [getConfiguration]. */ open class SignalServiceNetworkAccess(context: Context) { companion object { private val TAG = Log.tag(SignalServiceNetworkAccess::class.java) @JvmField val DNS: Dns = SequentialDns( Dns.SYSTEM, CustomDns("1.1.1.1"), StaticDns( mapOf( BuildConfig.SIGNAL_URL.stripProtocol() to BuildConfig.SIGNAL_SERVICE_IPS.toSet(), BuildConfig.STORAGE_URL.stripProtocol() to BuildConfig.SIGNAL_STORAGE_IPS.toSet(), BuildConfig.SIGNAL_CDN_URL.stripProtocol() to BuildConfig.SIGNAL_CDN_IPS.toSet(), BuildConfig.SIGNAL_CDN2_URL.stripProtocol() to BuildConfig.SIGNAL_CDN2_IPS.toSet(), BuildConfig.SIGNAL_CONTACT_DISCOVERY_URL.stripProtocol() to BuildConfig.SIGNAL_CDS_IPS.toSet(), BuildConfig.SIGNAL_KEY_BACKUP_URL.stripProtocol() to BuildConfig.SIGNAL_KBS_IPS.toSet(), BuildConfig.SIGNAL_SFU_URL.stripProtocol() to BuildConfig.SIGNAL_SFU_IPS.toSet(), BuildConfig.CONTENT_PROXY_HOST.stripProtocol() to BuildConfig.SIGNAL_CONTENT_PROXY_IPS.toSet(), ) ) ) private fun String.stripProtocol(): String { return this.removePrefix("https://") } private const val COUNTRY_CODE_EGYPT = 20 private const val COUNTRY_CODE_UAE = 971 private const val COUNTRY_CODE_OMAN = 968 private const val COUNTRY_CODE_QATAR = 974 private const val COUNTRY_CODE_IRAN = 98 private const val COUNTRY_CODE_CUBA = 53 private const val COUNTRY_CODE_UZBEKISTAN = 998 private const val COUNTRY_CODE_UKRAINE = 380 private const val G_HOST = "europe-west1-signal-cdn-reflector.cloudfunctions.net" private const val F_SERVICE_HOST = "textsecure-service.whispersystems.org.global.prod.fastly.net" private const val F_STORAGE_HOST = "storage.signal.org.global.prod.fastly.net" private const val F_CDN_HOST = "cdn.signal.org.global.prod.fastly.net" private const val F_CDN2_HOST = "cdn2.signal.org.global.prod.fastly.net" private const val F_DIRECTORY_HOST = "api.directory.signal.org.global.prod.fastly.net" private const val F_KBS_HOST = "api.backup.signal.org.global.prod.fastly.net" private val GMAPS_CONNECTION_SPEC = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2) .cipherSuites( CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384, CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA ) .supportsTlsExtensions(true) .build() private val GMAIL_CONNECTION_SPEC = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2) .cipherSuites( CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA ) .supportsTlsExtensions(true) .build() private val PLAY_CONNECTION_SPEC = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2) .cipherSuites( CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA ) .supportsTlsExtensions(true) .build() private val APP_CONNECTION_SPEC = ConnectionSpec.MODERN_TLS } private val serviceTrustStore: TrustStore = SignalServiceTrustStore(context) private val gTrustStore: TrustStore = DomainFrontingTrustStore(context) private val fTrustStore: TrustStore = DomainFrontingDigicertTrustStore(context) private val interceptors: List<Interceptor> = listOf( StandardUserAgentInterceptor(), RemoteDeprecationDetectorInterceptor(), DeprecatedClientPreventionInterceptor(), DeviceTransferBlockingInterceptor.getInstance() ) private val zkGroupServerPublicParams: ByteArray = try { Base64.decode(BuildConfig.ZKGROUP_SERVER_PUBLIC_PARAMS) } catch (e: IOException) { throw AssertionError(e) } private val baseGHostConfigs: List<HostConfig> = listOf( HostConfig("https://www.google.com", G_HOST, GMAIL_CONNECTION_SPEC), HostConfig("https://android.clients.google.com", G_HOST, PLAY_CONNECTION_SPEC), HostConfig("https://clients3.google.com", G_HOST, GMAPS_CONNECTION_SPEC), HostConfig("https://clients4.google.com", G_HOST, GMAPS_CONNECTION_SPEC), HostConfig("https://inbox.google.com", G_HOST, GMAIL_CONNECTION_SPEC), ) private val fUrls = arrayOf("https://cdn.sstatic.net", "https://github.githubassets.com", "https://pinterest.com", "https://open.scdn.co", "https://www.redditstatic.com") private val fConfig: SignalServiceConfiguration = SignalServiceConfiguration( fUrls.map { SignalServiceUrl(it, F_SERVICE_HOST, fTrustStore, APP_CONNECTION_SPEC) }.toTypedArray(), mapOf( 0 to fUrls.map { SignalCdnUrl(it, F_CDN_HOST, fTrustStore, APP_CONNECTION_SPEC) }.toTypedArray(), 2 to fUrls.map { SignalCdnUrl(it, F_CDN2_HOST, fTrustStore, APP_CONNECTION_SPEC) }.toTypedArray(), ), fUrls.map { SignalContactDiscoveryUrl(it, F_DIRECTORY_HOST, fTrustStore, APP_CONNECTION_SPEC) }.toTypedArray(), fUrls.map { SignalKeyBackupServiceUrl(it, F_KBS_HOST, fTrustStore, APP_CONNECTION_SPEC) }.toTypedArray(), fUrls.map { SignalStorageUrl(it, F_STORAGE_HOST, fTrustStore, APP_CONNECTION_SPEC) }.toTypedArray(), arrayOf(SignalCdsiUrl(BuildConfig.SIGNAL_CDSI_URL, serviceTrustStore)), interceptors, Optional.of(DNS), Optional.empty(), zkGroupServerPublicParams ) private val censorshipConfiguration: Map<Int, SignalServiceConfiguration> = mapOf( COUNTRY_CODE_EGYPT to buildGConfiguration( listOf(HostConfig("https://www.google.com.eg", G_HOST, GMAIL_CONNECTION_SPEC)) + baseGHostConfigs, ), COUNTRY_CODE_UAE to buildGConfiguration( listOf(HostConfig("https://www.google.ae", G_HOST, GMAIL_CONNECTION_SPEC)) + baseGHostConfigs, ), COUNTRY_CODE_OMAN to buildGConfiguration( listOf(HostConfig("https://www.google.com.om", G_HOST, GMAIL_CONNECTION_SPEC)) + baseGHostConfigs, ), COUNTRY_CODE_QATAR to buildGConfiguration( listOf(HostConfig("https://www.google.com.qa", G_HOST, GMAIL_CONNECTION_SPEC)) + baseGHostConfigs, ), COUNTRY_CODE_UZBEKISTAN to buildGConfiguration( listOf(HostConfig("https://www.google.co.uz", G_HOST, GMAIL_CONNECTION_SPEC)) + baseGHostConfigs, ), COUNTRY_CODE_UKRAINE to buildGConfiguration( listOf(HostConfig("https://www.google.com.ua", G_HOST, GMAIL_CONNECTION_SPEC)) + baseGHostConfigs, ), COUNTRY_CODE_IRAN to fConfig, COUNTRY_CODE_CUBA to fConfig, ) private val defaultCensoredConfiguration: SignalServiceConfiguration = buildGConfiguration(baseGHostConfigs) private val defaultCensoredCountryCodes: Set<Int> = setOf( COUNTRY_CODE_EGYPT, COUNTRY_CODE_UAE, COUNTRY_CODE_OMAN, COUNTRY_CODE_QATAR, COUNTRY_CODE_IRAN, COUNTRY_CODE_CUBA, COUNTRY_CODE_UZBEKISTAN, ) open val uncensoredConfiguration: SignalServiceConfiguration = SignalServiceConfiguration( arrayOf(SignalServiceUrl(BuildConfig.SIGNAL_URL, serviceTrustStore)), mapOf( 0 to arrayOf(SignalCdnUrl(BuildConfig.SIGNAL_CDN_URL, serviceTrustStore)), 2 to arrayOf(SignalCdnUrl(BuildConfig.SIGNAL_CDN2_URL, serviceTrustStore)) ), arrayOf(SignalContactDiscoveryUrl(BuildConfig.SIGNAL_CONTACT_DISCOVERY_URL, serviceTrustStore)), arrayOf(SignalKeyBackupServiceUrl(BuildConfig.SIGNAL_KEY_BACKUP_URL, serviceTrustStore)), arrayOf(SignalStorageUrl(BuildConfig.STORAGE_URL, serviceTrustStore)), arrayOf(SignalCdsiUrl(BuildConfig.SIGNAL_CDSI_URL, serviceTrustStore)), interceptors, Optional.of(DNS), if (SignalStore.proxy().isProxyEnabled) Optional.ofNullable(SignalStore.proxy().proxy) else Optional.empty(), zkGroupServerPublicParams ) open fun getConfiguration(): SignalServiceConfiguration { return getConfiguration(SignalStore.account().e164) } open fun getConfiguration(localNumber: String?): SignalServiceConfiguration { if (localNumber == null || SignalStore.proxy().isProxyEnabled) { return uncensoredConfiguration } val countryCode: Int = PhoneNumberFormatter.getLocalCountryCode() return when (SignalStore.settings().censorshipCircumventionEnabled) { SettingsValues.CensorshipCircumventionEnabled.ENABLED -> { censorshipConfiguration[countryCode] ?: defaultCensoredConfiguration } SettingsValues.CensorshipCircumventionEnabled.DISABLED -> { uncensoredConfiguration } SettingsValues.CensorshipCircumventionEnabled.DEFAULT -> { if (defaultCensoredCountryCodes.contains(countryCode)) { censorshipConfiguration[countryCode] ?: defaultCensoredConfiguration } else { uncensoredConfiguration } } } } fun isCensored(): Boolean { return isCensored(SignalStore.account().e164) } fun isCensored(number: String?): Boolean { return getConfiguration(number) != uncensoredConfiguration } fun isCountryCodeCensoredByDefault(countryCode: Int): Boolean { return defaultCensoredCountryCodes.contains(countryCode) } private fun buildGConfiguration( hostConfigs: List<HostConfig> ): SignalServiceConfiguration { val serviceUrls: Array<SignalServiceUrl> = hostConfigs.map { SignalServiceUrl("${it.baseUrl}/service", it.host, gTrustStore, it.connectionSpec) }.toTypedArray() val cdnUrls: Array<SignalCdnUrl> = hostConfigs.map { SignalCdnUrl("${it.baseUrl}/cdn", it.host, gTrustStore, it.connectionSpec) }.toTypedArray() val cdn2Urls: Array<SignalCdnUrl> = hostConfigs.map { SignalCdnUrl("${it.baseUrl}/cdn2", it.host, gTrustStore, it.connectionSpec) }.toTypedArray() val cdsUrls: Array<SignalContactDiscoveryUrl> = hostConfigs.map { SignalContactDiscoveryUrl("${it.baseUrl}/directory", it.host, gTrustStore, it.connectionSpec) }.toTypedArray() val kbsUrls: Array<SignalKeyBackupServiceUrl> = hostConfigs.map { SignalKeyBackupServiceUrl("${it.baseUrl}/backup", it.host, gTrustStore, it.connectionSpec) }.toTypedArray() val storageUrls: Array<SignalStorageUrl> = hostConfigs.map { SignalStorageUrl("${it.baseUrl}/storage", it.host, gTrustStore, it.connectionSpec) }.toTypedArray() val cdsiUrls: Array<SignalCdsiUrl> = listOf(SignalCdsiUrl(BuildConfig.SIGNAL_CDSI_URL, serviceTrustStore)).toTypedArray() return SignalServiceConfiguration( serviceUrls, mapOf( 0 to cdnUrls, 2 to cdn2Urls ), cdsUrls, kbsUrls, storageUrls, cdsiUrls, interceptors, Optional.of(DNS), Optional.empty(), zkGroupServerPublicParams ) } private data class HostConfig(val baseUrl: String, val host: String, val connectionSpec: ConnectionSpec) }
gpl-3.0
7b8a6990ce40d7a824be31742da28196
45.652174
180
0.743996
3.797713
false
true
false
false
androidx/androidx
navigation/navigation-common/src/androidTest/java/androidx/navigation/NavGraphTest.kt
3
4175
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.google.common.truth.Truth.assertWithMessage import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.mock @SmallTest @RunWith(AndroidJUnit4::class) class NavGraphTest { private val navGraphNavigator = NavGraphNavigator(mock(NavigatorProvider::class.java)) private val navigator = NoOpNavigator() @Test fun plusAssign() { val graph = NavGraph(navGraphNavigator) val destination = navigator.createDestination().apply { id = DESTINATION_ID } graph += destination assertWithMessage("plusAssign destination should be retrieved with get") .that(graph[DESTINATION_ID]) .isSameInstanceAs(destination) } @Test fun minusAssign() { val graph = NavGraph(navGraphNavigator) val destination = navigator.createDestination().apply { id = DESTINATION_ID } graph += destination assertWithMessage("plusAssign destination should be retrieved with get") .that(graph[DESTINATION_ID]) .isSameInstanceAs(destination) graph -= destination assertWithMessage("Destination should be removed after minusAssign") .that(DESTINATION_ID in graph) .isFalse() } @Test fun plusAssignGraph() { val graph = NavGraph(navGraphNavigator) val other = NavGraph(navGraphNavigator) other += navigator.createDestination().apply { id = DESTINATION_ID } other += navigator.createDestination().apply { id = SECOND_DESTINATION_ID } graph += other assertWithMessage("NavGraph should have destination1 from other") .that(DESTINATION_ID in graph) .isTrue() assertWithMessage("other nav graph should not have destination1") .that(DESTINATION_ID in other) .isFalse() assertWithMessage("NavGraph should have destination2 from other") .that(SECOND_DESTINATION_ID in graph) .isTrue() assertWithMessage("other nav graph should not have destination2") .that(SECOND_DESTINATION_ID in other) .isFalse() } @Test fun plusAssignGraphRoute() { val graph = NavGraph(navGraphNavigator) val other = NavGraph(navGraphNavigator) other += navigator.createDestination().apply { route = DESTINATION_ROUTE } other += navigator.createDestination().apply { route = SECOND_DESTINATION_ROUTE } graph += other assertWithMessage("NavGraph should have destination1 from other") .that(DESTINATION_ROUTE in graph) .isTrue() assertWithMessage("other nav graph should not have destination1") .that(DESTINATION_ROUTE in other) .isFalse() assertWithMessage("NavGraph should have destination2 from other") .that(SECOND_DESTINATION_ROUTE in graph) .isTrue() assertWithMessage("other nav graph should not have destination2") .that(SECOND_DESTINATION_ROUTE in other) .isFalse() } @Test(expected = IllegalArgumentException::class) fun getIllegalArgumentException() { val graph = NavGraph(navGraphNavigator) graph[DESTINATION_ID] } } private const val DESTINATION_ID = 1 private const val SECOND_DESTINATION_ID = 2 private const val DESTINATION_ROUTE = "first" private const val SECOND_DESTINATION_ROUTE = "second"
apache-2.0
8c7ba77cde14fa1cbe29c123c3d7e50d
36.954545
90
0.679521
4.934988
false
true
false
false
google/ide-perf
src/main/java/com/google/idea/perf/tracer/CallTreeUtil.kt
1
2615
/* * Copyright 2020 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.idea.perf.tracer /** Encapsulates aggregate statistic for a single tracepoint. */ class TracepointStats( val tracepoint: Tracepoint, var callCount: Long = 0L, var wallTime: Long = 0L, var maxWallTime: Long = 0L ) object CallTreeUtil { /** * Computes aggregate statistics for each tracepoint, * being careful not to double-count the time spent in recursive calls. */ fun computeFlatTracepointStats(root: CallTree): List<TracepointStats> { val allStats = mutableMapOf<Tracepoint, TracepointStats>() val ancestors = mutableSetOf<Tracepoint>() fun dfs(node: CallTree) { val nonRecursive = node.tracepoint !in ancestors val stats = allStats.getOrPut(node.tracepoint) { TracepointStats(node.tracepoint) } stats.callCount += node.callCount if (nonRecursive) { stats.wallTime += node.wallTime stats.maxWallTime = maxOf(stats.maxWallTime, node.maxWallTime) ancestors.add(node.tracepoint) } for (child in node.children.values) { dfs(child) } if (nonRecursive) { ancestors.remove(node.tracepoint) } } dfs(root) assert(ancestors.isEmpty()) allStats.remove(Tracepoint.ROOT) return allStats.values.toList() } /** Estimates total tracing overhead based on call counts in the given tree. */ fun estimateTracingOverhead(root: CallTree): Long { // TODO: Can we provide a more accurate estimate (esp. for param tracing)? var tracingOverhead = 0L root.forEachNodeInSubtree { node -> tracingOverhead += when (node.tracepoint) { is MethodTracepointWithArgs -> 1024 * node.callCount // A complete guess. else -> 256 * node.callCount // See TracerIntegrationTest.testTracingOverhead. } } return tracingOverhead } }
apache-2.0
be2e09e5eec9b4ad0d2ea84d00384387
35.319444
95
0.645124
4.47774
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/translations/reference/completion.kt
1
4996
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.reference import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.translations.TranslationConstants import com.demonwav.mcdev.translations.TranslationFiles import com.demonwav.mcdev.translations.index.TranslationIndex import com.demonwav.mcdev.translations.lang.MCLangLanguage import com.demonwav.mcdev.translations.lang.gen.psi.LangTypes import com.demonwav.mcdev.util.getSimilarity import com.demonwav.mcdev.util.mcDomain import com.intellij.codeInsight.completion.CompletionContributor import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.completion.CompletionType import com.intellij.codeInsight.completion.CompletionUtil import com.intellij.codeInsight.completion.PrioritizedLookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.json.JsonElementTypes import com.intellij.json.JsonLanguage import com.intellij.json.psi.JsonStringLiteral import com.intellij.patterns.PlatformPatterns import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiUtilCore sealed class TranslationCompletionContributor : CompletionContributor() { protected fun handleKey(text: String, element: PsiElement, domain: String?, result: CompletionResultSet) { if (text.isEmpty()) { return } val defaultEntries = TranslationIndex.getAllDefaultTranslations(element.project, domain) val existingKeys = TranslationIndex.getTranslations(element.containingFile ?: return).map { it.key }.toSet() val prefixResult = result.withPrefixMatcher(text) var counter = 0 for (entry in defaultEntries) { val key = entry.key if (!key.contains(text) || existingKeys.contains(key)) { continue } if (counter++ > 1000) { break // Prevent insane CPU usage } prefixResult.addElement( PrioritizedLookupElement.withPriority( LookupElementBuilder.create(key).withIcon(PlatformAssets.MINECRAFT_ICON), 1.0 + key.getSimilarity(text) ) ) } } } class JsonCompletionContributor : TranslationCompletionContributor() { override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) { if (parameters.completionType != CompletionType.BASIC) { return } val position = parameters.position if (!PsiUtilCore.findLanguageFromElement(position).isKindOf(JsonLanguage.INSTANCE)) { return } val file = position.containingFile.originalFile.virtualFile if ( !TranslationFiles.isTranslationFile(file) || TranslationFiles.getLocale(file) == TranslationConstants.DEFAULT_LOCALE ) { return } val text = getKey(position) if (text != null) { val domain = file.mcDomain handleKey(text.substring(0, text.length - CompletionUtil.DUMMY_IDENTIFIER.length), position, domain, result) } } private tailrec fun getKey(element: PsiElement): String? { if (element.node.elementType == JsonElementTypes.DOUBLE_QUOTED_STRING) { return getKey(element.parent) } if (element is JsonStringLiteral && element.isPropertyName) { return element.value } return null } } class LangCompletionContributor : TranslationCompletionContributor() { override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) { if (parameters.completionType != CompletionType.BASIC) { return } val position = parameters.position if (!PsiUtilCore.findLanguageFromElement(position).isKindOf(MCLangLanguage)) { return } val file = position.containingFile.originalFile.virtualFile if ( !TranslationFiles.isTranslationFile(file) || TranslationFiles.getLocale(file) == TranslationConstants.DEFAULT_LOCALE ) { return } if (KEY_PATTERN.accepts(position) || DUMMY_PATTERN.accepts(position)) { val text = position.text.let { it.substring(0, it.length - CompletionUtil.DUMMY_IDENTIFIER.length) } val domain = file.mcDomain handleKey(text, position, domain, result) } } companion object { val KEY_PATTERN = PlatformPatterns.psiElement() .withElementType(PlatformPatterns.elementType().oneOf(LangTypes.KEY)) val DUMMY_PATTERN = PlatformPatterns.psiElement() .withElementType(PlatformPatterns.elementType().oneOf(LangTypes.DUMMY)) } }
mit
6668549cc24c274cf657cbeb58a648a5
35.735294
120
0.688551
5.026157
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/net/social/ActivityType.kt
1
2814
/* * Copyright (C) 2017 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.net.social import android.content.Context import org.andstatus.app.R import org.andstatus.app.net.social.ActivityType /** * Activity type in a sense of * [Activity Vocabulary](https://www.w3.org/TR/activitystreams-vocabulary/#activity-types) * and ActivityPub, see [announce-activity-inbox](https://www.w3.org/TR/activitypub/#announce-activity-inbox) */ enum class ActivityType(val id: Long, val actedResourceId: Int, val activityPubValue: String?) { ANNOUNCE(1, R.string.reblogged, "Announce"), // known also as Reblog, Repost, Retweet, Boost... CREATE(2, R.string.created, "Create"), DELETE(3, R.string.deleted, "Delete"), FOLLOW(4, R.string.followed, "Follow"), LIKE(5, R.string.liked, "Like"), UPDATE(6, R.string.updated, "Update"), UNDO_ANNOUNCE(7, R.string.undid_reblog, "Undo"), UNDO_FOLLOW(8, R.string.undid_follow, "Undo"), UNDO_LIKE(9, R.string.undid_like, "Undo"), JOIN(10, R.string.joined, "Join"), EMPTY(0, R.string.empty_in_parenthesis, "(empty)"); fun getActedTitle(context: Context?): CharSequence? { return if (actedResourceId == 0 || context == null) { name } else { context.getText(actedResourceId) } } companion object { fun undo(type: ActivityType): ActivityType { return when (type) { ActivityType.ANNOUNCE -> ActivityType.UNDO_ANNOUNCE ActivityType.FOLLOW -> ActivityType.UNDO_FOLLOW ActivityType.LIKE -> ActivityType.UNDO_LIKE else -> ActivityType.EMPTY } } /** @return the enum or [.EMPTY] */ fun fromId(id: Long): ActivityType { for (type in ActivityType.values()) { if (type.id == id) { return type } } return ActivityType.EMPTY } fun from(activityPubValue: String?): ActivityType { for (type in ActivityType.values()) { if (type.activityPubValue == activityPubValue) { return type } } return ActivityType.EMPTY } } }
apache-2.0
bf7cc354cb21375d06d182227f733810
39.782609
419
0.627932
4.060606
false
false
false
false
minecraft-dev/MinecraftDev
src/test/kotlin/platform/mixin/InvalidInjectorMethodSignatureInspectionTest.kt
1
5473
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin import com.demonwav.mcdev.framework.EdtInterceptor import com.demonwav.mcdev.platform.mixin.inspection.injector.InvalidInjectorMethodSignatureInspection import org.intellij.lang.annotations.Language import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(EdtInterceptor::class) @DisplayName("Invalid Injector Method Signature Inspection Test") class InvalidInjectorMethodSignatureInspectionTest : BaseMixinTest() { private fun doTest(@Language("JAVA") code: String) { buildProject { dir("test") { java("TestMixin.java", code) } } fixture.enableInspections(InvalidInjectorMethodSignatureInspection::class) fixture.checkHighlighting(false, false, false) } @Test @DisplayName("Redirect in constructor before superconstructor call") fun redirectInConstructorBeforeSuperconstructorCall() { doTest( """ package test; import com.demonwav.mcdev.mixintestdata.invalidInjectorMethodSignatureInspection.MixedInOuter; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(MixedInOuter.class) public class TestMixin { @Redirect(method = "<init>()V", at = @At(value = "INVOKE", target = "Lcom/demonwav/mcdev/mixintestdata/invalidInjectorMethodSignatureInspection/MixedInOuter;method1()Ljava/lang/String;")) private String <error descr="Method must be static">redirectMethod1</error>() { return null; } @Redirect(method = "<init>()V", at = @At(value = "INVOKE", target = "Lcom/demonwav/mcdev/mixintestdata/invalidInjectorMethodSignatureInspection/MixedInOuter;method2()V")) private void redirectMethod2() { } } """ ) } @Test @DisplayName("Inner Ctor @Inject Parameters") fun innerCtorInjectParameters() { doTest( """ package test; import com.demonwav.mcdev.mixintestdata.invalidInjectorMethodSignatureInspection.MixedInOuter; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(MixedInOuter.MixedInInner.class) public class TestMixin { @Inject(method = "<init>(Lcom/demonwav/mcdev/mixintestdata/invalidInjectorMethodSignatureInspection/MixedInOuter;)V", at = @At("RETURN")) private void injectCtor(MixedInOuter outer, CallbackInfo ci) { } @Inject(method = "<init>", at = @At("RETURN")) private void injectCtor(CallbackInfo ci) { } @Inject(method = "<init>(Lcom/demonwav/mcdev/mixintestdata/invalidInjectorMethodSignatureInspection/MixedInOuter;Ljava/lang/String;)V", at = @At("RETURN")) private void injectCtor(MixedInOuter outer, String string, CallbackInfo ci) { } @Inject(method = "<init>(Lcom/demonwav/mcdev/mixintestdata/invalidInjectorMethodSignatureInspection/MixedInOuter;Ljava/lang/String;)V", at = @At("RETURN")) private void injectCtor<error descr="Method parameters do not match expected parameters for Inject">(String string, CallbackInfo ci)</error> { } } """ ) } @Test @DisplayName("Static Inner Ctor @Inject Parameters") fun staticInnerCtorInjectParameters() { doTest( """ package test; import com.demonwav.mcdev.mixintestdata.invalidInjectorMethodSignatureInspection.MixedInOuter; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(MixedInOuter.MixedInStaticInner.class) public class TestMixin { @Inject(method = "<init>()V", at = @At("RETURN")) private void injectCtorWrong<error descr="Method parameters do not match expected parameters for Inject">(MixedInOuter outer, CallbackInfo ci)</error> { } @Inject(method = "<init>", at = @At("RETURN")) private void injectCtor(CallbackInfo ci) { } @Inject(method = "<init>(Ljava/lang/String;)V", at = @At("RETURN")) private void injectCtor<error descr="Method parameters do not match expected parameters for Inject">(MixedInOuter outer, String string, CallbackInfo ci)</error> { } @Inject(method = "<init>(Ljava/lang/String;)V", at = @At("RETURN")) private void injectCtor(String string, CallbackInfo ci) { } } """ ) } }
mit
f7c86f77b3562ae3d55d6cb617f4723c
40.150376
203
0.628175
4.860568
false
true
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/AGroupedImageListQuestAnswerFragment.kt
1
4442
package de.westnordost.streetcomplete.quests import android.content.Context import android.os.Bundle import android.preference.PreferenceManager import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import android.view.View import androidx.core.view.postDelayed import javax.inject.Inject import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.view.GroupedImageSelectAdapter import de.westnordost.streetcomplete.view.Item import kotlinx.android.synthetic.main.fragment_quest_answer.* import kotlinx.android.synthetic.main.quest_generic_list.* import java.util.* /** * Abstract class for quests with a grouped list of images and one to select. * * Saving and restoring state is not implemented */ abstract class AGroupedImageListQuestAnswerFragment<I,T> : AbstractQuestFormAnswerFragment<T>() { override val contentLayoutResId = R.layout.quest_generic_list protected lateinit var imageSelector: GroupedImageSelectAdapter<I> protected abstract val allItems: List<Item<I>> protected abstract val topItems: List<Item<I>> @Inject internal lateinit var favs: LastPickedValuesStore<I> private val selectedItem get() = imageSelector.selectedItem protected open val itemsPerRow = 3 override fun onAttach(ctx: Context) { super.onAttach(ctx) favs = LastPickedValuesStore(PreferenceManager.getDefaultSharedPreferences(ctx.applicationContext)) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) imageSelector = GroupedImageSelectAdapter(GridLayoutManager(activity, itemsPerRow)) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) list.layoutManager = imageSelector.gridLayoutManager list.isNestedScrollingEnabled = false showMoreButton.setOnClickListener { imageSelector.items = allItems showMoreButton.visibility = View.GONE } selectHintLabel.setText(R.string.quest_select_hint_most_specific) imageSelector.listeners.add { checkIsFormComplete() } imageSelector.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() { override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { super.onItemRangeInserted(positionStart, itemCount) scrollTo(positionStart) } }) checkIsFormComplete() imageSelector.items = getInitialItems() list.adapter = imageSelector } private fun scrollTo(index: Int) { val item = imageSelector.gridLayoutManager.getChildAt(Math.max(0, index - 1)) if (item != null) { val itemPos = IntArray(2) item.getLocationInWindow(itemPos) val scrollViewPos = IntArray(2) scrollView.getLocationInWindow(scrollViewPos) scrollView.postDelayed(250) { scrollView.smoothScrollTo(0, itemPos[1] - scrollViewPos[1]) } } } private fun getInitialItems(): List<Item<I>> { val items = LinkedList(topItems) favs.moveLastPickedToFront(javaClass.simpleName, items, allItems) return items } override fun onClickOk() { val item = selectedItem!! val itemValue = item.value if (itemValue == null) { AlertDialog.Builder(context!!) .setMessage(R.string.quest_generic_item_invalid_value) .setPositiveButton(R.string.ok, null) .show() } else { if (item.isGroup) { AlertDialog.Builder(context!!) .setMessage(R.string.quest_generic_item_confirmation) .setNegativeButton(R.string.quest_generic_confirmation_no, null) .setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> favs.add(javaClass.simpleName, itemValue) onClickOk(item.value) } .show() } else { favs.add(javaClass.simpleName, itemValue) onClickOk(item.value) } } } abstract fun onClickOk(value: I) override fun isFormComplete() = selectedItem != null }
gpl-3.0
9671c6aa1c362e28c0bb7706f0ad33b3
33.976378
107
0.669518
5.059226
false
false
false
false
btimofeev/UniPatcher
app/src/main/java/org/emunix/unipatcher/ui/fragment/SnesSmcHeaderFragment.kt
1
5091
/* Copyright (C) 2014, 2020-2022 Boris Timofeev This file is part of UniPatcher. UniPatcher 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. UniPatcher 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 UniPatcher. If not, see <http://www.gnu.org/licenses/>. */ package org.emunix.unipatcher.ui.fragment import android.content.ActivityNotFoundException import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.core.view.isVisible import androidx.fragment.app.viewModels import dagger.hilt.android.AndroidEntryPoint import org.emunix.unipatcher.MIME_TYPE_ALL_FILES import org.emunix.unipatcher.MIME_TYPE_OCTET_STREAM import org.emunix.unipatcher.R import org.emunix.unipatcher.databinding.SnesSmcHeaderFragmentBinding import org.emunix.unipatcher.utils.registerActivityResult import org.emunix.unipatcher.viewmodels.ActionIsRunningViewModel import org.emunix.unipatcher.viewmodels.SnesSmcHeaderViewModel @AndroidEntryPoint class SnesSmcHeaderFragment : ActionFragment(), View.OnClickListener { private val viewModel by viewModels<SnesSmcHeaderViewModel>() private val actionIsRunningViewModel by viewModels<ActionIsRunningViewModel>() private lateinit var activityRomFile: ActivityResultLauncher<Intent> private lateinit var activityOutputFile: ActivityResultLauncher<Intent> private var _binding: SnesSmcHeaderFragmentBinding? = null private val binding get() = _binding!! private var suggestedOutputName: String = "headerless_rom.smc" override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = SnesSmcHeaderFragmentBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) activity?.setTitle(R.string.nav_snes_add_del_smc_header) activityRomFile = registerActivityResult(viewModel::romSelected) activityOutputFile = registerActivityResult(viewModel::outputSelected) viewModel.getRomName().observe(viewLifecycleOwner) { binding.romNameTextView.text = it } viewModel.getOutputName().observe(viewLifecycleOwner) { binding.outputNameTextView.text = it } viewModel.getSuggestedOutputName().observe(viewLifecycleOwner) { suggestedOutputName = it } viewModel.getMessage().observe(viewLifecycleOwner) { event -> event.getContentIfNotHandled()?.let { message -> Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show() } } viewModel.getInfoText().observe(viewLifecycleOwner) { text -> binding.headerInfoTextView.text = text } viewModel.getActionIsRunning().observe(viewLifecycleOwner) { isRunning -> actionIsRunningViewModel.removeSmc(isRunning) binding.progressBar.isVisible = isRunning } binding.romCardView.setOnClickListener(this) binding.outputCardView.setOnClickListener(this) } override fun onClick(view: View) { when (view.id) { R.id.romCardView -> { val intent = Intent(Intent.ACTION_GET_CONTENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = MIME_TYPE_ALL_FILES } try { activityRomFile.launch(intent) } catch (e: ActivityNotFoundException) { Toast.makeText(requireContext(), R.string.error_file_picker_app_is_no_installed, Toast.LENGTH_SHORT).show() } } R.id.outputCardView -> { val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = MIME_TYPE_OCTET_STREAM putExtra(Intent.EXTRA_TITLE, suggestedOutputName) } try { activityOutputFile.launch(intent) } catch (e: ActivityNotFoundException) { Toast.makeText(requireContext(), R.string.error_file_picker_app_is_no_installed, Toast.LENGTH_SHORT).show() } } } } override fun runAction(){ viewModel.runActionClicked() } }
gpl-3.0
622b336c14b95bd0fed941b485fb32b4
38.78125
127
0.692791
4.798303
false
false
false
false
andrewvora/historian
app/src/androidTest/java/com/andrewvora/apps/historian/InstrumentedTest.kt
1
3395
package com.andrewvora.apps.historian import android.support.test.espresso.Espresso.onView import android.support.test.espresso.PerformException import android.support.test.espresso.UiController import android.support.test.espresso.ViewAction import android.support.test.espresso.assertion.ViewAssertions.matches import android.support.test.espresso.matcher.ViewMatchers import android.support.test.espresso.matcher.ViewMatchers.isDisplayed import android.support.test.espresso.matcher.ViewMatchers.isRoot import android.support.test.espresso.util.HumanReadables import android.support.test.espresso.util.TreeIterables import android.support.test.runner.AndroidJUnit4 import android.support.v7.widget.RecyclerView import android.view.View import org.hamcrest.BaseMatcher import org.hamcrest.Description import org.hamcrest.Matcher import org.junit.After import org.junit.Before import org.junit.runner.RunWith import java.util.concurrent.TimeoutException /** * Created on 7/28/2017. * @author Andrew Vorakrajangthiti */ @RunWith(AndroidJUnit4::class) abstract class InstrumentedTest { @Before abstract fun setup() @After abstract fun tearDown() fun sleep(milliseconds: Long) { try { Thread.sleep(milliseconds) } catch (e: Exception) { e.printStackTrace() } } fun getRecyclerViewAdapterCount(): Int { var itemCount = 0 onView(object : BaseMatcher<View>() { override fun matches(item: Any?): Boolean { if (item is RecyclerView) { itemCount = item.adapter.itemCount return true } return false } override fun describeMismatch(item: Any?, mismatchDescription: Description?) {} override fun describeTo(description: Description?) {} }).check(matches(isDisplayed())) return itemCount } fun waitForId(viewId: Int, millis: Long): ViewAction { return object : ViewAction { override fun getConstraints(): Matcher<View> { return isRoot() } override fun getDescription(): String { return "wait for a specific view with id <$viewId> during $millis millis." } override fun perform(uiController: UiController, view: View) { uiController.loopMainThreadUntilIdle() val startTime = System.currentTimeMillis() val endTime = startTime + millis val viewMatcher = ViewMatchers.withId(viewId) do { TreeIterables.breadthFirstViewTraversal(view) .filter { // found view with required ID viewMatcher.matches(it) } .forEach { return } uiController.loopMainThreadForAtLeast(50) } while (System.currentTimeMillis() < endTime) // timeout happens throw PerformException.Builder() .withActionDescription(this.description) .withViewDescription(HumanReadables.describe(view)) .withCause(TimeoutException()) .build() } } } }
mit
3f85395b0404f561d9836eb061eebc8b
32.294118
91
0.6162
5.279938
false
true
false
false
grenzfrequence/showMyCar
app/src/main/java/com/grenzfrequence/showmycar/common/recycler_binding_adapter/EndlessRecyclerViewScrollListener.kt
1
4614
package com.grenzfrequence.showmycar.common.recycler_binding_adapter import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.StaggeredGridLayoutManager /** * Created by grenzfrequence on 25/03/17. */ abstract class EndlessRecyclerViewScrollListener : RecyclerView.OnScrollListener { // The minimum amount of items to have below your current scroll position // before loading more. private var visibleThreshold = 5 // The current offset index of data you have loaded private var currentPage = 0 // The total number of items in the dataset after the last load private var previousTotalItemCount = 0 // True if we are still waiting for the last set of data to load. private var loading = true // Sets the starting page index private val startingPageIndex = 0 internal var mLayoutManager: RecyclerView.LayoutManager constructor(layoutManager: LinearLayoutManager) { this.mLayoutManager = layoutManager } constructor(layoutManager: GridLayoutManager) { this.mLayoutManager = layoutManager visibleThreshold = visibleThreshold * layoutManager.spanCount } constructor(layoutManager: StaggeredGridLayoutManager) { this.mLayoutManager = layoutManager visibleThreshold = visibleThreshold * layoutManager.spanCount } fun getLastVisibleItem(lastVisibleItemPositions: IntArray): Int { var maxSize = 0 for (i in lastVisibleItemPositions.indices) { if (i == 0) { maxSize = lastVisibleItemPositions[i] } else if (lastVisibleItemPositions[i] > maxSize) { maxSize = lastVisibleItemPositions[i] } } return maxSize } // This happens many times a second during a scroll, so be wary of the code you place here. // We are given a few useful parameters to help us work out if we need to load some more data, // but first we check if we are waiting for the previous load to finish. override fun onScrolled(view: RecyclerView, dx: Int, dy: Int) { var lastVisibleItemPosition = 0 val totalItemCount = mLayoutManager.itemCount if (mLayoutManager is StaggeredGridLayoutManager) { val lastVisibleItemPositions = (mLayoutManager as StaggeredGridLayoutManager).findLastVisibleItemPositions(null) // get maximum element within the list lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions) } else if (mLayoutManager is GridLayoutManager) { lastVisibleItemPosition = (mLayoutManager as GridLayoutManager).findLastVisibleItemPosition() } else if (mLayoutManager is LinearLayoutManager) { lastVisibleItemPosition = (mLayoutManager as LinearLayoutManager).findLastVisibleItemPosition() } // If the total item count is zero and the previous isn't, assume the // list is invalidated and should be reset back to initial state if (totalItemCount < previousTotalItemCount) { this.currentPage = this.startingPageIndex this.previousTotalItemCount = totalItemCount if (totalItemCount == 0) { this.loading = true } } // If it’s still loading, we check to see if the dataset count has // changed, if so we conclude it has finished loading and update the current page // number and total item count. if (loading && totalItemCount > previousTotalItemCount) { loading = false previousTotalItemCount = totalItemCount } // If it isn’t currently loading, we check to see if we have breached // the visibleThreshold and need to reload more data. // If we do need to reload some more data, we execute onLoadMore to fetch the data. // threshold should reflect how many total columns there are too if (!loading && lastVisibleItemPosition + visibleThreshold > totalItemCount) { currentPage++ onLoadMore(currentPage, totalItemCount, view) loading = true } } // Call this method whenever performing new searches fun resetState() { this.currentPage = this.startingPageIndex this.previousTotalItemCount = 0 this.loading = true } // Defines the process for actually loading more data based on page abstract fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView) }
mit
132b1cfa21e3f8009d3c9badab220066
41.685185
124
0.690889
5.540865
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt
1
8079
package info.nightscout.androidaps.plugins.general.maintenance import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import dagger.android.support.DaggerFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.SingleFragmentActivity import info.nightscout.androidaps.dana.database.DanaHistoryDatabase import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.databinding.MaintenanceFragmentBinding import info.nightscout.androidaps.diaconn.database.DiaconnHistoryDatabase import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.extensions.toVisibility import info.nightscout.androidaps.insight.database.InsightDatabase import info.nightscout.androidaps.interfaces.DataSyncSelector import info.nightscout.androidaps.interfaces.ImportExportPrefs import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.maintenance.activities.LogSettingActivity import info.nightscout.androidaps.plugins.general.overview.OverviewData import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.DashHistoryDatabase import info.nightscout.androidaps.plugins.pump.omnipod.eros.history.database.ErosHistoryDatabase import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.PREFERENCES import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.rxjava3.core.Completable.fromAction import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.subscribeBy import javax.inject.Inject class MaintenanceFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var maintenancePlugin: MaintenancePlugin @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper @Inject lateinit var importExportPrefs: ImportExportPrefs @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var repository: AppRepository @Inject lateinit var danaHistoryDatabase: DanaHistoryDatabase @Inject lateinit var insightDatabase: InsightDatabase @Inject lateinit var diaconnDatabase: DiaconnHistoryDatabase @Inject lateinit var erosDatabase: ErosHistoryDatabase @Inject lateinit var dashDatabase: DashHistoryDatabase @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var uel: UserEntryLogger @Inject lateinit var dataSyncSelector: DataSyncSelector @Inject lateinit var pumpSync: PumpSync @Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var overviewData: OverviewData private val compositeDisposable = CompositeDisposable() private var inMenu = false private var queryingProtection = false private var _binding: MaintenanceFragmentBinding? = null // This property is only valid between onCreateView and onDestroyView. private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = MaintenanceFragmentBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val parentClass = this.activity?.let { it::class.java } inMenu = parentClass == SingleFragmentActivity::class.java updateProtectedUi() binding.logSend.setOnClickListener { maintenancePlugin.sendLogs() } binding.logDelete.setOnClickListener { uel.log(Action.DELETE_LOGS, Sources.Maintenance) Thread { maintenancePlugin.deleteLogs(5) }.start() } binding.navResetdb.setOnClickListener { activity?.let { activity -> OKDialog.showConfirmation(activity, rh.gs(R.string.maintenance), rh.gs(R.string.reset_db_confirm), Runnable { compositeDisposable.add( fromAction { repository.clearDatabases() danaHistoryDatabase.clearAllTables() insightDatabase.clearAllTables() diaconnDatabase.clearAllTables() erosDatabase.clearAllTables() dashDatabase.clearAllTables() dataSyncSelector.resetToNextFullSync() pumpSync.connectNewPump() overviewData.reset() iobCobCalculator.ads.reset() iobCobCalculator.clearCache() } .subscribeOn(aapsSchedulers.io) .subscribeBy( onError = { aapsLogger.error("Error clearing databases", it) }, onComplete = { rxBus.send(EventPreferenceChange(rh, R.string.key_units)) } ) ) uel.log(Action.RESET_DATABASES, Sources.Maintenance) }) } } binding.navExport.setOnClickListener { uel.log(Action.EXPORT_SETTINGS, Sources.Maintenance) // start activity for checking permissions... importExportPrefs.verifyStoragePermissions(this) { importExportPrefs.exportSharedPreferences(this) } } binding.navImport.setOnClickListener { uel.log(Action.IMPORT_SETTINGS, Sources.Maintenance) // start activity for checking permissions... importExportPrefs.verifyStoragePermissions(this) { importExportPrefs.importSharedPreferences(this) } } binding.navLogsettings.setOnClickListener { startActivity(Intent(activity, LogSettingActivity::class.java)) } binding.exportCsv.setOnClickListener { activity?.let { activity -> OKDialog.showConfirmation(activity, rh.gs(R.string.ue_export_to_csv) + "?") { uel.log(Action.EXPORT_CSV, Sources.Maintenance) importExportPrefs.exportUserEntriesCsv(activity) } } } binding.unlock.setOnClickListener { queryProtection() } } override fun onResume() { super.onResume() if (inMenu) queryProtection() else updateProtectedUi() } @Synchronized override fun onDestroyView() { super.onDestroyView() compositeDisposable.clear() _binding = null } private fun updateProtectedUi() { val isLocked = protectionCheck.isLocked(PREFERENCES) binding.mainLayout.visibility = isLocked.not().toVisibility() binding.unlock.visibility = isLocked.toVisibility() } private fun queryProtection() { val isLocked = protectionCheck.isLocked(PREFERENCES) if (isLocked && !queryingProtection) { activity?.let { activity -> queryingProtection = true val doUpdate = { activity.runOnUiThread { queryingProtection = false; updateProtectedUi() } } protectionCheck.queryProtection(activity, PREFERENCES, doUpdate, doUpdate, doUpdate) } } } }
agpl-3.0
f2c193bf571a7fb6156abad58db08e99
46.245614
125
0.692908
5.368106
false
false
false
false
Turbo87/intellij-rust
src/main/kotlin/org/rust/ide/template/RustContextType.kt
1
1499
package org.rust.ide.template import com.intellij.codeInsight.template.EverywhereContextType import com.intellij.codeInsight.template.TemplateContextType import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtilCore import org.rust.lang.RustLanguage import org.rust.lang.core.psi.RustStructItem sealed class RustContextType(id: String, presentableName: String, parentContext: Class<out TemplateContextType>) : TemplateContextType(id, presentableName, parentContext) { final override fun isInContext(file: PsiFile, offset: Int): Boolean { if (!PsiUtilCore.getLanguageAtOffset(file, offset).isKindOf(RustLanguage)) { return false } val element = file.findElementAt(offset) return element != null && isInContextImpl(element) } abstract protected fun isInContextImpl(element: PsiElement): Boolean class Generic : RustContextType("RUST_FILE", "Rust", EverywhereContextType::class.java) { override fun isInContextImpl(element: PsiElement): Boolean = true } class Struct : RustContextType("RUST_STRUCT", "Structure", Generic::class.java) { override fun isInContextImpl(element: PsiElement): Boolean = // Structs can't be nested or contain other expressions, // so it is ok to look for any Struct ancestor. PsiTreeUtil.getParentOfType(element, RustStructItem::class.java) != null } }
mit
5aaf8fa8c36d2147e0c3bfc0ca255c51
39.513514
112
0.737158
4.626543
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/mediapicker/MediaThumbnailViewUtils.kt
1
7009
package org.wordpress.android.ui.mediapicker import android.view.View import android.widget.ImageView import android.widget.TextView import org.wordpress.android.R import org.wordpress.android.ui.mediapicker.MediaPickerUiItem.ClickAction import org.wordpress.android.ui.mediapicker.MediaPickerUiItem.ToggleAction import org.wordpress.android.util.AccessibilityUtils import org.wordpress.android.util.AniUtils import org.wordpress.android.util.AniUtils.Duration.SHORT import org.wordpress.android.util.ColorUtils.setImageResourceWithTint import org.wordpress.android.util.PhotoPickerUtils import org.wordpress.android.util.ViewUtils import org.wordpress.android.util.WPMediaUtils import org.wordpress.android.util.image.ImageManager import org.wordpress.android.util.extensions.redirectContextClickToLongPressListener import java.util.Locale class MediaThumbnailViewUtils(val imageManager: ImageManager) { @Suppress("LongParameterList") fun setupListeners( imgThumbnail: ImageView, isVideo: Boolean, isSelected: Boolean, toggleAction: ToggleAction, clickAction: ClickAction, animateSelection: Boolean ) { addImageSelectedToAccessibilityFocusedEvent(imgThumbnail, isSelected) imgThumbnail.setOnClickListener { toggleAction.toggle() PhotoPickerUtils.announceSelectedMediaForAccessibility( imgThumbnail, isVideo, !isSelected ) } imgThumbnail.setOnLongClickListener { clickAction.click() true } imgThumbnail.redirectContextClickToLongPressListener() displaySelection(animateSelection, isSelected, imgThumbnail) } @Suppress("LongParameterList") fun setupFileImageView( container: View, imgThumbnail: ImageView, fileName: String, isSelected: Boolean, clickAction: ClickAction, toggleAction: ToggleAction, animateSelection: Boolean ) { imageManager.cancelRequestAndClearImageView(imgThumbnail) // not an image or video, so show file name and file type val placeholderResId = WPMediaUtils.getPlaceholder(fileName) setImageResourceWithTint( imgThumbnail, placeholderResId, R.color.neutral_30 ) addImageSelectedToAccessibilityFocusedEvent(imgThumbnail, isSelected) container.setOnClickListener { toggleAction.toggle() PhotoPickerUtils.announceSelectedMediaForAccessibility( imgThumbnail, false, !isSelected ) } container.setOnLongClickListener { clickAction.click() true } container.redirectContextClickToLongPressListener() displaySelection(animateSelection, isSelected, container) } private fun addImageSelectedToAccessibilityFocusedEvent( imageView: ImageView, isSelected: Boolean ) { AccessibilityUtils.addPopulateAccessibilityEventFocusedListener( imageView ) { val imageSelectedText = imageView.context .getString(R.string.photo_picker_image_selected) if (isSelected) { if (!imageView.contentDescription.toString().contains(imageSelectedText)) { imageView.contentDescription = ("${imageView.contentDescription} $imageSelectedText") } } else { imageView.contentDescription = imageView.contentDescription .toString().replace( imageSelectedText, "" ) } } } private fun displaySelection(animate: Boolean, isSelected: Boolean, view: View) { if (animate) { if (isSelected) { AniUtils.scale( view, SCALE_NORMAL, SCALE_SELECTED, ANI_DURATION ) } else { AniUtils.scale( view, SCALE_SELECTED, SCALE_NORMAL, ANI_DURATION ) } } else { val scale = if (isSelected) SCALE_SELECTED else SCALE_NORMAL if (view.scaleX != scale) { view.scaleX = scale view.scaleY = scale } } } fun displayTextSelectionCount( animate: Boolean, showOrderCounter: Boolean, isSelected: Boolean, txtSelectionCount: TextView ) { if (animate) { when { showOrderCounter -> { AniUtils.startAnimation( txtSelectionCount, R.anim.pop ) } isSelected -> { AniUtils.fadeIn( txtSelectionCount, ANI_DURATION ) } else -> { AniUtils.fadeOut( txtSelectionCount, ANI_DURATION ) } } } else { txtSelectionCount.visibility = if (showOrderCounter || isSelected) View.VISIBLE else View.GONE } } fun updateSelectionCountForPosition( txtSelectionCount: TextView, selectedOrder: Int? ) { if (selectedOrder != null) { txtSelectionCount.text = String.format(Locale.getDefault(), "%d", selectedOrder) } else { txtSelectionCount.text = null } } fun setupTextSelectionCount( txtSelectionCount: TextView, isSelected: Boolean, selectedOrder: Int?, showOrderCounter: Boolean, animateSelection: Boolean ) { ViewUtils.addCircularShadowOutline( txtSelectionCount ) txtSelectionCount.isSelected = isSelected updateSelectionCountForPosition(txtSelectionCount, selectedOrder) if (!showOrderCounter) { txtSelectionCount.setBackgroundResource(R.drawable.media_picker_circle_pressed) } displayTextSelectionCount( animateSelection, showOrderCounter, isSelected, txtSelectionCount ) } fun setupVideoOverlay(videoOverlay: ImageView, clickAction: ClickAction) { videoOverlay.visibility = View.VISIBLE videoOverlay.setOnClickListener { clickAction.click() } } companion object { private const val SCALE_NORMAL = 1.0f private const val SCALE_SELECTED = .8f private val ANI_DURATION = SHORT } }
gpl-2.0
375826446133aa97b05fea5656ec42c5
32.697115
106
0.578257
5.62069
false
false
false
false
Turbo87/intellij-rust
src/test/kotlin/org/rust/lang/core/parser/RustCompleteParsingTestCase.kt
1
1365
package org.rust.lang.core.parser import com.intellij.psi.PsiFile import org.assertj.core.api.Assertions.assertThat class RustCompleteParsingTestCase : RustParsingTestCaseBase("well-formed") { override fun checkResult(targetDataName: String?, file: PsiFile?) { assertThat(hasError(file!!)) .withFailMessage("Error in well formed file ${file.name}") .isFalse() super.checkResult(targetDataName, file) } // @formatter:off fun testFn() = doTest(true) fun testExpr() = doTest(true) fun testMod() = doTest(true) fun testUseItem() = doTest(true) fun testType() = doTest(true) fun testShifts() = doTest(true) fun testPatterns() = doTest(true) fun testAttributes() = doTest(true) fun testTraits() = doTest(true) fun testMacros() = doTest(true) fun testImpls() = doTest(true) fun testSuper() = doTest(true) fun testRanges() = doTest(true) fun testExternCrates() = doTest(true) fun testExternFns() = doTest(true) fun testSuperPaths() = doTest(true) fun testPrecedence() = doTest(true) // @formatter:on }
mit
d235a828ba696f9c31ae543e32d1d8ef
40.363636
76
0.547985
4.50495
false
true
false
false
NativeScript/android-runtime
test-app/build-tools/android-metadata-generator/src/src/com/telerik/metadata/parsing/kotlin/extensions/bytecode/KotlinExtensionFunctionBytecodeDescriptor.kt
1
1781
package com.telerik.metadata.parsing.kotlin.extensions.bytecode import com.telerik.metadata.parsing.MetadataInfoAnnotationDescriptor import com.telerik.metadata.parsing.kotlin.extensions.KotlinExtensionFunctionDescriptor import com.telerik.metadata.parsing.kotlin.methods.KotlinMethodDescriptor class KotlinExtensionFunctionBytecodeDescriptor(private val kotlinMethodDescriptor: KotlinMethodDescriptor) : KotlinExtensionFunctionDescriptor { override val isSynthetic = kotlinMethodDescriptor.isSynthetic override val isStatic = kotlinMethodDescriptor.isStatic override val isAbstract = kotlinMethodDescriptor.isAbstract override val declaringClass = kotlinMethodDescriptor.declaringClass override val name = kotlinMethodDescriptor.name override val signature = kotlinMethodDescriptor.signature override val argumentTypes = kotlinMethodDescriptor.argumentTypes override val returnType = kotlinMethodDescriptor.returnType override val metadataInfoAnnotation: MetadataInfoAnnotationDescriptor? = null override val isPublic = kotlinMethodDescriptor.isPublic override val isInternal = kotlinMethodDescriptor.isInternal override val isProtected = kotlinMethodDescriptor.isProtected override val isPackagePrivate = kotlinMethodDescriptor.isPackagePrivate override val isPrivate = kotlinMethodDescriptor.isPrivate override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val that = other as KotlinExtensionFunctionBytecodeDescriptor? return kotlinMethodDescriptor == that!!.kotlinMethodDescriptor } override fun hashCode(): Int { return kotlinMethodDescriptor.hashCode() } }
apache-2.0
c6146eb28ef3ae5d24e4c2695fd52be3
35.346939
145
0.801235
6.249123
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/contributors/FirCompletionContributorBase.kt
1
10029
// 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.completion.contributors import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.completion.PrefixMatcher import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementDecorator import com.intellij.codeInsight.lookup.LookupElementPresentation import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.scopes.KtScopeNameFilter import org.jetbrains.kotlin.analysis.api.symbols.* import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol import org.jetbrains.kotlin.analysis.api.types.KtSubstitutor import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.idea.base.analysis.api.utils.KtSymbolFromIndexProvider import org.jetbrains.kotlin.idea.completion.ItemPriority import org.jetbrains.kotlin.idea.completion.LookupElementFactory import org.jetbrains.kotlin.idea.completion.LookupElementSink import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext import org.jetbrains.kotlin.idea.completion.context.FirRawPositionCompletionContext import org.jetbrains.kotlin.idea.completion.contributors.helpers.CallableMetadataProvider import org.jetbrains.kotlin.idea.completion.contributors.helpers.CallableMetadataProvider.getCallableMetadata import org.jetbrains.kotlin.idea.completion.lookups.CallableInsertionOptions import org.jetbrains.kotlin.idea.completion.lookups.ImportStrategy import org.jetbrains.kotlin.idea.completion.lookups.detectImportStrategy import org.jetbrains.kotlin.idea.completion.lookups.factories.KotlinFirLookupElementFactory import org.jetbrains.kotlin.idea.completion.priority import org.jetbrains.kotlin.idea.completion.weighers.Weighers import org.jetbrains.kotlin.idea.completion.weighers.WeighingContext import org.jetbrains.kotlin.idea.fir.HLIndexHelper import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.deprecation.DeprecationLevelValue internal class FirCompletionContributorOptions( val priority: Int = 0 ) { companion object { val DEFAULT = FirCompletionContributorOptions() } } internal abstract class FirCompletionContributorBase<C : FirRawPositionCompletionContext>( protected val basicContext: FirBasicCompletionContext, options: FirCompletionContributorOptions, ) { constructor(basicContext: FirBasicCompletionContext, priority: Int) : this(basicContext, FirCompletionContributorOptions(priority)) protected val prefixMatcher: PrefixMatcher get() = basicContext.prefixMatcher protected val parameters: CompletionParameters get() = basicContext.parameters protected val sink: LookupElementSink = basicContext.sink.withPriority(options.priority) protected val originalKtFile: KtFile get() = basicContext.originalKtFile protected val fakeKtFile: KtFile get() = basicContext.fakeKtFile protected val project: Project get() = basicContext.project protected val targetPlatform: TargetPlatform get() = basicContext.targetPlatform protected val indexHelper: HLIndexHelper get() = basicContext.indexHelper protected val symbolFromIndexProvider: KtSymbolFromIndexProvider get() = basicContext.symbolFromIndexProvider protected val lookupElementFactory: KotlinFirLookupElementFactory get() = basicContext.lookupElementFactory protected val visibleScope = basicContext.visibleScope protected val scopeNameFilter: KtScopeNameFilter = { name -> !name.isSpecial && prefixMatcher.prefixMatches(name.identifier) } abstract fun KtAnalysisSession.complete(positionContext: C) protected fun KtAnalysisSession.addSymbolToCompletion(expectedType: KtType?, symbol: KtSymbol) { if (symbol !is KtNamedSymbol) return // Don't offer any hidden deprecated items. if (symbol.deprecationStatus?.deprecationLevel == DeprecationLevelValue.HIDDEN) return with(lookupElementFactory) { createLookupElement(symbol) .let(sink::addElement) } } protected fun KtAnalysisSession.addClassifierSymbolToCompletion( symbol: KtClassifierSymbol, context: WeighingContext, importingStrategy: ImportStrategy = detectImportStrategy(symbol), ) { if (symbol !is KtNamedSymbol) return // Don't offer any deprecated items that could leads to compile errors. if (symbol.deprecationStatus?.deprecationLevel == DeprecationLevelValue.HIDDEN) return val lookup = with(lookupElementFactory) { when (symbol) { is KtClassLikeSymbol -> createLookupElementForClassLikeSymbol(symbol, importingStrategy) is KtTypeParameterSymbol -> createLookupElement(symbol) } } ?: return lookup.availableWithoutImport = importingStrategy == ImportStrategy.DoNothing applyWeighers(context, lookup, symbol, KtSubstitutor.Empty(token)) sink.addElement(lookup) } protected fun KtAnalysisSession.addCallableSymbolToCompletion( context: WeighingContext, symbol: KtCallableSymbol, options: CallableInsertionOptions, substitutor: KtSubstitutor = KtSubstitutor.Empty(token), priority: ItemPriority? = null, explicitReceiverTypeHint: KtType? = null, ) { if (symbol !is KtNamedSymbol) return // Don't offer any deprecated items that could leads to compile errors. if (symbol.deprecationStatus?.deprecationLevel == DeprecationLevelValue.HIDDEN) return val lookup = with(lookupElementFactory) { createCallableLookupElement(symbol, options, substitutor) } priority?.let { lookup.priority = it } lookup.callableWeight = getCallableMetadata(context, symbol, substitutor) applyWeighers(context, lookup, symbol, substitutor) sink.addElement(lookup.adaptToReceiver(context, explicitReceiverTypeHint?.render())) } private fun LookupElement.adaptToReceiver(weigherContext: WeighingContext, explicitReceiverTypeHint: String?): LookupElement { val explicitReceiverRange = weigherContext.explicitReceiver?.textRange val explicitReceiverText = weigherContext.explicitReceiver?.text return when (val kind = callableWeight?.kind) { // Make the text bold if it's immediate member of the receiver CallableMetadataProvider.CallableKind.ThisClassMember, CallableMetadataProvider.CallableKind.ThisTypeExtension -> object : LookupElementDecorator<LookupElement>(this) { override fun renderElement(presentation: LookupElementPresentation) { super.renderElement(presentation) presentation.isItemTextBold = true } } // TODO this code should be uncommented when KTIJ-20913 is fixed //// Make the text gray and insert type cast if the receiver type does not match. //is CallableMetadataProvider.CallableKind.ReceiverCastRequired -> object : LookupElementDecorator<LookupElement>(this) { // override fun renderElement(presentation: LookupElementPresentation) { // super.renderElement(presentation) // presentation.itemTextForeground = LookupElementFactory.CAST_REQUIRED_COLOR // // gray all tail fragments too: // val fragments = presentation.tailFragments // presentation.clearTail() // for (fragment in fragments) { // presentation.appendTailText(fragment.text, true) // } // } // // override fun handleInsert(context: InsertionContext) { // super.handleInsert(context) // if (explicitReceiverRange == null || explicitReceiverText == null) return // val castType = explicitReceiverTypeHint ?: kind.fullyQualifiedCastType // val newReceiver = "(${explicitReceiverText} as $castType)" // context.document.replaceString(explicitReceiverRange.startOffset, explicitReceiverRange.endOffset, newReceiver) // context.commitDocument() // shortenReferencesInRange( // context.file as KtFile, // explicitReceiverRange.grown(newReceiver.length) // ) // } //} else -> this } } protected fun KtExpression.reference() = when (this) { is KtDotQualifiedExpression -> selectorExpression?.mainReference else -> mainReference } private fun KtAnalysisSession.applyWeighers( context: WeighingContext, lookupElement: LookupElement, symbol: KtSymbol, substitutor: KtSubstitutor, ): LookupElement = lookupElement.apply { with(Weighers) { applyWeighsToLookupElement(context, lookupElement, symbol, substitutor) } } } internal var LookupElement.availableWithoutImport: Boolean by NotNullableUserDataProperty(Key("KOTLIN_AVAILABLE_FROM_CURRENT_SCOPE"), true) internal fun <C : FirRawPositionCompletionContext> KtAnalysisSession.complete( contextContributor: FirCompletionContributorBase<C>, positionContext: C, ) { with(contextContributor) { complete(positionContext) } } internal var LookupElement.callableWeight by UserDataProperty(Key<CallableMetadataProvider.CallableMetadata>("KOTLIN_CALLABlE_WEIGHT")) private set
apache-2.0
90a49b97a4cabb30984dd542495e89de
50.168367
158
0.731678
5.259046
false
false
false
false
ingokegel/intellij-community
plugins/hg4idea/src/org/zmlx/hg4idea/action/HgAdd.kt
13
938
// 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.zmlx.hg4idea.action import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.changes.actions.ScheduleForAdditionActionExtension import com.intellij.openapi.vfs.VirtualFile import org.zmlx.hg4idea.HgVcs import org.zmlx.hg4idea.command.HgAddCommand class HgAdd : ScheduleForAdditionActionExtension { override fun getSupportedVcs(project: Project) = HgVcs.getInstance(project)!! override fun isStatusForAddition(status: FileStatus) = status === FileStatus.IGNORED override fun doAddFiles(project: Project, vcsRoot: VirtualFile, paths: List<FilePath>, containsIgnored: Boolean) { HgAddCommand(project).addWithProgress(paths.mapNotNull(FilePath::getVirtualFile)) } }
apache-2.0
b5b1f06a8834e830ed9e360faaefbd8e
41.681818
140
0.811301
3.908333
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/structuralsearch/KotlinStructuralSearchProfile.kt
1
18336
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.structuralsearch import com.intellij.dupLocator.util.NodeFilter import com.intellij.lang.Language import com.intellij.openapi.fileTypes.LanguageFileType import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiErrorElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.elementType import com.intellij.structuralsearch.* import com.intellij.structuralsearch.impl.matcher.CompiledPattern import com.intellij.structuralsearch.impl.matcher.GlobalMatchingVisitor import com.intellij.structuralsearch.impl.matcher.PatternTreeContext import com.intellij.structuralsearch.impl.matcher.compiler.GlobalCompilingVisitor import com.intellij.structuralsearch.impl.matcher.predicates.MatchPredicate import com.intellij.structuralsearch.impl.matcher.predicates.NotPredicate import com.intellij.structuralsearch.plugin.replace.ReplaceOptions import com.intellij.structuralsearch.plugin.ui.Configuration import com.intellij.structuralsearch.plugin.ui.UIUtil import com.intellij.util.SmartList import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.liveTemplates.KotlinTemplateContextType import org.jetbrains.kotlin.idea.structuralsearch.filters.AlsoMatchCompanionObjectModifier import org.jetbrains.kotlin.idea.structuralsearch.filters.AlsoMatchValModifier import org.jetbrains.kotlin.idea.structuralsearch.filters.AlsoMatchVarModifier import org.jetbrains.kotlin.idea.structuralsearch.filters.OneStateFilter import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinAlsoMatchCompanionObjectPredicate import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinAlsoMatchValVarPredicate import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinExprTypePredicate import org.jetbrains.kotlin.idea.structuralsearch.visitor.KotlinCompilingVisitor import org.jetbrains.kotlin.idea.structuralsearch.visitor.KotlinMatchingVisitor import org.jetbrains.kotlin.idea.structuralsearch.visitor.KotlinRecursiveElementWalkingVisitor import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* class KotlinStructuralSearchProfile : StructuralSearchProfile() { override fun getLexicalNodesFilter(): NodeFilter = NodeFilter { element -> element is PsiWhiteSpace } override fun createMatchingVisitor(globalVisitor: GlobalMatchingVisitor): KotlinMatchingVisitor = KotlinMatchingVisitor(globalVisitor) override fun createCompiledPattern(): CompiledPattern = object : CompiledPattern() { init { strategy = KotlinMatchingStrategy } override fun getTypedVarPrefixes(): Array<String> = arrayOf(TYPED_VAR_PREFIX) override fun isTypedVar(str: String): Boolean = when { str.isEmpty() -> false str[0] == '@' -> str.regionMatches(1, TYPED_VAR_PREFIX, 0, TYPED_VAR_PREFIX.length) else -> str.startsWith(TYPED_VAR_PREFIX) } override fun getTypedVarString(element: PsiElement): String { val typedVarString = super.getTypedVarString(element) return if (typedVarString.firstOrNull() == '@') typedVarString.drop(1) else typedVarString } } override fun isMyLanguage(language: Language): Boolean = language == KotlinLanguage.INSTANCE override fun getTemplateContextTypeClass(): Class<KotlinTemplateContextType> = KotlinTemplateContextType::class.java override fun getPredefinedTemplates(): Array<Configuration> = KotlinPredefinedConfigurations.createPredefinedTemplates() override fun getDefaultFileType(fileType: LanguageFileType?): LanguageFileType = fileType ?: KotlinFileType.INSTANCE override fun supportsShortenFQNames(): Boolean = true override fun compile(elements: Array<out PsiElement>, globalVisitor: GlobalCompilingVisitor) { KotlinCompilingVisitor(globalVisitor).compile(elements) } override fun getPresentableElement(element: PsiElement): PsiElement { val elem = if (isIdentifier(element)) element.parent else return element return if(elem is KtReferenceExpression) elem.parent else elem } override fun isIdentifier(element: PsiElement?): Boolean = element != null && element.node?.elementType == KtTokens.IDENTIFIER override fun createPatternTree( text: String, context: PatternTreeContext, fileType: LanguageFileType, language: Language, contextId: String?, project: Project, physical: Boolean ): Array<PsiElement> { var elements: List<PsiElement> val factory = KtPsiFactory(project, false) if (PROPERTY_CONTEXT.id == contextId) { try { val fragment = factory.createProperty(text) elements = listOf(getNonWhitespaceChildren(fragment).first().parent) if (elements.first() !is KtProperty) return PsiElement.EMPTY_ARRAY } catch (e: Exception) { return arrayOf(factory.createComment("//").apply { putUserData(PATTERN_ERROR, KotlinBundle.message("error.context.getter.or.setter")) }) } } else { val fragment = factory.createBlockCodeFragment("Unit\n$text", null) elements = when (fragment.lastChild) { is PsiComment -> getNonWhitespaceChildren(fragment).drop(1) else -> getNonWhitespaceChildren(fragment.firstChild).drop(1) } } if (elements.isEmpty()) return PsiElement.EMPTY_ARRAY // Standalone KtAnnotationEntry support if (elements.first() is KtAnnotatedExpression && elements.first().lastChild is PsiErrorElement) elements = getNonWhitespaceChildren(elements.first()).dropLast(1) // Standalone KtNullableType || KtUserType w/ type parameter support if (elements.last() is PsiErrorElement && elements.last().firstChild.elementType == KtTokens.QUEST || elements.first() is KtCallExpression && (elements.first() as KtCallExpression).valueArgumentList == null) { try { val fragment = factory.createType(text) elements = listOf(getNonWhitespaceChildren(fragment).first().parent) } catch (e: Exception) {} } // for (element in elements) print(DebugUtil.psiToString(element, false)) return elements.toTypedArray() } inner class KotlinValidator : KotlinRecursiveElementWalkingVisitor() { override fun visitErrorElement(element: PsiErrorElement) { super.visitErrorElement(element) if (shouldShowProblem(element)) { throw MalformedPatternException(element.errorDescription) } } override fun visitComment(comment: PsiComment) { super.visitComment(comment) comment.getUserData(PATTERN_ERROR)?.let { error -> throw MalformedPatternException(error) } } } override fun checkSearchPattern(pattern: CompiledPattern) { val visitor = KotlinValidator() val nodes = pattern.nodes while (nodes.hasNext()) { nodes.current().accept(visitor) nodes.advance() } nodes.reset() } override fun shouldShowProblem(error: PsiErrorElement): Boolean { val description = error.errorDescription val parent = error.parent return when { parent is KtTryExpression && KotlinBundle.message("error.expected.catch.or.finally") == description -> false //naked try parent is KtAnnotatedExpression && KotlinBundle.message("error.expected.an.expression") == description -> false else -> true } } override fun checkReplacementPattern(project: Project, options: ReplaceOptions) { val matchOptions = options.matchOptions val fileType = matchOptions.fileType!! val dialect = matchOptions.dialect!! val searchIsDeclaration = isProbableExpression(matchOptions.searchPattern, fileType, dialect, project) val replacementIsDeclaration = isProbableExpression(options.replacement, fileType, dialect, project) if (searchIsDeclaration != replacementIsDeclaration) { throw UnsupportedPatternException( if (searchIsDeclaration) SSRBundle.message("replacement.template.is.not.expression.error.message") else SSRBundle.message("search.template.is.not.expression.error.message") ) } } private fun ancestors(node: PsiElement?): List<PsiElement?> { val family = mutableListOf(node) repeat(7) { family.add(family.last()?.parent) } return family.drop(1) } override fun isApplicableConstraint( constraintName: String, variableNode: PsiElement?, completePattern: Boolean, target: Boolean ): Boolean { if (variableNode != null) return when (constraintName) { UIUtil.TYPE, UIUtil.TYPE_REGEX -> isApplicableType(variableNode) UIUtil.MINIMUM_ZERO -> isApplicableMinCount(variableNode) || isApplicableMinMaxCount(variableNode) UIUtil.MAXIMUM_UNLIMITED -> isApplicableMaxCount(variableNode) || isApplicableMinMaxCount(variableNode) UIUtil.TEXT_HIERARCHY -> isApplicableTextHierarchy(variableNode) UIUtil.REFERENCE -> isApplicableReference(variableNode) AlsoMatchVarModifier.CONSTRAINT_NAME -> variableNode.parent is KtProperty && !(variableNode.parent as KtProperty).isVar AlsoMatchValModifier.CONSTRAINT_NAME -> variableNode.parent is KtProperty && (variableNode.parent as KtProperty).isVar AlsoMatchCompanionObjectModifier.CONSTRAINT_NAME -> variableNode.parent is KtObjectDeclaration && !(variableNode.parent as KtObjectDeclaration).isCompanion() else -> super.isApplicableConstraint(constraintName, variableNode, completePattern, target) } return super.isApplicableConstraint(constraintName, null as PsiElement?, completePattern, target) } private fun isApplicableReference(variableNode: PsiElement): Boolean = variableNode.parent is KtNameReferenceExpression private fun isApplicableTextHierarchy(variableNode: PsiElement): Boolean { val family = ancestors(variableNode) return when { family[0] is KtClass && (family[0] as KtClass).nameIdentifier == variableNode -> true family[0] is KtObjectDeclaration && (family[0] as KtObjectDeclaration).nameIdentifier == variableNode -> true family[0] is KtEnumEntry && (family[0] as KtEnumEntry).nameIdentifier == variableNode -> true family[0] is KtNamedDeclaration && family[2] is KtClassOrObject -> true family[3] is KtSuperTypeListEntry && family[5] is KtClassOrObject -> true family[4] is KtSuperTypeListEntry && family[6] is KtClassOrObject -> true else -> false } } private fun isApplicableType(variableNode: PsiElement): Boolean { val family = ancestors(variableNode) return when { family[0] is KtNameReferenceExpression -> when (family[1]) { is KtValueArgument, is KtProperty, is KtBinaryExpression, is KtBinaryExpressionWithTypeRHS, is KtIsExpression, is KtBlockExpression, is KtContainerNode, is KtArrayAccessExpression, is KtPostfixExpression, is KtDotQualifiedExpression, is KtSafeQualifiedExpression, is KtCallableReferenceExpression, is KtSimpleNameStringTemplateEntry, is KtBlockStringTemplateEntry, is KtPropertyAccessor, is KtWhenEntry -> true else -> false } family[0] is KtProperty -> true family[0] is KtParameter -> true else -> false } } /** * Returns true if the largest count filter should be [0; 1]. */ private fun isApplicableMinCount(variableNode: PsiElement): Boolean { val family = ancestors(variableNode) return when { family[0] is KtObjectDeclaration -> true family[0] !is KtNameReferenceExpression -> false family[1] is KtProperty -> true family[1] is KtDotQualifiedExpression -> true family[1] is KtCallableReferenceExpression && family[0]?.nextSibling.elementType == KtTokens.COLONCOLON -> true family[1] is KtWhenExpression -> true family[2] is KtTypeReference && family[3] is KtNamedFunction -> true family[3] is KtConstructorCalleeExpression -> true else -> false } } /** * Returns true if the largest count filter should be [1; +inf]. */ private fun isApplicableMaxCount(variableNode: PsiElement): Boolean { val family = ancestors(variableNode) return when { family[0] is KtDestructuringDeclarationEntry -> true family[0] is KtNameReferenceExpression && family[1] is KtWhenConditionWithExpression -> true else -> false } } /** * Returns true if the largest count filter should be [0; +inf]. */ private fun isApplicableMinMaxCount(variableNode: PsiElement): Boolean { val family = ancestors(variableNode) return when { // Containers (lists, bodies, ...) family[0] is KtObjectDeclaration -> false family[1] is KtClassBody -> true family[0] is KtParameter && family[1] is KtParameterList -> true family[0] is KtTypeParameter && family[1] is KtTypeParameterList -> true family[2] is KtTypeParameter && family[3] is KtTypeParameterList -> true family[1] is KtUserType && family[4] is KtParameterList && family[5] !is KtNamedFunction -> true family[1] is KtUserType && family[3] is KtSuperTypeEntry -> true family[1] is KtValueArgument && family[2] is KtValueArgumentList -> true family[1] is KtBlockExpression && family[3] is KtDoWhileExpression -> true family[0] is KtNameReferenceExpression && family[1] is KtBlockExpression -> true family[1] is KtUserType && family[3] is KtTypeProjection && family[5] !is KtNamedFunction -> true // Annotations family[1] is KtUserType && family[4] is KtAnnotationEntry -> true family[1] is KtCollectionLiteralExpression -> true // Strings family[1] is KtSimpleNameStringTemplateEntry -> true // KDoc family[0] is KDocTag -> true // Default: count filter not applicable else -> false } } override fun getCustomPredicates( constraint: MatchVariableConstraint, name: String, options: MatchOptions ): MutableList<MatchPredicate> { val result = SmartList<MatchPredicate>() constraint.apply { if (!StringUtil.isEmptyOrSpaces(nameOfExprType)) { val predicate = KotlinExprTypePredicate( search = if (isRegexExprType) nameOfExprType else expressionTypes, withinHierarchy = isExprTypeWithinHierarchy, ignoreCase = !options.isCaseSensitiveMatch, target = isPartOfSearchResults, baseName = name, regex = isRegexExprType ) result.add(if (isInvertExprType) NotPredicate(predicate) else predicate) } if (getAdditionalConstraint(AlsoMatchValModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED || getAdditionalConstraint(AlsoMatchVarModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED ) result.add(KotlinAlsoMatchValVarPredicate()) if (getAdditionalConstraint(AlsoMatchCompanionObjectModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED) { result.add(KotlinAlsoMatchCompanionObjectPredicate()) } } return result } private fun isProbableExpression(pattern: String, fileType: LanguageFileType, dialect: Language, project: Project): Boolean { if(pattern.isEmpty()) return false val searchElements = try { createPatternTree(pattern, PatternTreeContext.Block, fileType, dialect, null, project, false) } catch (e: Exception) { return false } if (searchElements.isEmpty()) return false return searchElements[0] is KtDeclaration } override fun getReplaceHandler(project: Project, replaceOptions: ReplaceOptions): KotlinStructuralReplaceHandler = KotlinStructuralReplaceHandler(project) override fun getPatternContexts(): MutableList<PatternContext> = PATTERN_CONTEXTS companion object { const val TYPED_VAR_PREFIX: String = "_____" val DEFAULT_CONTEXT: PatternContext = PatternContext("default", KotlinBundle.lazyMessage("context.default")) val PROPERTY_CONTEXT: PatternContext = PatternContext("property", KotlinBundle.lazyMessage("context.property.getter.or.setter")) private val PATTERN_CONTEXTS: MutableList<PatternContext> = mutableListOf(DEFAULT_CONTEXT, PROPERTY_CONTEXT) private val PATTERN_ERROR: Key<String> = Key("patternError") fun getNonWhitespaceChildren(fragment: PsiElement): List<PsiElement> { var element = fragment.firstChild val result: MutableList<PsiElement> = SmartList() while (element != null) { if (element !is PsiWhiteSpace) result.add(element) element = element.nextSibling } return result } } }
apache-2.0
fbd18f48755966fd51467ee5a4257350
47.382586
136
0.680628
5.383441
false
false
false
false
mdaniel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/AttachedEntityParentListImpl.kt
1
5810
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.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class AttachedEntityParentListImpl: AttachedEntityParentList, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } @JvmField var _data: String? = null override val data: String get() = _data!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: AttachedEntityParentListData?): ModifiableWorkspaceEntityBase<AttachedEntityParentList>(), AttachedEntityParentList.Builder { constructor(): this(AttachedEntityParentListData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity AttachedEntityParentList 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().isDataInitialized()) { error("Field AttachedEntityParentList#data should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field AttachedEntityParentList#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override fun getEntityData(): AttachedEntityParentListData = result ?: super.getEntityData() as AttachedEntityParentListData override fun getEntityClass(): Class<AttachedEntityParentList> = AttachedEntityParentList::class.java } } class AttachedEntityParentListData : WorkspaceEntityData<AttachedEntityParentList>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<AttachedEntityParentList> { val modifiable = AttachedEntityParentListImpl.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): AttachedEntityParentList { val entity = AttachedEntityParentListImpl() entity._data = data entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return AttachedEntityParentList::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 AttachedEntityParentListData if (this.data != other.data) 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 AttachedEntityParentListData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } }
apache-2.0
7eadf35b923254a73001539bbd76160c
34.87037
155
0.655594
6.254037
false
false
false
false
NativeScript/android-runtime
test-app/build-tools/android-metadata-generator/src/src/com/telerik/metadata/parsing/kotlin/metadata/bytecode/BytecodeMetadataAnnotation.kt
1
5030
package com.telerik.metadata.parsing.kotlin.metadata.bytecode import com.telerik.metadata.parsing.kotlin.metadata.MetadataAnnotation import org.apache.bcel.classfile.AnnotationEntry import org.apache.bcel.classfile.ArrayElementValue import org.apache.bcel.classfile.ElementValue import org.apache.bcel.classfile.SimpleElementValue class BytecodeMetadataAnnotation(annotationEntry: AnnotationEntry?) : MetadataAnnotation { override var kind: Int = 1 // 1 comes from the source of the kotlin.Metadata private set(value) { field = value } override var metadataVersion: IntArray = intArrayOf() private set(value) { field = value } override var bytecodeVersion: IntArray = intArrayOf() private set(value) { field = value } override var data1: Array<String> = emptyArray() private set(value) { field = value } override var data2: Array<String> = emptyArray() private set(value) { field = value } override var extraString: String = "" private set(value) { field = value } override var packageName: String = "" private set(value) { field = value } override var extraInt: Int = 0 // 0 comes from the source of the kotlin.Metadata private set(value) { field = value } init { if (annotationEntry != null) { parseKotlinMetadataAnnotation(annotationEntry) } } private fun parseKotlinMetadataAnnotation(annotationEntry: AnnotationEntry) { val elementValuePairs = annotationEntry.elementValuePairs if (elementValuePairs != null) { for (elementValuePair in annotationEntry.elementValuePairs) { val elementName = elementValuePair.nameString val elementValue = elementValuePair.value when (elementName) { "k" -> parseKind(elementValue) "mv" -> parseMetadataVersion(elementValue) "bv" -> parseBytecodeVersion(elementValue) "d1" -> parseData1(elementValue) "d2" -> parseData2(elementValue) "xs" -> parseExtraString(elementValue) "pn" -> parsePackageName(elementValue) "xi" -> parseExtraInt(elementValue) } } } } private fun parseKind(elementValue: ElementValue) { val simpleElementValue = elementValue as SimpleElementValue kind = simpleElementValue.valueInt } private fun parseMetadataVersion(elementValue: ElementValue) { val arrayElement = elementValue as ArrayElementValue val metadataVersionArraySize = arrayElement.elementValuesArraySize val arrayElementValues = arrayElement.elementValuesArray metadataVersion = IntArray(metadataVersionArraySize) { val simpleElementValue = arrayElementValues[it] as SimpleElementValue simpleElementValue.valueInt } } private fun parseBytecodeVersion(elementValue: ElementValue) { val arrayElement = elementValue as ArrayElementValue val bytecodeVersionArraySize = arrayElement.elementValuesArraySize val arrayElementValues = arrayElement.elementValuesArray bytecodeVersion = IntArray(bytecodeVersionArraySize) { val simpleElementValue = arrayElementValues[it] as SimpleElementValue simpleElementValue.valueInt } } private fun parseData1(elementValue: ElementValue) { val arrayElement = elementValue as ArrayElementValue val data1ArraySize = arrayElement.elementValuesArraySize val arrayElementValues = arrayElement.elementValuesArray data1 = Array(data1ArraySize) { val simpleElementValue = arrayElementValues[it] as SimpleElementValue simpleElementValue.valueString } } private fun parseData2(elementValue: ElementValue) { val arrayElement = elementValue as ArrayElementValue val data2ArraySize = arrayElement.elementValuesArraySize val arrayElementValues = arrayElement.elementValuesArray data2 = Array(data2ArraySize) { i -> val simpleElementValue = arrayElementValues[i] as SimpleElementValue simpleElementValue.valueString } } private fun parseExtraString(elementValue: ElementValue) { val simpleElementValue = elementValue as SimpleElementValue extraString = simpleElementValue.valueString } private fun parsePackageName(elementValue: ElementValue) { val simpleElementValue = elementValue as SimpleElementValue packageName = simpleElementValue.valueString } private fun parseExtraInt(elementValue: ElementValue) { val simpleElementValue = elementValue as SimpleElementValue extraInt = simpleElementValue.valueInt } }
apache-2.0
e3e69429be58a9fd0ffa4b62d58fedcd
33.452055
90
0.663618
5.169579
false
false
false
false
JavaEden/Orchid-Core
plugins/OrchidJavadoc/src/main/kotlin/com/eden/orchid/javadoc/menu/ClassDocLinksMenuItemType.kt
1
4572
package com.eden.orchid.javadoc.menu import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.BooleanDefault import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.theme.menus.MenuItem import com.eden.orchid.api.theme.menus.OrchidMenu import com.eden.orchid.api.theme.menus.OrchidMenuFactory import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.javadoc.models.JavadocModel import com.eden.orchid.javadoc.pages.JavadocClassPage import java.util.ArrayList @Description( "Links to the different sections within a Javadoc Class page, optionally with their items nested " + "underneath them.", name = "Javadoc Class Sections" ) class ClassDocLinksMenuItemType : OrchidMenuFactory("javadocClassLinks") { @Option @BooleanDefault(false) @Description( "Whether to include the items for each category. For example, including a menu item for each " + "individual constructor as children of 'Constructors' or just a link to the Constructors section." ) var includeItems: Boolean = false override fun canBeUsedOnPage( containingPage: OrchidPage, menu: OrchidMenu, possibleMenuItems: List<Map<String, Any>>, currentMenuItems: List<OrchidMenuFactory> ): Boolean { return containingPage is JavadocClassPage } override fun getMenuItems( context: OrchidContext, page: OrchidPage ): List<MenuItem> { val model = context.resolve(JavadocModel::class.java) val containingPage = page as JavadocClassPage val classDoc = containingPage.classDoc val menuItems = ArrayList<MenuItem>() val linkData = arrayOf( LinkData( { true }, { emptyList() }, "Summary", "summary" ), LinkData( { true }, { emptyList() }, "Description", "description" ), LinkData( { classDoc.fields.isNotEmpty() }, { getFieldLinks(context, model, page) }, "Fields", "fields" ), LinkData( { classDoc.constructors.isNotEmpty() }, { getConstructorLinks(context, model, page) }, "Constructors", "constructors" ), LinkData( { classDoc.methods.isNotEmpty() }, { getMethodLinks(context, model, page) }, "Methods", "methods" ) ) for (item in linkData) { if (item.matches()) { val menuItem = MenuItem.Builder(context) .title(item.title) .anchor(item.id) if (includeItems) { menuItem.children(item.items()) } menuItems.add(menuItem.build()) } } return menuItems } private data class LinkData( val matches: () -> Boolean, val items: () -> List<MenuItem>, val title: String, val id: String ) private fun getFieldLinks(context: OrchidContext, model: JavadocModel, page: OrchidPage): List<MenuItem> { val containingPage = page as JavadocClassPage val classDoc = containingPage.classDoc return classDoc.fields.map { MenuItem.Builder(context) .title(it.simpleSignature) .anchor(model.idFor(it)) .build() } } private fun getConstructorLinks(context: OrchidContext, model: JavadocModel, page: OrchidPage): List<MenuItem> { val containingPage = page as JavadocClassPage val classDoc = containingPage.classDoc return classDoc.constructors.map { MenuItem.Builder(context) .title(it.simpleSignature) .anchor(model.idFor(it)) .build() } } private fun getMethodLinks(context: OrchidContext, model: JavadocModel, page: OrchidPage): List<MenuItem> { val containingPage = page as JavadocClassPage val classDoc = containingPage.classDoc return classDoc.methods.map { MenuItem.Builder(context) .title(it.simpleSignature) .anchor(model.idFor(it)) .build() } } }
mit
6210525346a54984fc871193113d526e
31.197183
116
0.582021
4.932039
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/challenge/usecase/FindQuestsForChallengeUseCase.kt
1
1083
package io.ipoli.android.challenge.usecase import io.ipoli.android.challenge.entity.Challenge import io.ipoli.android.common.UseCase import io.ipoli.android.quest.data.persistence.QuestRepository import io.ipoli.android.repeatingquest.persistence.RepeatingQuestRepository /** * Created by Polina Zhelyazkova <[email protected]> * on 3/13/18. */ class FindQuestsForChallengeUseCase( private val questRepository: QuestRepository, private val repeatingQuestRepository: RepeatingQuestRepository ) : UseCase<FindQuestsForChallengeUseCase.Params, Challenge> { override fun execute(parameters: Params): Challenge { val challenge = parameters.challenge val rqs = repeatingQuestRepository.findAllForChallenge(challenge.id) val quests = questRepository.findAllForChallengeNotRepeating(challenge.id) return challenge.copy( baseQuests = (rqs + quests), repeatingQuests = rqs, quests = questRepository.findNotRemovedForChallenge(challenge.id) ) } data class Params(val challenge: Challenge) }
gpl-3.0
f5de63f1f35eb7af62cd257a712c0ae3
35.133333
82
0.756233
4.608511
false
false
false
false
GunoH/intellij-community
plugins/kotlin/gradle/code-insight-groovy/src/org/jetbrains/kotlin/idea/groovy/inspections/KotlinGradleInspectionVisitor.kt
4
3206
// 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.groovy.inspections import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.io.FileUtilRt import com.intellij.psi.PsiFile import org.jetbrains.kotlin.idea.base.externalSystem.KotlinGradleFacade import org.jetbrains.kotlin.idea.base.util.isGradleModule import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.extensions.gradle.KotlinGradleConstants import org.jetbrains.kotlin.idea.gradleCodeInsightCommon.findGradleProjectStructure import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase const val KOTLIN_PLUGIN_CLASSPATH_MARKER = "${KotlinGradleConstants.GROUP_ID}:${KotlinGradleConstants.GRADLE_PLUGIN_ID}:" abstract class KotlinGradleInspectionVisitor : BaseInspectionVisitor() { override fun visitFile(file: GroovyFileBase) { if (!FileUtilRt.extensionEquals(file.name, KotlinGradleConstants.GROOVY_EXTENSION)) return val fileIndex = ProjectRootManager.getInstance(file.project).fileIndex if (!isUnitTestMode()) { val module = fileIndex.getModuleForFile(file.virtualFile) ?: return if (!module.isGradleModule) return } if (fileIndex.isExcluded(file.virtualFile)) return super.visitFile(file) } } @Deprecated("Use findResolvedKotlinGradleVersion() instead.", ReplaceWith("findResolvedKotlinGradleVersion(module)?.rawVersion")) fun getResolvedKotlinGradleVersion(file: PsiFile): String? = ModuleUtilCore.findModuleForFile(file.virtualFile, file.project)?.let { @Suppress("DEPRECATION") getResolvedKotlinGradleVersion(it) } fun findResolvedKotlinGradleVersion(file: PsiFile): IdeKotlinVersion? = ModuleUtilCore.findModuleForFile(file.virtualFile, file.project)?.let { findResolvedKotlinGradleVersion(it) } @Deprecated("Use findResolvedKotlinGradleVersion() instead.", ReplaceWith("findResolvedKotlinGradleVersion(module)?.rawVersion")) fun getResolvedKotlinGradleVersion(module: Module): String? { return findResolvedKotlinGradleVersion(module)?.rawVersion } fun findResolvedKotlinGradleVersion(module: Module): IdeKotlinVersion? { val projectStructureNode = findGradleProjectStructure(module) ?: return null val gradleFacade = KotlinGradleFacade.instance ?: return null for (node in ExternalSystemApiUtil.findAll(projectStructureNode, ProjectKeys.MODULE)) { if (node.data.internalName == module.name) { val kotlinPluginVersion = gradleFacade.findKotlinPluginVersion(node) if (kotlinPluginVersion != null) { return kotlinPluginVersion } } } return null }
apache-2.0
2de2dc2a18485d7cc9a1c54ae414861d
45.463768
158
0.784155
4.924731
false
false
false
false
GunoH/intellij-community
plugins/kotlin/code-insight/postfix-templates/src/org/jetbrains/kotlin/idea/codeInsight/postfix/KotlinSpreadPostfixTemplate.kt
3
2056
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeInsight.postfix import com.intellij.codeInsight.template.postfix.templates.StringBasedPostfixTemplate import com.intellij.psi.PsiElement import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtValueArgument import org.jetbrains.kotlin.psi.psiUtil.getParentOfType internal class KotlinSpreadPostfixTemplate : StringBasedPostfixTemplate { @Suppress("ConvertSecondaryConstructorToPrimary") constructor(provider: KotlinPostfixTemplateProvider) : super( /* name = */ "spread", /* example = */ "*expr", /* selector = */ allExpressions(ValuedFilter, ValueParameterFilter, ExpressionTypeFilter { it.canSpread() }), /* provider = */ provider ) override fun getTemplateString(element: PsiElement) = "*\$expr$\$END$" override fun getElementToRemove(expr: PsiElement) = expr } private object ValueParameterFilter : (KtExpression) -> Boolean { override fun invoke(expression: KtExpression): Boolean { val valueArgument = expression.getParentOfType<KtValueArgument>(strict = true) ?: return false return !valueArgument.isSpread } } private val ARRAY_CLASS_FQ_NAMES: Set<FqNameUnsafe> = buildSet { addAll(StandardNames.FqNames.arrayClassFqNameToPrimitiveType.keys) add(StandardNames.FqNames.array) add(StandardNames.FqNames.uByteArrayFqName.toUnsafe()) add(StandardNames.FqNames.uShortArrayFqName.toUnsafe()) add(StandardNames.FqNames.uIntArrayFqName.toUnsafe()) add(StandardNames.FqNames.uLongArrayFqName.toUnsafe()) } private fun KtType.canSpread(): Boolean { return this is KtNonErrorClassType && classId.asSingleFqName().toUnsafe() in ARRAY_CLASS_FQ_NAMES }
apache-2.0
eca03260ecd23f52ebe10a90e40653fb
44.711111
120
0.774319
4.508772
false
false
false
false
ktorio/ktor
ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/Render.kt
1
6559
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.tls import io.ktor.network.tls.extensions.* import io.ktor.utils.io.* import io.ktor.utils.io.core.* import java.security.* import java.security.cert.* import java.security.interfaces.* import java.security.spec.* import javax.crypto.* internal suspend fun ByteWriteChannel.writeRecord(record: TLSRecord) = with(record) { writeByte(type.code.toByte()) writeByte((version.code shr 8).toByte()) writeByte(version.code.toByte()) writeShort(packet.remaining.toShort()) writePacket(packet) flush() } internal fun BytePacketBuilder.writeTLSHandshakeType(type: TLSHandshakeType, length: Int) { if (length > 0xffffff) throw TLSException("TLS handshake size limit exceeded: $length") val v = (type.code shl 24) or length writeInt(v) } internal fun BytePacketBuilder.writeTLSClientHello( version: TLSVersion, suites: List<CipherSuite>, random: ByteArray, sessionId: ByteArray, serverName: String? = null ) { writeShort(version.code.toShort()) writeFully(random) val sessionIdLength = sessionId.size if (sessionIdLength < 0 || sessionIdLength > 0xff || sessionIdLength > sessionId.size) { throw TLSException("Illegal sessionIdLength") } writeByte(sessionIdLength.toByte()) writeFully(sessionId, 0, sessionIdLength) writeShort((suites.size * 2).toShort()) for (suite in suites) { writeShort(suite.code) } // compression is always null writeByte(1) writeByte(0) val extensions = ArrayList<ByteReadPacket>() extensions += buildSignatureAlgorithmsExtension() extensions += buildECCurvesExtension() extensions += buildECPointFormatExtension() serverName?.let { name -> extensions += buildServerNameExtension(name) } writeShort(extensions.sumOf { it.remaining.toInt() }.toShort()) for (e in extensions) { writePacket(e) } } internal fun BytePacketBuilder.writeTLSCertificates(certificates: Array<X509Certificate>) { val chain = buildPacket { for (certificate in certificates) { val certificateBytes = certificate.encoded!! writeTripleByteLength(certificateBytes.size) writeFully(certificateBytes) } } writeTripleByteLength(chain.remaining.toInt()) writePacket(chain) } internal fun BytePacketBuilder.writeEncryptedPreMasterSecret( preSecret: ByteArray, publicKey: PublicKey, random: SecureRandom ) { require(preSecret.size == 48) val rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")!! rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey, random) val encryptedSecret = rsaCipher.doFinal(preSecret) if (encryptedSecret.size > 0xffff) throw TLSException("Encrypted premaster secret is too long") writeShort(encryptedSecret.size.toShort()) writeFully(encryptedSecret) } internal fun finished(digest: ByteArray, secretKey: SecretKey) = buildPacket { val prf = PRF(secretKey, CLIENT_FINISHED_LABEL, digest, 12) writeFully(prf) } internal fun serverFinished(handshakeHash: ByteArray, secretKey: SecretKey, length: Int = 12): ByteArray = PRF(secretKey, SERVER_FINISHED_LABEL, handshakeHash, length) internal fun BytePacketBuilder.writePublicKeyUncompressed(key: PublicKey) = when (key) { is ECPublicKey -> { val fieldSize = key.params.curve.field.fieldSize writeECPoint(key.w, fieldSize) } else -> throw TLSException("Unsupported public key type: $key") } internal fun BytePacketBuilder.writeECPoint(point: ECPoint, fieldSize: Int) { val pointData = buildPacket { writeByte(4) // 4 - uncompressed writeAligned(point.affineX.toByteArray(), fieldSize) writeAligned(point.affineY.toByteArray(), fieldSize) } writeByte(pointData.remaining.toByte()) writePacket(pointData) } private fun buildSignatureAlgorithmsExtension( algorithms: List<HashAndSign> = SupportedSignatureAlgorithms ): ByteReadPacket = buildPacket { writeShort(TLSExtensionType.SIGNATURE_ALGORITHMS.code) // signature_algorithms extension val size = algorithms.size writeShort((2 + size * 2).toShort()) // length in bytes writeShort((size * 2).toShort()) // length in bytes algorithms.forEach { writeByte(it.hash.code) writeByte(it.sign.code) } } private const val MAX_SERVER_NAME_LENGTH: Int = Short.MAX_VALUE - 5 private fun buildServerNameExtension(name: String): ByteReadPacket = buildPacket { require(name.length < MAX_SERVER_NAME_LENGTH) { "Server name length limit exceeded: at most $MAX_SERVER_NAME_LENGTH characters allowed" } writeShort(TLSExtensionType.SERVER_NAME.code) // server_name writeShort((name.length + 2 + 1 + 2).toShort()) // length writeShort((name.length + 2 + 1).toShort()) // list length writeByte(0) // type: host_name writeShort(name.length.toShort()) // name length writeText(name) } private const val MAX_CURVES_QUANTITY: Int = Short.MAX_VALUE / 2 - 1 private fun buildECCurvesExtension(curves: List<NamedCurve> = SupportedNamedCurves): ByteReadPacket = buildPacket { require(curves.size <= MAX_CURVES_QUANTITY) { "Too many named curves provided: at most $MAX_CURVES_QUANTITY could be provided" } writeShort(TLSExtensionType.ELLIPTIC_CURVES.code) val size = curves.size * 2 writeShort((2 + size).toShort()) // extension length writeShort(size.toShort()) // list length curves.forEach { writeShort(it.code) } } private fun buildECPointFormatExtension( formats: List<PointFormat> = SupportedPointFormats ): ByteReadPacket = buildPacket { writeShort(TLSExtensionType.EC_POINT_FORMAT.code) val size = formats.size writeShort((1 + size).toShort()) // extension length writeByte(size.toByte()) // list length formats.forEach { writeByte(it.code) } } private fun BytePacketBuilder.writeAligned(src: ByteArray, fieldSize: Int) { val expectedSize = (fieldSize + 7) ushr 3 val index = src.indexOfFirst { it != 0.toByte() } val padding = expectedSize - (src.size - index) if (padding > 0) writeFully(ByteArray(padding)) writeFully(src, index, src.size - index) } private fun BytePacketBuilder.writeTripleByteLength(value: Int) { val high = (value ushr 16) and 0xff val low = value and 0xffff writeByte(high.toByte()) writeShort(low.toShort()) }
apache-2.0
8f754faa79049db45d94bd36b7d609de
30.995122
119
0.708187
4.112226
false
false
false
false
ktorio/ktor
ktor-io/jvm/test/io/ktor/utils/io/ByteBufferChannelTest.kt
1
5131
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.utils.io import kotlinx.coroutines.* import kotlinx.coroutines.debug.junit4.* import org.junit.* import java.io.* import kotlin.test.* import kotlin.test.Test class ByteBufferChannelTest { @get:Rule public val timeoutRule: CoroutinesTimeout by lazy { CoroutinesTimeout.seconds(60) } @Test fun testCompleteExceptionallyJob() { val channel = ByteBufferChannel(false) Job().also { channel.attachJob(it) }.completeExceptionally(IOException("Text exception")) assertFailsWith<IOException> { runBlocking { channel.readByte() } } } @Test fun readRemainingThrowsOnClosed() = runBlocking { val channel = ByteBufferChannel(false) channel.writeFully(byteArrayOf(1, 2, 3, 4, 5)) channel.close(IllegalStateException("closed")) assertFailsWith<IllegalStateException>("closed") { channel.readRemaining() } Unit } @Test fun testWriteWriteAvailableRaceCondition() = runBlocking { testWriteXRaceCondition { it.writeAvailable(1) { it.put(1) } } } @Test fun testWriteByteRaceCondition() = runBlocking { testWriteXRaceCondition { it.writeByte(1) } } @Test fun testWriteIntRaceCondition() = runBlocking { testWriteXRaceCondition { it.writeInt(1) } } @Test fun testWriteShortRaceCondition() = runBlocking { testWriteXRaceCondition { it.writeShort(1) } } @Test fun testWriteLongRaceCondition() = runBlocking { testWriteXRaceCondition { it.writeLong(1) } } @OptIn(DelicateCoroutinesApi::class) private fun testWriteXRaceCondition(writer: suspend (ByteChannel) -> Unit): Unit = runBlocking { val channel = ByteBufferChannel(false) val job1 = GlobalScope.async { try { repeat(10_000_000) { writer(channel) channel.flush() } channel.close() } catch (cause: Throwable) { channel.close(cause) throw cause } } val job2 = GlobalScope.async { channel.readRemaining() } job1.await() job2.await() } @Test fun testReadAvailable() = runBlocking { val channel = ByteBufferChannel(true) channel.writeFully(byteArrayOf(1, 2)) val read1 = channel.readAvailable(4) { it.position(it.position() + 4) } assertEquals(-1, read1) channel.writeFully(byteArrayOf(3, 4)) val read2 = channel.readAvailable(4) { it.position(it.position() + 4) } assertEquals(4, read2) } @Test fun testPartialReadAvailable() = runBlocking { val dataSize = 4088 val channel = ByteChannel(autoFlush = true) val data = ByteArray(dataSize) { 0 } val job = launch { channel.writeFully(data) channel.close() } launch { channel.awaitContent() assertEquals(dataSize, channel.availableForRead) val firstRead = channel.readAvailable { /* no-op */ } assertEquals(0, firstRead) assertEquals(dataSize, channel.availableForRead) val secondRead = channel.readAvailable { it.position(it.remaining()) } assertEquals(dataSize, secondRead) } try { withTimeout(2500) { job.join() } } catch (e: TimeoutCancellationException) { fail("All bytes should be written to and read from the channel") } } @Test fun testReadAvailableWithMoreThanBufferSizeContent() = runBlocking { val dataSize = 4089 // larger than buffer capacity (4088) val channel = ByteChannel(autoFlush = true) val data = ByteArray(dataSize) { 0 } val job = launch { channel.writeFully(data) channel.close() } launch { var totalRead = 0 var result: Int do { channel.awaitContent() result = channel.readAvailable { it.position(it.remaining()) // consume all available bytes } if (result > 0) totalRead += result } while (result > 0) assertEquals(dataSize, totalRead) } try { withTimeout(2500) { job.join() } } catch (e: TimeoutCancellationException) { fail("All bytes should be written to and read from the channel") } } @Test fun testAwaitContent() = runBlocking { val channel = ByteBufferChannel(true) var awaitingContent = false launch { awaitingContent = true channel.awaitContent() awaitingContent = false } yield() assertTrue(awaitingContent) channel.writeByte(1) yield() assertFalse(awaitingContent) } }
apache-2.0
3af4b955ce2138657e36b0cfcc8a2bd7
27.038251
118
0.584681
4.76416
false
true
false
false
ktorio/ktor
ktor-server/ktor-server-plugins/ktor-server-request-validation/jvmAndNix/src/io/ktor/server/plugins/requestvalidation/RequestValidationConfig.kt
1
2758
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.requestvalidation import kotlin.reflect.* /** * A config for [RequestValidation] plugin */ public class RequestValidationConfig { internal val validators: MutableList<Validator> = mutableListOf() internal var validateContentLength: Boolean = false /** * Enables validation of the request body length matches the [Content-Length] header. * If the length doesn't match, body channel will be cancelled with [IOException]. */ public fun validateContentLength() { validateContentLength = true } /** * Registers [validator] */ public fun validate(validator: Validator) { validators.add(validator) } /** * Registers [Validator] that should check instances of a [kClass] using [block] */ public fun <T : Any> validate(kClass: KClass<T>, block: suspend (T) -> ValidationResult) { val validator = object : Validator { @Suppress("UNCHECKED_CAST") override suspend fun validate(value: Any): ValidationResult = block(value as T) override fun filter(value: Any): Boolean = kClass.isInstance(value) } validate(validator) } /** * Registers [Validator] that should check instances of a [T] using [block] */ public inline fun <reified T : Any> validate(noinline block: suspend (T) -> ValidationResult) { validate(T::class, block) } /** * Registers [Validator] using DSL * ``` * validate { * filter { it is Int } * validation { check(it is Int); ... } * } * ``` */ public fun validate(block: ValidatorBuilder.() -> Unit) { val builder = ValidatorBuilder().apply(block) validate(builder.build()) } public class ValidatorBuilder { private lateinit var validationBlock: suspend (Any) -> ValidationResult private lateinit var filterBlock: (Any) -> Boolean public fun filter(block: (Any) -> Boolean) { filterBlock = block } public fun validation(block: suspend (Any) -> ValidationResult) { validationBlock = block } internal fun build(): Validator { check(::validationBlock.isInitialized) { "`validation { ... } block is not ser`" } check(::filterBlock.isInitialized) { "`filter { ... } block is not set`" } return object : Validator { override suspend fun validate(value: Any) = validationBlock(value) override fun filter(value: Any): Boolean = filterBlock(value) } } } }
apache-2.0
1c7aeb8357caaeb0e2724d37a04f3ed6
30.701149
119
0.613488
4.643098
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/util/expression-utils.kt
1
4428
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util import com.demonwav.mcdev.i18n.translations.Translation import com.demonwav.mcdev.i18n.translations.Translation.Companion.FormattingError import com.intellij.psi.JavaTokenType import com.intellij.psi.PsiAnnotationMemberValue import com.intellij.psi.PsiCall import com.intellij.psi.PsiExpression import com.intellij.psi.PsiLiteral import com.intellij.psi.PsiParameter import com.intellij.psi.PsiParameterList import com.intellij.psi.PsiPolyadicExpression import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.PsiTypeCastExpression import com.intellij.psi.PsiVariable fun PsiAnnotationMemberValue.evaluate(defaultValue: String?, parameterReplacement: String?): String? { val visited = mutableSetOf<PsiAnnotationMemberValue?>() fun eval(expr: PsiAnnotationMemberValue?, defaultValue: String?): String? { if (!visited.add(expr)) { return defaultValue } when { expr is PsiTypeCastExpression && expr.operand != null -> return eval(expr.operand, defaultValue) expr is PsiReferenceExpression -> { val reference = expr.advancedResolve(false).element if (reference is PsiParameter) { return parameterReplacement } if (reference is PsiVariable && reference.initializer != null) { return eval(reference.initializer, null) } } expr is PsiLiteral -> return expr.value.toString() expr is PsiPolyadicExpression && expr.operationTokenType == JavaTokenType.PLUS -> { var value = "" for (operand in expr.operands) { val operandResult = eval(operand, defaultValue) ?: return defaultValue value += operandResult } return value } } return defaultValue } return eval(this, defaultValue) } fun PsiExpression.substituteParameter(substitutions: Map<Int, Array<String?>?>, allowReferences: Boolean, allowTranslations: Boolean): Array<String?>? { val visited = mutableSetOf<PsiExpression?>() fun substitute(expr: PsiExpression?): Array<String?>? { if (!visited.add(expr) && expr != null) { return arrayOf("\${${expr.text}}") } when { expr is PsiTypeCastExpression && expr.operand != null -> return substitute(expr.operand) expr is PsiReferenceExpression -> { val reference = expr.advancedResolve(false).element if (reference is PsiParameter && reference.parent is PsiParameterList) { val paramIndex = (reference.parent as PsiParameterList).getParameterIndex(reference) if (substitutions.containsKey(paramIndex)) { return substitutions[paramIndex] } } if (reference is PsiVariable && reference.initializer != null) { return substitute(reference.initializer) } } expr is PsiLiteral -> return arrayOf(expr.value.toString()) expr is PsiPolyadicExpression && expr.operationTokenType == JavaTokenType.PLUS -> { var value = "" for (operand in expr.operands) { val operandResult = operand.evaluate(null, null) ?: return null value += operandResult } return arrayOf(value) } expr is PsiCall && allowTranslations -> for (argument in expr.argumentList?.expressions ?: emptyArray()) { val translation = Translation.find(argument) ?: continue if (translation.formattingError == FormattingError.MISSING) { return arrayOf("{ERROR: Missing formatting arguments for '${translation.text}'}") } return arrayOf(translation.text) } } return if (allowReferences && expr != null) { arrayOf("\${${expr.text}}") } else { null } } return substitute(this) }
mit
88085af74285dd42e5f6618348a959b0
38.891892
152
0.593044
5.548872
false
false
false
false
dahlstrom-g/intellij-community
plugins/devkit/devkit-core/src/inspections/missingApi/update/IntelliJSdkExternalAnnotationsUpdater.kt
12
6226
// 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.idea.devkit.inspections.missingApi.update import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runInEdt import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.AnnotationOrderRootType import com.intellij.openapi.util.BuildNumber import com.intellij.profile.codeInspection.ProjectInspectionProfileManager import org.jetbrains.idea.devkit.DevKitBundle import org.jetbrains.idea.devkit.inspections.missingApi.MissingRecentApiInspection import org.jetbrains.idea.devkit.inspections.missingApi.resolve.IntelliJSdkExternalAnnotations import org.jetbrains.idea.devkit.inspections.missingApi.resolve.PublicIntelliJSdkExternalAnnotationsRepository import org.jetbrains.idea.devkit.inspections.missingApi.resolve.getAnnotationsBuildNumber import org.jetbrains.idea.devkit.inspections.missingApi.resolve.isAnnotationsRoot import java.time.Duration import java.time.Instant import java.time.temporal.ChronoUnit import java.util.concurrent.atomic.AtomicReference /** * Utility class that updates external annotations of IntelliJ SDK. */ class IntelliJSdkExternalAnnotationsUpdater { companion object { private val LOG = Logger.getInstance(IntelliJSdkExternalAnnotationsUpdater::class.java) private val UPDATE_RETRY_TIMEOUT = Duration.of(1, ChronoUnit.HOURS) fun getInstance(): IntelliJSdkExternalAnnotationsUpdater = service() } private val buildNumberLastFailedUpdateInstant = hashMapOf<BuildNumber, Instant>() private val buildNumberUpdateInProgress = hashSetOf<BuildNumber>() private fun isInspectionEnabled(project: Project): Boolean { return runReadAction { ProjectInspectionProfileManager.getInstance(project).currentProfile .getTools(MissingRecentApiInspection.INSPECTION_SHORT_NAME, project) .isEnabled } } fun updateIdeaJdkAnnotationsIfNecessary(project: Project, ideaJdk: Sdk, buildNumber: BuildNumber) { if (!isInspectionEnabled(project)) { return } if (synchronized(this) { buildNumber in buildNumberUpdateInProgress }) { return } val attachedAnnotations = getAttachedAnnotationsBuildNumbers(ideaJdk) if (attachedAnnotations.any { it >= buildNumber }) { return } runInEdt { synchronized(this) { val lastFailedInstant = buildNumberLastFailedUpdateInstant[buildNumber] val lastFailedWasLongAgo = lastFailedInstant == null || Instant.now().isAfter(lastFailedInstant.plus(UPDATE_RETRY_TIMEOUT)) if (lastFailedWasLongAgo) { updateAnnotationsInBackground(ideaJdk, project, buildNumber) } } } } private fun reattachAnnotations(project: Project, ideaJdk: Sdk, annotationsRoot: IntelliJSdkExternalAnnotations) { val annotationsUrl = runReadAction { annotationsRoot.annotationsRoot.url } ApplicationManager.getApplication().invokeAndWait { if (project.isDisposed) { return@invokeAndWait } runWriteAction { val type = AnnotationOrderRootType.getInstance() val sdkModificator = ideaJdk.sdkModificator val attachedUrls = sdkModificator.getRoots(type) .asSequence() .filter { isAnnotationsRoot(it) } .mapTo(mutableSetOf()) { it.url } if (annotationsUrl !in attachedUrls) { sdkModificator.addRoot(annotationsUrl, type) } for (redundantUrl in attachedUrls - annotationsUrl) { sdkModificator.removeRoot(redundantUrl, type) } sdkModificator.commitChanges() } } } private fun getAttachedAnnotationsBuildNumbers(ideaJdk: Sdk): List<BuildNumber> = ideaJdk.rootProvider .getFiles(AnnotationOrderRootType.getInstance()) .mapNotNull { getAnnotationsBuildNumber(it) } private fun updateAnnotationsInBackground(ideaJdk: Sdk, project: Project, buildNumber: BuildNumber) { if (synchronized(this) { !buildNumberUpdateInProgress.add(buildNumber) }) { return } UpdateTask(project, ideaJdk, buildNumber).queue() } private inner class UpdateTask( project: Project, private val ideaJdk: Sdk, private val ideBuildNumber: BuildNumber ) : Task.Backgroundable(project, DevKitBundle.message("intellij.api.annotations.update.task.title", ideBuildNumber), true) { private val ideAnnotations = AtomicReference<IntelliJSdkExternalAnnotations>() override fun run(indicator: ProgressIndicator) { val annotations = tryDownloadAnnotations(ideBuildNumber) ?: throw Exception("No external annotations found for $ideBuildNumber in the Maven repository.") ideAnnotations.set(annotations) reattachAnnotations(project, ideaJdk, annotations) } private fun tryDownloadAnnotations(ideBuildNumber: BuildNumber): IntelliJSdkExternalAnnotations? { return try { PublicIntelliJSdkExternalAnnotationsRepository(project).downloadExternalAnnotations(ideBuildNumber) } catch (e: Exception) { throw Exception("Failed to download annotations for $ideBuildNumber", e) } } override fun onSuccess() { synchronized(this@IntelliJSdkExternalAnnotationsUpdater) { buildNumberLastFailedUpdateInstant.remove(ideBuildNumber) } } override fun onThrowable(error: Throwable) { synchronized(this@IntelliJSdkExternalAnnotationsUpdater) { buildNumberLastFailedUpdateInstant[ideBuildNumber] = Instant.now() } LOG.warn("Failed to update IntelliJ API external annotations", error) } override fun onFinished() { synchronized(this@IntelliJSdkExternalAnnotationsUpdater) { buildNumberUpdateInProgress.remove(ideBuildNumber) } } } }
apache-2.0
5ea077862be20a3cec2cef0c6315729d
36.739394
140
0.756184
5.033145
false
false
false
false
JiaweiWu/GiphyApp
app/src/main/java/com/jwu5/giphyapp/giphyhome/HomeFragment.kt
1
5790
package com.jwu5.giphyapp.giphyhome import android.content.res.Configuration import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.SearchView import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import com.jwu5.giphyapp.adapters.GiphyRecyclerViewAdapter import com.jwu5.giphyapp.R import com.jwu5.giphyapp.network.model.GiphyModel import java.util.ArrayList class HomeFragment : Fragment(), HomeView { private var mGiphyRecyclerView: RecyclerView? = null private var mGridLayoutManager: GridLayoutManager? = null private var mGiphyRecyclerViewAdapter: GiphyRecyclerViewAdapter? = null private var mQuery: String? = null private var mSearchView: SearchView? = null private var mProgressBar: ProgressBar? = null private var isLoading = false private var trending = true private var mOrientation: Int = 0 private var mHomePresenter: HomePresenter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true setHasOptionsMenu(true) mOrientation = activity.resources.configuration.orientation mHomePresenter = HomePresenter(this) mGiphyRecyclerViewAdapter = GiphyRecyclerViewAdapter(activity, TAB_NAME, mOrientation) } override fun onConfigurationChanged(newConfig: Configuration?) { mOrientation = newConfig!!.orientation mHomePresenter!!.updateUI(mGiphyRecyclerViewAdapter!!.items, mGridLayoutManager!!.findFirstVisibleItemPosition()) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = inflater!!.inflate(R.layout.fragment_giphy_view, container, false) mGiphyRecyclerView = v.findViewById(R.id.fragment_giphy_view_recycler_view) as RecyclerView mGridLayoutManager = GridLayoutManager(activity, 2) mGiphyRecyclerView!!.layoutManager = mGridLayoutManager mGiphyRecyclerView!!.adapter = mGiphyRecyclerViewAdapter mProgressBar = v.findViewById(R.id.fragment_progress_bar) as ProgressBar if (trending) { mHomePresenter!!.getTrendingList(LIMIT, 0) } mGiphyRecyclerView!!.addOnScrollListener(object : PaginationScrollListener(mGridLayoutManager!!) { override fun onLoadMore(totalItemCount: Int) { if (!isLoading) { if (trending) { mHomePresenter!!.getTrendingList(LIMIT, totalItemCount) } else { mHomePresenter!!.getSearchedList(mQuery, LIMIT, totalItemCount) } } } }) return v } override fun onCreateOptionsMenu(menu: Menu?, menuInflater: MenuInflater?) { super.onCreateOptionsMenu(menu, menuInflater) menuInflater!!.inflate(R.menu.fragment_giphy_view, menu) val searchItem = menu!!.findItem(R.id.menu_item_search) mSearchView = searchItem.actionView as SearchView mSearchView!!.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(s: String): Boolean { val result = s.trim { it <= ' ' }.replace(" ".toRegex(), "-").toLowerCase() mQuery = s mGiphyRecyclerViewAdapter!!.removeAll() mHomePresenter!!.getSearchedList(result, LIMIT, 0) mSearchView!!.clearFocus() return true } override fun onQueryTextChange(s: String): Boolean { return false } }) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item!!.itemId) { R.id.menu_item_clear -> { mSearchView!!.setQuery("", false) mSearchView!!.isIconified = true mHomePresenter!!.getTrendingList(LIMIT, 0) return true } else -> return super.onOptionsItemSelected(item) } } override fun showTrendingList(items: ArrayList<GiphyModel>?) { if (!trending) { mGiphyRecyclerViewAdapter!!.setItemList(items) trending = true return } mGiphyRecyclerViewAdapter!!.addItems(items) } override fun showSearchList(items: ArrayList<GiphyModel>?) { if (trending) { mGiphyRecyclerViewAdapter!!.setItemList(items) trending = false return } mGiphyRecyclerViewAdapter!!.addItems(items) } override fun setLoading() { mProgressBar!!.visibility = ProgressBar.VISIBLE isLoading = true } override fun setLoadingComplete() { mProgressBar!!.visibility = ProgressBar.INVISIBLE isLoading = false } override fun onResume() { super.onResume() mGiphyRecyclerViewAdapter!!.notifyDataSetChanged() } override fun updateAdapter(items: ArrayList<GiphyModel>?, position: Int) { mGiphyRecyclerViewAdapter = GiphyRecyclerViewAdapter(activity, TAB_NAME, mOrientation) mGiphyRecyclerViewAdapter!!.setItemList(items) mGiphyRecyclerView!!.adapter = mGiphyRecyclerViewAdapter mGiphyRecyclerView!!.scrollToPosition(position) } companion object { val TAB_NAME = "Home" private val LIMIT = 12 fun newInstance(): HomeFragment { return HomeFragment() } } }
mit
badfe2ce343074c12642cb56697b4aa7
34.521472
121
0.661485
5.416277
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RestrictedRetentionForExpressionAnnotationFactory.kt
5
5542
// 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.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe object RestrictedRetentionForExpressionAnnotationFactory : KotlinIntentionActionsFactory() { private val sourceRetention = "${StandardNames.FqNames.annotationRetention.asString()}.${AnnotationRetention.SOURCE.name}" private val sourceRetentionAnnotation = "@${StandardNames.FqNames.retention.asString()}($sourceRetention)" override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val annotationEntry = diagnostic.psiElement as? KtAnnotationEntry ?: return emptyList() val containingClass = annotationEntry.containingClass() ?: return emptyList() val retentionAnnotation = containingClass.annotation(StandardNames.FqNames.retention) val targetAnnotation = containingClass.annotation(StandardNames.FqNames.target) val expressionTargetArgument = if (targetAnnotation != null) findExpressionTargetArgument(targetAnnotation) else null return listOfNotNull( if (expressionTargetArgument != null) RemoveExpressionTargetFix(expressionTargetArgument) else null, if (retentionAnnotation == null) AddSourceRetentionFix(containingClass) else ChangeRetentionToSourceFix(retentionAnnotation) ) } private fun KtClass.annotation(fqName: FqName): KtAnnotationEntry? { return annotationEntries.firstOrNull { it.typeReference?.text?.endsWith(fqName.shortName().asString()) == true && analyze()[BindingContext.TYPE, it.typeReference]?.constructor?.declarationDescriptor?.fqNameSafe == fqName } } private fun findExpressionTargetArgument(targetAnnotation: KtAnnotationEntry): KtValueArgument? { val valueArgumentList = targetAnnotation.valueArgumentList ?: return null if (targetAnnotation.lambdaArguments.isNotEmpty()) return null for (valueArgument in valueArgumentList.arguments) { val argumentExpression = valueArgument.getArgumentExpression() ?: continue if (argumentExpression.text.contains(KotlinTarget.EXPRESSION.toString())) { return valueArgument } } return null } private class AddSourceRetentionFix(element: KtClass) : KotlinQuickFixAction<KtClass>(element) { override fun getText() = KotlinBundle.message("add.source.retention") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val added = element.addAnnotationEntry(KtPsiFactory(element).createAnnotationEntry(sourceRetentionAnnotation)) ShortenReferences.DEFAULT.process(added) } } private class ChangeRetentionToSourceFix(retentionAnnotation: KtAnnotationEntry) : KotlinQuickFixAction<KtAnnotationEntry>(retentionAnnotation) { override fun getText() = KotlinBundle.message("change.existent.retention.to.source") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val retentionAnnotation = element ?: return val psiFactory = KtPsiFactory(retentionAnnotation) val added = if (retentionAnnotation.valueArgumentList == null) { retentionAnnotation.add(psiFactory.createCallArguments("($sourceRetention)")) as KtValueArgumentList } else { if (retentionAnnotation.valueArguments.isNotEmpty()) { retentionAnnotation.valueArgumentList?.removeArgument(0) } retentionAnnotation.valueArgumentList?.addArgument(psiFactory.createArgument(sourceRetention)) } if (added != null) { ShortenReferences.DEFAULT.process(added) } } } private class RemoveExpressionTargetFix(expressionTargetArgument: KtValueArgument) : KotlinQuickFixAction<KtValueArgument>(expressionTargetArgument) { override fun getText() = KotlinBundle.message("remove.expression.target") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val expressionTargetArgument = element ?: return val argumentList = expressionTargetArgument.parent as? KtValueArgumentList ?: return if (argumentList.arguments.size == 1) { val annotation = argumentList.parent as? KtAnnotationEntry ?: return annotation.delete() } else { argumentList.removeArgument(expressionTargetArgument) } } } }
apache-2.0
e8a185ec8d776070d999641fceec3f10
47.614035
158
0.720137
5.672467
false
false
false
false
dahlstrom-g/intellij-community
platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalSystemProjectTest.kt
5
17545
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.service.project import com.intellij.compiler.CompilerConfiguration import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType.* import com.intellij.openapi.externalSystem.model.project.LibraryLevel import com.intellij.openapi.externalSystem.model.project.LibraryPathType import com.intellij.openapi.externalSystem.test.javaProject import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil import com.intellij.openapi.roots.* import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess import com.intellij.platform.externalSystem.testFramework.ExternalSystemProjectTestCase import com.intellij.platform.externalSystem.testFramework.ExternalSystemTestCase.collectRootsInside import com.intellij.platform.externalSystem.testFramework.toDataNode import com.intellij.pom.java.LanguageLevel import com.intellij.testFramework.IdeaTestUtil import com.intellij.util.PathUtil import junit.framework.TestCase import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.entry import org.junit.Test import java.io.File class ExternalSystemProjectTest : ExternalSystemProjectTestCase() { @Test fun `test module names deduplication`() { val projectModel = project { module("root", externalProjectPath = "root") module("root", externalProjectPath = "root/1") module("root", externalProjectPath = "root/2") module("root", externalProjectPath = "root/3") module("root", externalProjectPath = "another/root") module("root", externalProjectPath = "another/notRoot") module("root", externalProjectPath = "root/root/root") module("root", externalProjectPath = "root/root/root/root") module("root", externalProjectPath = "yetanother/root/root") module("group-root", externalProjectPath = "root") module("group-root", externalProjectPath = "root/group/root") module("group-root", externalProjectPath = "root/my/group/root") module("group-root", externalProjectPath = "root/my-group/root") } val modelsProvider = IdeModelsProviderImpl(project) applyProjectModel(projectModel) val expectedNames = arrayOf( "root", "1.root", "2.root", "3.root", "another.root", "notRoot.root", "root.root", "root.root.root", "yetanother.root.root", "group-root", "root.group-root", "group.root.group-root", "my-group.root.group-root" ) assertOrderedEquals(modelsProvider.modules.map { it.name }, *expectedNames) // check reimport with the same data applyProjectModel(projectModel) assertOrderedEquals(modelsProvider.modules.map { it.name }, *expectedNames) } @Test fun `test no duplicate library dependency is added on subsequent refresh when there is an unresolved library`() { val projectModel = project { module { lib("lib1") lib("lib2", unresolved = true) } } applyProjectModel(projectModel, projectModel) val modelsProvider = IdeModelsProviderImpl(project) val module = modelsProvider.findIdeModule("module") val entries = modelsProvider.getOrderEntries(module!!) val dependencies = mutableMapOf<String?, Int>() entries.groupingBy { (it as? LibraryOrderEntry)?.libraryName }.eachCountTo(dependencies).remove(null) assertThat(dependencies).containsExactly( entry("Test_external_system_id: lib1", 1), entry("Test_external_system_id: lib2", 1) ) } @Test fun `test no duplicate module dependency is added on subsequent refresh when duplicated dependencies exist`() { val projectModel = project { module("module1") module("module2") { moduleDependency("module1", DependencyScope.RUNTIME) moduleDependency("module1", DependencyScope.TEST) } } applyProjectModel(projectModel) val assertOrderEntries = { val modelsProvider = IdeModelsProviderImpl(project) val module = modelsProvider.findIdeModule("module2") val dependencies = modelsProvider.getOrderEntries(module!!) .filterIsInstance<ExportableOrderEntry>().map { it.presentableName to it.scope } val expected = listOf("module1" to DependencyScope.RUNTIME, "module1" to DependencyScope.TEST) assertThat(dependencies).containsExactlyInAnyOrderElementsOf(expected) } assertOrderEntries.invoke() // change dependency scope to test to get duplicated order entries with(ProjectDataManager.getInstance().createModifiableModelsProvider(project)) { val modifiableRootModel = getModifiableRootModel(findIdeModule("module2")) modifiableRootModel.orderEntries.filterIsInstance<ExportableOrderEntry>().forEach { it.scope = DependencyScope.TEST } runWriteAction { commit() } } applyProjectModel(projectModel) assertOrderEntries.invoke() } @Test fun `test optimized method for getting modules libraries order entries`() { val libBinPath = File(projectPath, "bin_path") val libSrcPath = File(projectPath, "source_path") val namedlibPath = File(projectPath, "named_lib") FileUtil.createDirectory(libBinPath) FileUtil.createDirectory(libSrcPath) val projectModel = project { module { lib("", level = LibraryLevel.MODULE) { roots(LibraryPathType.BINARY, libBinPath.absolutePath) } lib("", level = LibraryLevel.MODULE) { roots(LibraryPathType.BINARY, libSrcPath.absolutePath) } lib("named", level = LibraryLevel.MODULE) { roots(LibraryPathType.BINARY, namedlibPath.absolutePath) } } } applyProjectModel(projectModel, projectModel) val modelsProvider = IdeModelsProviderImpl(project) val projectNode = projectModel.toDataNode() val moduleNodeList = ExternalSystemApiUtil.findAll(projectNode, ProjectKeys.MODULE) assertThat(moduleNodeList).hasSize(1) val moduleNode = moduleNodeList.first() assertEquals("module", moduleNode.data.moduleName) val libraryDependencyDataList = ExternalSystemApiUtil.findAll(moduleNode, ProjectKeys.LIBRARY_DEPENDENCY) .filter { it.data.level == LibraryLevel.MODULE } .map { it.data } val libraryOrderEntries = modelsProvider.findIdeModuleLibraryOrderEntries(moduleNode.data, libraryDependencyDataList) assertThat(libraryOrderEntries).hasSize(3) for ((libraryEntry, libraryData) in libraryOrderEntries) { val expected = libraryData.target.getPaths(LibraryPathType.BINARY).map(PathUtil::getLocalPath) val actual = libraryEntry.getUrls(OrderRootType.CLASSES).map { PathUtil.getLocalPath(VfsUtilCore.urlToPath(it)) } assertThat(expected).containsExactlyInAnyOrderElementsOf(actual) } } private fun buildProjectModel(contentRoots: Map<ExternalSystemSourceType, List<String>>) = project { module { contentRoot { for ((key, values) in contentRoots) { values.forEach { folder(type = key, relativePath = it) } } } } } @Test fun `test changes in a project layout (content roots) could be detected on Refresh`() { val contentRoots = mutableMapOf( TEST to mutableListOf("src/test/resources", "/src/test/java", "src/test/groovy"), SOURCE to mutableListOf("src/main/resources", "src/main/java", "src/main/groovy"), EXCLUDED to mutableListOf(".gradle", "build") ) (contentRoots[TEST]!! union contentRoots[SOURCE]!!).forEach { FileUtil.createDirectory(File(projectPath, it)) } val projectModelInitial = buildProjectModel(contentRoots) contentRoots[SOURCE]!!.removeFirst() contentRoots[TEST]!!.removeFirst() val projectModelRefreshed = buildProjectModel(contentRoots) applyProjectModel(projectModelInitial, projectModelRefreshed) val modelsProvider = IdeModelsProviderImpl(project) val module = modelsProvider.findIdeModule("module")!! val entries = modelsProvider.getOrderEntries(module) val folders = mutableMapOf<String?, Int>() for (entry in entries) { if (entry is ModuleSourceOrderEntry) { val contentEntry = entry.rootModel.contentEntries.first() folders.merge("source", contentEntry.sourceFolders.size, Integer::sum) folders.merge("excluded", contentEntry.excludeFolders.size, Integer::sum) } } assertThat(folders).containsExactly(entry("source", 4), entry("excluded", 2)) } @Test fun `test import does not fail if filename contains space`() { val nameWithTrailingSpace = "source2 " val contentRoots = mapOf( SOURCE to listOf(" source1", nameWithTrailingSpace, "source 3") ) // note, dir.mkdirs() used at ExternalSystemProjectTestCase.createProjectSubDirectory -> FileUtil.ensureExists // will create "source2" instead of "source2 " on disk on Windows contentRoots.forEach { (_, v) -> v.forEach { createProjectSubDirectory(it) } } applyProjectModel(buildProjectModel(contentRoots), buildProjectModel(contentRoots)) val modelsProvider = IdeModelsProviderImpl(project) val module = modelsProvider.findIdeModule("module") if (module == null) { fail("Could not find single module") } else { val folders = ArrayList<String>() modelsProvider.getOrderEntries(module) .filterIsInstance<ModuleSourceOrderEntry>() .flatMap { it.rootModel.contentEntries.asIterable() } .forEach { contentEntry -> folders.addAll(contentEntry.sourceFolders.map { File(it.url).name }) } val expected = if (SystemInfo.isWindows) contentRoots[SOURCE]!! - nameWithTrailingSpace else contentRoots[SOURCE] TestCase.assertEquals(expected, folders) } } @Test fun `test excluded directories merge`() { val contentRoots = mutableMapOf( EXCLUDED to mutableListOf(".gradle", "build") ) val projectModelInitial = buildProjectModel(contentRoots) contentRoots[EXCLUDED]!!.removeFirst() contentRoots[EXCLUDED]!!.add("newExclDir") val projectModelRefreshed = buildProjectModel(contentRoots) applyProjectModel(projectModelInitial, projectModelRefreshed) val modelsProvider = IdeModelsProviderImpl(project) val module = modelsProvider.findIdeModule("module")!! val folders = mutableListOf<String>() modelsProvider.getOrderEntries(module) .filterIsInstance<ModuleSourceOrderEntry>() .flatMap { it.rootModel.contentEntries.asIterable() } .forEach { contentEntry -> folders.addAll(contentEntry.excludeFolders.map { File(it.url).name }) } assertThat(folders).containsExactlyInAnyOrderElementsOf(listOf(".gradle", "build", "newExclDir")) } @Test fun `test library dependency with sources path added on subsequent refresh`() { val libBinPath = File(projectPath, "bin_path") val libSrcPath = File(projectPath, "source_path") val libDocPath = File(projectPath, "doc_path") FileUtil.createDirectory(libBinPath) FileUtil.createDirectory(libSrcPath) FileUtil.createDirectory(libDocPath) applyProjectModel( project { module { lib("lib1", level = LibraryLevel.MODULE) { roots(LibraryPathType.BINARY, libBinPath.absolutePath) } } }, project { module { lib("lib1", level = LibraryLevel.MODULE) { roots(LibraryPathType.BINARY, libBinPath.absolutePath) roots(LibraryPathType.SOURCE, libSrcPath.absolutePath) } } }, project { module { lib("lib1", level = LibraryLevel.MODULE) { roots(LibraryPathType.BINARY, libBinPath.absolutePath) roots(LibraryPathType.SOURCE, libSrcPath.absolutePath) roots(LibraryPathType.DOC, libDocPath.absolutePath) } } } ) val modelsProvider = IdeModelsProviderImpl(project) val module = modelsProvider.findIdeModule("module")!! val dependencies = mutableMapOf<String?, Int>() for (entry in modelsProvider.getOrderEntries(module)) { if (entry is LibraryOrderEntry) { val name = entry.libraryName dependencies.merge(name, 1, Integer::sum) if ("Test_external_system_id: lib1" == name) { val classesUrls = entry.getUrls(OrderRootType.CLASSES) assertThat(classesUrls).hasSize(1) assertTrue(classesUrls.first().endsWith("bin_path")) val sourceUrls = entry.getUrls(OrderRootType.SOURCES) assertThat(sourceUrls).hasSize(1) assertTrue(sourceUrls.first().endsWith("source_path")) val docUrls = entry.getUrls(JavadocOrderRootType.getInstance()) assertThat(docUrls).hasSize(1) assertTrue(docUrls.first().endsWith("doc_path")) } else { fail() } } } assertThat(dependencies).containsExactly(entry("Test_external_system_id: lib1", 1)) } @Test fun `test package prefix setup`() { createProjectSubDirectory("src/main/java") applyProjectModel( project { module { contentRoot { folder(type = SOURCE, relativePath = "src/main/java", packagePrefix = "org.example") } } } ) assertSourcePackagePrefix("module", "src/main/java", "org.example") applyProjectModel( project { module { contentRoot { folder(type = SOURCE, relativePath = "src/main/java", packagePrefix = "org.jetbrains") } } } ) assertSourcePackagePrefix("module", "src/main/java", "org.jetbrains") applyProjectModel( project { module { contentRoot { folder(type = SOURCE, relativePath = "src/main/java", packagePrefix = "") } } } ) assertSourcePackagePrefix("module", "src/main/java", "org.jetbrains") } @Test fun `test project SDK configuration import`() { val myJdkName = "My JDK" val myJdkHome = IdeaTestUtil.requireRealJdkHome() val allowedRoots = mutableListOf<String>() allowedRoots.add(myJdkHome) allowedRoots.addAll(collectRootsInside(myJdkHome)) VfsRootAccess.allowRootAccess(testRootDisposable, *allowedRoots.toTypedArray()) runWriteAction { val oldJdk = ProjectJdkTable.getInstance().findJdk(myJdkName) if (oldJdk != null) { ProjectJdkTable.getInstance().removeJdk(oldJdk) } val jdkHomeDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(File(myJdkHome))!! val jdk = SdkConfigurationUtil.setupSdk(emptyArray(), jdkHomeDir, JavaSdk.getInstance(), true, null, myJdkName) assertNotNull("Cannot create JDK for $myJdkHome", jdk) ProjectJdkTable.getInstance().addJdk(jdk!!, project) } applyProjectModel( project { javaProject(compileOutputPath = "$projectPath/out", languageLevel = LanguageLevel.JDK_1_7, targetBytecodeVersion = "1.5") } ) val languageLevelExtension = LanguageLevelProjectExtension.getInstance(project) assertEquals(LanguageLevel.JDK_1_7, languageLevelExtension.languageLevel) val compilerConfiguration = CompilerConfiguration.getInstance(project) assertEquals("1.5", compilerConfiguration.projectBytecodeTarget) } private fun assertSourcePackagePrefix(moduleName: String, sourcePath: String, packagePrefix: String) { val module = runReadAction { ModuleManager.getInstance(project).findModuleByName(moduleName) } assertNotNull("Module $moduleName not found", module) assertSourcePackagePrefix(module!!, sourcePath, packagePrefix) } private fun assertSourcePackagePrefix(module: com.intellij.openapi.module.Module, sourcePath: String, packagePrefix: String) { val rootManger = ModuleRootManager.getInstance(module) val sourceFolder = findSourceFolder(rootManger, sourcePath) assertNotNull("Source folder $sourcePath not found in module ${module.name}", sourceFolder) assertEquals(packagePrefix, sourceFolder!!.packagePrefix) } private fun findSourceFolder(moduleRootManager: ModuleRootModel, sourcePath: String): SourceFolder? { val contentEntries = moduleRootManager.contentEntries val module = moduleRootManager.module val externalProjectPath = ExternalSystemApiUtil.getExternalProjectPath(module) ?: return null for (contentEntry in contentEntries) { for (sourceFolder in contentEntry.sourceFolders) { val folderPath = urlToPath(sourceFolder.url) val rootPath = urlToPath("$externalProjectPath/$sourcePath") if (folderPath == rootPath) return sourceFolder } } return null } private fun urlToPath(url: String): String { val path = VfsUtilCore.urlToPath(url) return FileUtil.toSystemIndependentName(path) } }
apache-2.0
44e92e2e515d9f2a9bb220dd51350b9f
39.615741
158
0.71291
4.797648
false
true
false
false
dahlstrom-g/intellij-community
plugins/settings-repository/src/RepositoryService.kt
9
2122
// 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.settingsRepository import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.util.NlsContexts import com.intellij.util.io.URLUtil import com.intellij.util.io.exists import com.intellij.util.io.isDirectory import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.transport.URIish import org.jetbrains.settingsRepository.git.createBareRepository import java.io.IOException import java.nio.file.Path import java.nio.file.Paths interface RepositoryService { fun checkUrl(uriString: String, project: Project? = null): @NlsContexts.DialogMessage String? { val uri = URIish(uriString) val isFile = uri.scheme == URLUtil.FILE_PROTOCOL || (uri.scheme == null && uri.host == null) return if (isFile) checkFileRepo(uriString, project) else null } private fun checkFileRepo(url: String, project: Project?): @NlsContexts.DialogMessage String? { val suffix = "/${Constants.DOT_GIT}" val file = Paths.get(if (url.endsWith(suffix)) url.substring(0, url.length - suffix.length) else url) if (file.exists()) { if (!file.isDirectory()) { return icsMessage("dialog.message.path.is.not.directory") } else if (isValidRepository(file)) { return null } } else if (!file.isAbsolute) { return icsMessage("specify.absolute.path.dialog.message") } if (MessageDialogBuilder .yesNo(icsMessage("init.dialog.title"), icsMessage("init.dialog.message", file)) .yesText(icsMessage("init.dialog.create.button")) .ask(project)) { return try { createBareRepository(file) null } catch (e: IOException) { e.message?.let { icsMessage("init.failed.message", it) } ?: icsMessage("init.failed.message.without.details") } } else { return "" } } // must be protected, kotlin bug fun isValidRepository(file: Path): Boolean }
apache-2.0
50589c545c0d002f50d4dfdf3c0b1939
35.603448
158
0.703582
4.018939
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/translate/src/main/kotlin/com/kotlin/translate/DescribeTextTranslationJob.kt
1
1813
// snippet-sourcedescription:[DescribeTextTranslationJob.kt demonstrates how to describe a translation job.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon Translate] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.translate // snippet-start:[translate.kotlin._describe_jobs.import] import aws.sdk.kotlin.services.translate.TranslateClient import aws.sdk.kotlin.services.translate.model.DescribeTextTranslationJobRequest import kotlin.system.exitProcess // snippet-end:[translate.kotlin._describe_jobs.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <jobId> Where: jobId - A translation job ID value. You can obtain this value from the BatchTranslation example. """ if (args.size != 1) { println(usage) exitProcess(0) } val jobId = args[0] describeTranslationJob(jobId) } // snippet-start:[translate.kotlin._describe_jobs.main] suspend fun describeTranslationJob(id: String?) { val textTranslationJobRequest = DescribeTextTranslationJobRequest { jobId = id!! } TranslateClient { region = "us-west-2" }.use { translateClient -> val jobResponse = translateClient.describeTextTranslationJob(textTranslationJobRequest) println("The job status is ${jobResponse.textTranslationJobProperties?.jobStatus}.") } } // snippet-end:[translate.kotlin._describe_jobs.main]
apache-2.0
6af39bf880d54241ddc12777b0d76d52
30.375
108
0.712079
4.120455
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/columnviewholder/ColumnViewHolderLoading.kt
1
9125
package jp.juggler.subwaytooter.columnviewholder import android.annotation.SuppressLint import android.view.GestureDetector import android.view.MotionEvent import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import jp.juggler.subwaytooter.column.getColumnName import jp.juggler.subwaytooter.column.startLoading import jp.juggler.subwaytooter.column.toAdapterIndex import jp.juggler.subwaytooter.column.toListIndex import jp.juggler.subwaytooter.util.ScrollPosition import jp.juggler.subwaytooter.view.ListDivider import jp.juggler.util.abs import java.io.Closeable private class ErrorFlickListener( private val cvh: ColumnViewHolder, ) : View.OnTouchListener, GestureDetector.OnGestureListener { private val gd = GestureDetector(cvh.activity, this) val density = cvh.activity.resources.displayMetrics.density @SuppressLint("ClickableViewAccessibility") override fun onTouch(v: View?, event: MotionEvent?) = event?.let { gd.onTouchEvent(it) } ?: false override fun onShowPress(e: MotionEvent) = Unit override fun onLongPress(e: MotionEvent) = Unit override fun onSingleTapUp(e: MotionEvent) = true override fun onDown(e: MotionEvent) = true override fun onScroll( e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float, ) = true override fun onFling( e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float, ): Boolean { val vx = velocityX.abs() val vy = velocityY.abs() if (vy < vx * 1.5f) { // フリック方向が上下ではない ColumnViewHolder.log.d("fling? not vertical view. $vx $vy") } else { val vyDp = vy / density val limit = 1024f ColumnViewHolder.log.d("fling? $vyDp/$limit") if (vyDp >= limit) { val column = cvh.column if (column != null && column.lastTask == null) { column.startLoading() } } } return true } } private class AdapterItemHeightWorkarea( val listView: RecyclerView, val adapter: ItemListAdapter, ) : Closeable { private val itemWidth = listView.width - listView.paddingLeft - listView.paddingRight private val widthSpec = View.MeasureSpec.makeMeasureSpec(itemWidth, View.MeasureSpec.EXACTLY) var lastViewType: Int = -1 var lastViewHolder: RecyclerView.ViewHolder? = null override fun close() { val childViewHolder = lastViewHolder if (childViewHolder != null) { adapter.onViewRecycled(childViewHolder) lastViewHolder = null } } // この関数はAdapterViewの項目の(marginを含む)高さを返す fun getAdapterItemHeight(adapterIndex: Int): Int { fun View.getTotalHeight(): Int { measure(widthSpec, ColumnViewHolder.heightSpec) val lp = layoutParams as? ViewGroup.MarginLayoutParams return measuredHeight + (lp?.topMargin ?: 0) + (lp?.bottomMargin ?: 0) } listView.findViewHolderForAdapterPosition(adapterIndex)?.itemView?.let { return it.getTotalHeight() } ColumnViewHolder.log.d("getAdapterItemHeight idx=$adapterIndex createView") val viewType = adapter.getItemViewType(adapterIndex) var childViewHolder = lastViewHolder if (childViewHolder == null || lastViewType != viewType) { if (childViewHolder != null) { adapter.onViewRecycled(childViewHolder) } childViewHolder = adapter.onCreateViewHolder(listView, viewType) lastViewHolder = childViewHolder lastViewType = viewType } adapter.onBindViewHolder(childViewHolder, adapterIndex) return childViewHolder.itemView.getTotalHeight() } } @SuppressLint("ClickableViewAccessibility") fun ColumnViewHolder.initLoadingTextView() { llLoading.setOnTouchListener(ErrorFlickListener(this)) } // 特定の要素が特定の位置に来るようにスクロール位置を調整する fun ColumnViewHolder.setListItemTop(listIndex: Int, yArg: Int) { var adapterIndex = column?.toAdapterIndex(listIndex) ?: return val adapter = statusAdapter if (adapter == null) { ColumnViewHolder.log.e("setListItemTop: missing status adapter") return } var y = yArg AdapterItemHeightWorkarea(listView, adapter).use { workarea -> while (y > 0 && adapterIndex > 0) { --adapterIndex y -= workarea.getAdapterItemHeight(adapterIndex) y -= ListDivider.height } } if (adapterIndex == 0 && y > 0) y = 0 listLayoutManager.scrollToPositionWithOffset(adapterIndex, y) } // この関数は scrollToPositionWithOffset 用のオフセットを返す fun ColumnViewHolder.getListItemOffset(listIndex: Int): Int { val adapterIndex = column?.toAdapterIndex(listIndex) ?: return 0 val childView = listLayoutManager.findViewByPosition(adapterIndex) ?: throw IndexOutOfBoundsException("findViewByPosition($adapterIndex) returns null.") // スクロールとともにtopは減少する // しかしtopMarginがあるので最大値は4である // この関数は scrollToPositionWithOffset 用のオフセットを返すので top - topMargin を返す return childView.top - ((childView.layoutParams as? ViewGroup.MarginLayoutParams)?.topMargin ?: 0) } fun ColumnViewHolder.findFirstVisibleListItem(): Int = when (val adapterIndex = listLayoutManager.findFirstVisibleItemPosition()) { RecyclerView.NO_POSITION -> throw IndexOutOfBoundsException() else -> column?.toListIndex(adapterIndex) ?: throw IndexOutOfBoundsException() } fun ColumnViewHolder.scrollToTop() { try { listView.stopScroll() } catch (ex: Throwable) { ColumnViewHolder.log.e(ex, "stopScroll failed.") } try { listLayoutManager.scrollToPositionWithOffset(0, 0) } catch (ex: Throwable) { ColumnViewHolder.log.e(ex, "scrollToPositionWithOffset failed.") } } fun ColumnViewHolder.scrollToTop2() { val statusAdapter = this.statusAdapter if (bindingBusy || statusAdapter == null) return if (statusAdapter.itemCount > 0) { scrollToTop() } } fun ColumnViewHolder.saveScrollPosition(): Boolean { val column = this.column when { column == null -> ColumnViewHolder.log.d("saveScrollPosition [$pageIdx] , column==null") column.isDispose.get() -> ColumnViewHolder.log.d("saveScrollPosition [$pageIdx] , column is disposed") listView.visibility != View.VISIBLE -> { val scrollSave = ScrollPosition() column.scrollSave = scrollSave ColumnViewHolder.log.d( "saveScrollPosition [$pageIdx] ${column.getColumnName(true)} , listView is not visible, save ${scrollSave.adapterIndex},${scrollSave.offset}" ) return true } else -> { val scrollSave = ScrollPosition(this) column.scrollSave = scrollSave ColumnViewHolder.log.d( "saveScrollPosition [$pageIdx] ${column.getColumnName(true)} , listView is visible, save ${scrollSave.adapterIndex},${scrollSave.offset}" ) return true } } return false } fun ColumnViewHolder.setScrollPosition(sp: ScrollPosition, deltaDp: Float = 0f) { val lastAdapter = listView.adapter if (column == null || lastAdapter == null) return sp.restore(this) // 復元した後に意図的に少し上下にずらしたい val dy = (deltaDp * activity.density + 0.5f).toInt() if (dy != 0) listView.postDelayed(Runnable { if (column == null || listView.adapter !== lastAdapter) return@Runnable try { val recycler = ColumnViewHolder.fieldRecycler.get(listView) as RecyclerView.Recycler val state = ColumnViewHolder.fieldState.get(listView) as RecyclerView.State listLayoutManager.scrollVerticallyBy(dy, recycler, state) } catch (ex: Throwable) { ColumnViewHolder.log.trace(ex) ColumnViewHolder.log.e("can't access field in class ${RecyclerView::class.java.simpleName}") } }, 20L) } // 相対時刻を更新する fun ColumnViewHolder.updateRelativeTime() = rebindAdapterItems() fun ColumnViewHolder.rebindAdapterItems() { for (childIndex in 0 until listView.childCount) { val adapterIndex = listView.getChildAdapterPosition(listView.getChildAt(childIndex)) if (adapterIndex == RecyclerView.NO_POSITION) continue statusAdapter?.notifyItemChanged(adapterIndex) } }
apache-2.0
f20f09a7bf67661d5e84daf5d69d07fb
33.284
157
0.650607
4.570466
false
false
false
false
subhalaxmin/Programming-Kotlin
Chapter07/src/main/kotlin/com/packt/chapter7/7.4.SafeNullAccess.kt
1
923
package com.packt.chapter7 class Person(name: String, val address: Address?) class Address(name: String, val postcode: String, val city: City?) class City(name: String, val country: Country?) class Country(val name: String) fun getCountryName(person: Person?): String? { var countryName: String? = null if (person != null) { val address = person.address if (address != null) { val city = address.city if (city != null) { val country = city.country if (country != null) { countryName = country.name } } } } return countryName } fun getCountryNameSafe(person: Person?): String? { return person?.address?.city?.country?.name } fun nullableAddress(): Address? = TODO() fun forceVariable() { val nullableName: String? = "george" val name: String = nullableName!! } fun forceFunction() { val postcode: String = nullableAddress()!!.postcode }
mit
458015f51b49e0edcbdbbd9f5bc8921c
22.666667
66
0.656555
3.736842
false
false
false
false
EddieRingle/statesman
runtime/src/main/kotlin/io/ringle/statesman/StateHost.kt
1
1608
package io.ringle.statesman import android.os.Bundle import android.support.annotation.CallSuper import android.util.SparseArray import java.util.* interface StateHost { companion object { @Suppress("nothing_to_inline") inline fun newManagedStates(): SparseArray<Bundle> = SparseArray() } val managedStates: SparseArray<Bundle> fun deleteState(key: Int) { managedStates.delete(key) } fun getState(key: Int): Bundle { var state = managedStates.get(key, null) if (state == null) { state = Bundle() state.putBoolean(Statesman.sKeyNewState, true) managedStates.put(key, state) } return state } @CallSuper fun restoreState(savedInstanceState: Bundle?) { if (savedInstanceState != null) { val keyList = savedInstanceState.getIntegerArrayList(Statesman.sKeyKeyList) if (keyList != null) { for (k in keyList) { if (savedInstanceState.containsKey(Statesman.sKeyState(k))) { managedStates.put(k, savedInstanceState.getBundle(Statesman.sKeyState(k))) } } } } } @CallSuper fun saveState(outState: Bundle) { val keyList = ArrayList<Int>(managedStates.size()) for ((k, s) in managedStates) { s.remove(Statesman.sKeyNewState) outState.putBundle(Statesman.sKeyState(k), s) keyList.add(k) } outState.putIntegerArrayList(Statesman.sKeyKeyList, keyList) } }
mit
ade9b0ad6bc1b1aa1547ef34c319bdb5
27.714286
98
0.598881
4.345946
false
false
false
false
flesire/ontrack
ontrack-extension-git/src/test/java/net/nemerosa/ontrack/extension/git/GitBranchesTemplateSynchronisationSourceTest.kt
1
3539
package net.nemerosa.ontrack.extension.git import net.nemerosa.ontrack.extension.git.model.BasicGitActualConfiguration import net.nemerosa.ontrack.extension.git.model.BasicGitConfiguration import net.nemerosa.ontrack.extension.git.model.GitConfiguration import net.nemerosa.ontrack.extension.git.service.GitService import net.nemerosa.ontrack.model.structure.Branch import net.nemerosa.ontrack.model.structure.NameDescription.nd import net.nemerosa.ontrack.model.structure.Project import org.junit.Before import org.junit.Test import org.mockito.Mockito.`when` import org.mockito.Mockito.mock import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class GitBranchesTemplateSynchronisationSourceTest { private lateinit var gitService: GitService private lateinit var source: GitBranchesTemplateSynchronisationSource private lateinit var gitConfiguration: GitConfiguration private lateinit var branch: Branch private lateinit var project: Project @Before fun before() { project = Project.of(nd("P", "Project")) branch = Branch.of(project, nd("B", "Branch")) gitConfiguration = BasicGitActualConfiguration.of(BasicGitConfiguration.empty()) gitService = mock(GitService::class.java) `when`(gitService.getProjectConfiguration(project)).thenReturn(gitConfiguration) `when`(gitService.getRemoteBranches(gitConfiguration)).thenReturn( listOf("master", "feature/ontrack-40-templating", "feature/ontrack-111-project-manager", "fix/ontrack-110") ) source = GitBranchesTemplateSynchronisationSource( gitService ) } @Test fun `Not applicable if branch not configured for Git`() { `when`(gitService.isBranchConfiguredForGit(branch)).thenReturn(false) assertFalse(source.isApplicable(branch)) } @Test fun `Applicable if branch configured for Git`() { `when`(gitService.isBranchConfiguredForGit(branch)).thenReturn(true) assertTrue(source.isApplicable(branch)) } @Test fun `Branches - no filter`() { assertEquals( listOf("feature/ontrack-111-project-manager", "feature/ontrack-40-templating", "fix/ontrack-110", "master"), source.getBranchNames(branch, GitBranchesTemplateSynchronisationSourceConfig("", "")) ) } @Test fun `Branches - includes all`() { assertEquals( listOf("feature/ontrack-111-project-manager", "feature/ontrack-40-templating", "fix/ontrack-110", "master"), source.getBranchNames(branch, GitBranchesTemplateSynchronisationSourceConfig("*", "")) ) } @Test fun `Branches - exclude master`() { assertEquals( listOf("feature/ontrack-111-project-manager", "feature/ontrack-40-templating", "fix/ontrack-110"), source.getBranchNames(branch, GitBranchesTemplateSynchronisationSourceConfig("", "master")) ) } @Test fun `Branches - include only`() { assertEquals( listOf("fix/ontrack-110"), source.getBranchNames(branch, GitBranchesTemplateSynchronisationSourceConfig("fix/*", "")) ) } @Test fun `Branches - include and exclude`() { assertEquals( listOf("feature/ontrack-111-project-manager"), source.getBranchNames(branch, GitBranchesTemplateSynchronisationSourceConfig("feature/*", "*templating")) ) } }
mit
c52cc58cf0c451adaab6a877298a6491
37.064516
124
0.691721
4.596104
false
true
false
false
algra/pact-jvm
pact-jvm-provider/src/main/kotlin/au/com/dius/pact/provider/ProviderVerifier.kt
1
2160
package au.com.dius.pact.provider import au.com.dius.pact.model.BrokerUrlSource import au.com.dius.pact.model.Interaction import au.com.dius.pact.model.Pact import au.com.dius.pact.provider.broker.PactBrokerClient import au.com.dius.pact.provider.broker.com.github.kittinunf.result.Result import groovy.lang.GroovyObjectSupport import mu.KotlinLogging import java.util.function.Function private val logger = KotlinLogging.logger {} @JvmOverloads fun <I> reportVerificationResults(pact: Pact<I>, result: Boolean, version: String, client: PactBrokerClient? = null) where I: Interaction { val source = pact.source when (source) { is BrokerUrlSource -> { val brokerClient = client ?: PactBrokerClient(source.pactBrokerUrl, source.options) publishResult(brokerClient, source, result, version, pact) } else -> logger.info { "Skipping publishing verification results for source $source" } } } private fun <I> publishResult(brokerClient: PactBrokerClient, source: BrokerUrlSource, result: Boolean, version: String, pact: Pact<I>) where I : Interaction { val publishResult = brokerClient.publishVerificationResults(source.attributes, result, version) if (publishResult is Result.Failure) { logger.warn { "Failed to publish verification results - ${publishResult.error.localizedMessage}" } logger.debug(publishResult.error) {} } else { logger.info { "Published verification result of '$result' for consumer '${pact.consumer}'" } } } open class ProviderVerifierBase : GroovyObjectSupport() { var projectHasProperty = Function<String, Boolean> { name -> !System.getProperty(name).isNullOrEmpty() } var projectGetProperty = Function<String, String?> { name -> System.getProperty(name) } /** * This will return true unless the pact.verifier.publishResults property has the value of "true" */ open fun publishingResultsDisabled(): Boolean { return !projectHasProperty.apply(PACT_VERIFIER_PUBLISHRESUTS) || projectGetProperty.apply(PACT_VERIFIER_PUBLISHRESUTS)?.toLowerCase() != "true" } companion object { const val PACT_VERIFIER_PUBLISHRESUTS = "pact.verifier.publishResults" } }
apache-2.0
85305ecdb0b8927157b8c68035f1988f
39.754717
159
0.75463
3.920145
false
false
false
false
chip2n/fretboard
app/src/main/java/org/chip2n/fretboard/view/FretboardView.kt
1
5443
package org.chip2n.fretboard.view import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import android.view.View import org.chip2n.fretboard.R import org.chip2n.fretboard.data.FretboardSetup import org.chip2n.fretboard.data.StringNote class FretboardView : View { var fretboardSetup: FretboardSetup var numberOfFrets: Int = 12 var numberOfStrings: Int = 6 var fretboardBgColor: Int = Color.WHITE var fretboardBgPaint: Paint = Paint() var stringColor: Int = Color.BLACK var stringWidth: Float = 8f var stringPaint: Paint = Paint() var fretColor: Int = Color.BLACK var fretWidth: Float = 8f var fretPaint: Paint = Paint() var nutWidth: Float = 32f var nutPaint: Paint = Paint() var fretDotRadius: Float = 20f var fretDotPaint: Paint = Paint() constructor(context: Context, attribSet: AttributeSet) : super(context, attribSet) { val typedArray = context.obtainStyledAttributes(attribSet, R.styleable.FretboardView) val fretboardSetupPattern = typedArray.getString(R.styleable.FretboardView_fretboardSetup) typedArray.recycle() if (fretboardSetupPattern == null) { fretboardSetup = FretboardSetup.createFromPattern(FretboardSetup.TUNING_STANDARD) } else { fretboardSetup = FretboardSetup.createFromPattern(fretboardSetupPattern) } fretboardBgPaint.color = fretboardBgColor stringPaint.color = stringColor stringPaint.strokeWidth = stringWidth fretPaint.color = fretColor fretPaint.strokeWidth = fretWidth nutPaint.color = fretColor nutPaint.strokeWidth = nutWidth fretDotPaint.color = fretColor fretDotPaint.isAntiAlias = true } fun displayFretboardPattern(pattern: Array<StringNote>) { } override fun onDraw(canvas: Canvas) { drawFretboard(canvas) } private fun drawFretboardBackground(canvas: Canvas) { canvas.drawPaint(fretboardBgPaint) } private fun drawFretboard(canvas: Canvas) { drawFretboardBackground(canvas) drawFretDots(canvas) drawNut(canvas) drawFrets(canvas) drawFretDots(canvas) drawStrings(canvas) } private fun drawFretDots(canvas: Canvas) { drawDotBetweenStrings(3, 4, 3, canvas) drawDotBetweenStrings(3, 4, 5, canvas) drawDotBetweenStrings(3, 4, 7, canvas) drawDotBetweenStrings(3, 4, 9, canvas) drawDotBetweenStrings(2, 3, 12, canvas) drawDotBetweenStrings(4, 5, 12, canvas) } //TODO: Don't draw dots outside canvas //TODO: Support dots past 12th fret private fun drawDotOnString(string: Int, fret: Int, canvas: Canvas) { val x = (calculateFretX(fret - 1) + calculateFretX(fret)) / 2 val y = calculateStringY(string) drawDot(x, y, canvas) } private fun drawDotBetweenStrings(string1: Int, string2: Int, fret: Int, canvas: Canvas) { val x = (calculateFretX(fret - 1) + calculateFretX(fret)) / 2 val y = (calculateStringY(string1) + calculateStringY(string2)) / 2 drawDot(x, y, canvas) } private fun drawNote(fret: Int, string: Int, canvas: Canvas) { canvas.drawCircle(x, y, fretDotRadius, fretDotPaint) } private fun drawDot(x: Float, y: Float, canvas: Canvas) { canvas.drawCircle(x, y, fretDotRadius, fretDotPaint) } private fun drawNut(canvas: Canvas) { val x = nutWidth / 2 val endY = height.toFloat() canvas.drawLine(x, 0f, x, endY, nutPaint) } private fun drawFrets(canvas: Canvas) { for (i in 1..numberOfFrets) drawFret(i, canvas) } private fun drawFret(fret: Int, canvas: Canvas) { val x = calculateFretX(fret) val endY = height.toFloat() canvas.drawLine(x, 0f, x, endY, fretPaint) } private fun calculateFretX(fret: Int): Float { val fretIndex = fret - 1 val numberOfLines = numberOfFrets + 1 val drawableWidth = width.toFloat() - fretWidth / 2 - nutWidth val lineStep = drawableWidth / (numberOfLines - 1) val startX = lineStep + nutWidth return startX + lineStep * fretIndex } private fun drawStrings(canvas: Canvas) { for (i in 1..numberOfStrings) drawString(i, canvas) } private fun drawString(string: Int, canvas: Canvas) { val y = calculateStringY(string) val endX = width.toFloat() canvas.drawLine(0f, y, endX, y, stringPaint) } private fun calculateStringY(string: Int): Float { val stringIndex = string - 1 val startY = stringWidth / 2 val drawableHeight = height.toFloat() - stringWidth val lineStep = drawableHeight / (numberOfStrings - 1) return startY + lineStep * stringIndex } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val width = measureWidth(widthMeasureSpec) val height = measureHeight(heightMeasureSpec) setMeasuredDimension(width, height) } private fun measureWidth(widthMeasureSpec: Int): Int { return resolveSizeAndState(1000, widthMeasureSpec, 0) } private fun measureHeight(heightMeasureSpec: Int): Int { return resolveSizeAndState(100, heightMeasureSpec, 0) } }
mit
6059aca70c01de9484b83dfcb58f8a51
30.462428
98
0.667095
3.967201
false
false
false
false
Masterzach32/SwagBot
src/main/kotlin/commands/InfoCommand.kt
1
1581
package xyz.swagbot.commands import discord4j.common.* import io.facet.chatcommands.* import io.facet.common.* import io.facet.common.dsl.* import xyz.swagbot.* import xyz.swagbot.util.* object InfoCommand : ChatCommand( name = "Info", aliases = setOf("info") ) { override fun DSLCommandNode<ChatCommandSource>.register() { runs { message.reply(baseTemplate.and { title = "SwagBot v3 ${if (EnvVars.CODE_ENV == "test") "Development Version" else ""} (${EnvVars.CODE_VERSION})" description = """ SwagBot is a music bot with many additional features. Type `${EnvVars.DEFAULT_COMMAND_PREFIX}help` to see more commands! Learn more about SwagBot at https://swagbot.xyz Follow SwagBot on Twitter for updates: https://twitter.com/DiscordSwagBot Check out the development for SwagBot at: https://github.com/Masterzach32/SwagBot Help development of SwagBot by donating to my PayPal: https://paypal.me/ultimatedoge Or pledge a small amount on Patreon: https://patreon.com/ultimatedoge Join the SwagBot support server: https://discord.me/swagbothub Want to add SwagBot to your server? Click the link below: https://discordapp.com/oauth2/authorize?client_id=${client.selfId.asLong()}&scope=bot&permissions=87149640 """.trimIndent() footer( "\u00a9 SwagBot 2016-2020. Written in Kotlin. Built off of Discord4J " + "${GitProperties.getProperties()[GitProperties.APPLICATION_VERSION]}", null ) }) } } }
gpl-2.0
c194a01e9e0d9cff0d2a882615578b8e
33.369565
127
0.674257
3.932836
false
false
false
false
SixRQ/KAXB
src/main/kotlin/com/sixrq/kaxb/parsers/XmlParser.kt
1
5230
/* * Copyright 2017 SixRQ Ltd. * * 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.sixrq.kaxb.parsers import org.w3c.dom.Element import org.w3c.dom.Node import org.w3c.dom.NodeList import java.io.File import javax.xml.parsers.DocumentBuilderFactory class XmlParser(val filename: String, val packageName: String) { val root: Element by lazy { val resource = ClassLoader.getSystemClassLoader().getResource(filename) val xmlFile = if (resource == null) File(filename) else File(resource.toURI().schemeSpecificPart) val dbFactory = DocumentBuilderFactory.newInstance() val dBuilder = dbFactory.newDocumentBuilder() dBuilder.parse(xmlFile).documentElement } val xmlns: String by lazy { root.getAttribute("xmlns") } val primitiveTypeMapping: MutableMap<String, String> = hashMapOf() fun generate() : Map<String, Tag> { val elements = root.childNodes val schema = Schema(xmlns) val classes: MutableMap<String, Tag> = hashMapOf() processElements(schema, elements) schema.includes.forEach { val xmlParser = XmlParser(it, packageName) classes.putAll(xmlParser.generate()) } primitiveTypeMapping.putAll(extractBasicTypes(schema)) classes.putAll(extractEnumerations(schema)) classes.putAll(extractClasses(schema)) classes.putAll(extractQNames(schema)) return classes } private fun extractEnumerations(schema: Schema) : Map<String, Tag> { val enumerations: MutableMap<String, Tag> = hashMapOf() schema.children.filter { it is SimpleType && it.children.filter { it is Restriction && it.children.filter { it is Enumeration }.isNotEmpty() }.isNotEmpty() }.forEach { enumerations.put(it.name, it) } return enumerations } private fun extractQNames(schema: Schema) : Map<String, Tag> { val qNames: MutableMap<String, Tag> = hashMapOf() schema.children.filter { it is com.sixrq.kaxb.parsers.Element }.forEach { qNames.put(it.name, it) } return qNames } private fun extractClasses(schema: Schema) : Map<String, Tag> { val classes: MutableMap<String, Tag> = hashMapOf() schema.children.filter { it is ComplexType }.forEach { classes.put(it.name, it) } return classes } private fun extractBasicTypes(schema: Schema) : Map<String, String> { val basicTypes: MutableMap<String, String> = hashMapOf() schema.children.filter { it is SimpleType && it.children.filter { it is Restriction && it.children.filter { it is Enumeration }.isEmpty()}.isNotEmpty()}.forEach { basicTypes.put(it.name, (it.children.filter { it is Restriction }[0] as Restriction).extractType()) } return basicTypes } private fun processElements(tag: Tag, elements: NodeList) { for (index in 0..(elements.length - 1)) { val item = elements.item(index) val childTag = { when (item.nodeName) { "xsd:complexType" -> ComplexType(xmlns, packageName) "xsd:simpleType" -> SimpleType(xmlns, packageName) "xsd:element" -> Element(xmlns, primitiveTypeMapping) "xsd:any" -> AnyElement(xmlns, primitiveTypeMapping) "xsd:extension" -> Extension(xmlns, primitiveTypeMapping) "xsd:annotation" -> Annotation(xmlns) "xsd:documentation" -> Documentation(xmlns) "xsd:sequence" -> Sequence(xmlns) "xsd:restriction" -> Restriction(xmlns) "xsd:enumeration" -> Enumeration(xmlns) "xsd:simpleContent" -> SimpleContent(xmlns) "xsd:attribute" -> Attribute(xmlns, primitiveTypeMapping) "xsd:include" -> Include(xmlns) else -> Tag(xmlns) } }.invoke() if (item.hasAttributes() || item.hasChildNodes()) { childTag.processAttributes(item) processElements(childTag, item.childNodes) if (childTag is Include) { tag.includes.add(childTag.schemaLocation) } else { tag.children.add(childTag) } } if (item.nodeType == Node.TEXT_NODE) { tag.processText(item) } } } }
apache-2.0
117b4fe849250e0ecc337a5d602675f7
39.238462
111
0.595602
4.543875
false
false
false
false
flamurey/koltin-func
src/main/kotlin/com/flamurey/kfunc/collections/list.kt
1
3705
package com.flamurey.kfunc.collections import com.flamurey.kfunc.core.Monoid sealed class List<out T> { var hashCode: Int = 0 object Nil : List<Nothing>() class Cons<out T>(val head: T, val tail: List<T>) : List<T>() final fun drop(n: Int): List<T> { tailrec fun loop(nn: Int, l: List<T>): List<T> = if (nn == 0) l else when (l) { is Cons<T> -> loop(nn - 1, l.tail) else -> Nil } return loop(n, this) } fun dropWhile(f: (T) -> Boolean): List<T> { tailrec fun loop(l: List<T>): List<T> = when (l) { is Nil -> Nil is Cons<T> -> if (f(l.head)) loop(l.tail) else l } return loop(this) } fun <B> foldLeft(init: B, f: (B, T) -> B): B { tailrec fun loop(l: List<T>, acc: B): B = when (l) { is Cons<T> -> loop(l.tail, f(acc, l.head)) else -> acc } return loop(this, init) } fun reverse(): List<T> = foldLeft(Nil as List<T>) { acc, x -> Cons(x, acc) } fun <B> foldRight(z: B, f: (T, B) -> B): B = reverse().foldLeft(z) { acc, x -> f(x, acc) } fun <B> map(f: (T) -> B): List<B> = foldRight(Nil as List<B>) { x, acc -> Cons(f(x), acc) } fun init(): List<T> = when (this) { is Cons<T> -> if (this.tail === Nil) Nil else Cons(this.head, this.tail.init()) else -> Nil } override fun toString(): String { tailrec fun loop(delimiter: String, s: StringBuilder, l: List<T>): String = when (l) { is Nil -> s.toString() is Cons<T> -> { s.append(delimiter) s.append(l.head) loop(",", s, l.tail) } } val list = loop("", StringBuilder(), this) return "[$list]" } fun tail(): List<T> = when (this) { is Nil -> Nil is Cons<T> -> this.tail } override fun equals(other: Any?): Boolean { if (other === null) return false if (other !is List<*>) return false tailrec fun loop(self: List<T>, other: List<*>): Boolean = when (self) { is Cons<T> -> when (other) { is Cons<*> -> if (self.head != other.head) false else loop(self.tail, other.tail) else -> false } else -> other is Nil } return loop(this, other) } override fun hashCode(): Int { if (hashCode == 0) { fun loop(l: List<T>, result: Int): Int = when (l) { is Cons<T> -> { val headHashCode = l.head?.hashCode() ?: 1 loop(l.tail, 31 * result + headHashCode) } else -> result } hashCode = loop(this, 1) } return hashCode } companion object { operator fun <T> invoke(vararg data: T): List<T> { tailrec fun loop(acc: List<T>, index: Int): List<T> = if (index < 0) acc else loop(Cons(data[index], acc), index - 1) return loop(Nil, data.size - 1) } fun <T> reverse(vararg data: T): List<T> { tailrec fun loop(acc: List<T>, index: Int): List<T> = if (index >= data.size) acc else loop(Cons(data[index], acc), index + 1) return loop(Nil, 0) } } } fun <T> List<T>.setHead(head: T): List<T> = when (this) { is List.Nil -> List.Nil is List.Cons -> List.Cons(head, this.tail) } fun <T> List<T>.appendLeft(l: List<T>): List<T> = l.foldRight(this) { x, acc -> List.Cons(x, acc) } fun <T> List<T>.appendRight(l: List<T>): List<T> = this.foldRight(l) { x, acc -> List.Cons(x, acc) } fun <T> List<T>.appendLeft(x: T): List<T> = List.Cons(x, this) operator fun <T> List<T>.plus(x: T): List<T> = this.appendLeft(x) fun <T> List<T>.concatenate(m: Monoid<T>) = foldLeft(m.zero()) { acc, x -> m.op(acc, x)}
mit
3e2dd61ff01dbe6e7f3648412ebf3466
25.276596
88
0.520108
2.938144
false
false
false
false
HTWDD/HTWDresden
app/src/main/java/de/htwdd/htwdresden/ui/models/Overview.kt
1
8181
package de.htwdd.htwdresden.ui.models import androidx.databinding.ObservableField import de.htwdd.htwdresden.BR import de.htwdd.htwdresden.R import de.htwdd.htwdresden.interfaces.Identifiable import de.htwdd.htwdresden.interfaces.Modelable import de.htwdd.htwdresden.utils.extensions.format import de.htwdd.htwdresden.utils.extensions.toColor import de.htwdd.htwdresden.utils.extensions.toSHA256 import de.htwdd.htwdresden.utils.holders.StringHolder //-------------------------------------------------------------------------------------------------- Protocols interface Overviewable: Identifiable<OverviewableModels> interface OverviewableModels: Modelable //-------------------------------------------------------------------------------------------------- Schedule Item class OverviewScheduleItem(private val item: Timetable): Overviewable { override val viewType: Int get() = R.layout.list_item_overview_schedule_bindable override val bindings by lazy { ArrayList<Pair<Int, OverviewableModels>>().apply { add(BR.overviewScheduleModel to model) } } private val model = OverviewScheduleModel() private val sh: StringHolder by lazy { StringHolder.instance } init { model.apply { name.set(item.name) setProfessor(item.professor) type.set(with(item.type) { when { startsWith("v", true) -> sh.getString(R.string.lecture) startsWith("ü", true) -> sh.getString(R.string.excersise) startsWith("p", true) -> sh.getString(R.string.practical) startsWith("b", true) -> sh.getString(R.string.block) startsWith("r", true) -> sh.getString(R.string.requested) else -> sh.getString(R.string.unknown) } }) beginTime.set(item.beginTime.format("HH:mm")) endTime.set(item.endTime.format("HH:mm")) val colors = sh.getStringArray(R.array.timetableColors) val colorPosition = Integer.parseInt("${item.name} - ${item.professor}".toSHA256().subSequence(0..5).toString(), 16) % colors.size lessonColor.set(colors[colorPosition].toColor()) setRooms(item.rooms) } } override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode() = item.hashCode() } //-------------------------------------------------------------------------------------------------- FreeDay Item class OverviewFreeDayItem: Overviewable { override val viewType: Int get() = R.layout.list_item_overview_free_day_bindable override val bindings: ArrayList<Pair<Int, OverviewableModels>> get() = ArrayList() override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode() = viewType * 31 } //-------------------------------------------------------------------------------------------------- Mensa Item class OverviewMensaItem(private val item: Meal): Overviewable { override val viewType: Int get() = R.layout.list_item_overview_mensa_bindable override val bindings by lazy { ArrayList<Pair<Int, OverviewableModels>>().apply { add(BR.overviewMensaModel to model) } } private val model = OverviewMensaModel() init { model.apply { name.set(item.name) } } override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode() = item.hashCode() } //-------------------------------------------------------------------------------------------------- Grade Item class OverviewGradeItem(private val grades: String, private val credits: Float): Overviewable { override val viewType: Int get() = R.layout.list_item_overview_grade_bindable override val bindings by lazy { ArrayList<Pair<Int, OverviewableModels>>().apply { add(BR.overviewGradeModel to model) } } private val model = OverviewGradeModel() private val sh by lazy { StringHolder.instance } init { model.apply { grades.set(sh.getString(R.string.grades, [email protected])) credits.set(sh.getString(R.string.exams_stats_count_credits, [email protected])) } } override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode(): Int { var result = grades.hashCode() result = 31 * result + credits.hashCode() return result } } //-------------------------------------------------------------------------------------------------- Header Item class OverviewHeaderItem(private val header: String, private val subheader: String): Overviewable { override val viewType: Int get() = R.layout.list_item_overview_header_bindable override val bindings by lazy { ArrayList<Pair<Int, OverviewableModels>>().apply { add(BR.overviewHeaderModel to model) } } private val model = OverviewHeaderModel() var credits: String get() = model.subheader.get() ?: "" set(value) = model.subheader.set(value) init { model.apply { header.set([email protected]) subheader.set([email protected]) } } override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode(): Int { var result = header.hashCode() result = 31 * result + subheader.hashCode() return result } } //-------------------------------------------------------------------------------------------------- StudyGroup Item class OverviewStudyGroupItem: Overviewable { override val viewType: Int get() = R.layout.list_item_overview_no_studygroup_bindable override val bindings: ArrayList<Pair<Int, OverviewableModels>> get() = ArrayList() override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode() = 31 * viewType } //-------------------------------------------------------------------------------------------------- Login Item class OverviewLoginItem: Overviewable { override val viewType: Int get() = R.layout.list_item_overview_no_login_bindable override val bindings: ArrayList<Pair<Int, OverviewableModels>> get() = ArrayList() override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode() = 31 * viewType } //-------------------------------------------------------------------------------------------------- Schedule Model class OverviewScheduleModel: OverviewableModels { val name = ObservableField<String>() val professor = ObservableField<String>() val type = ObservableField<String>() val beginTime = ObservableField<String>() val endTime = ObservableField<String>() val rooms = ObservableField<String>() val hasProfessor = ObservableField<Boolean>() val hasRooms = ObservableField<Boolean>() val lessonColor = ObservableField<Int>() fun setProfessor(professor: String?) { hasProfessor.set(!professor.isNullOrEmpty()) this.professor.set(professor) } fun setRooms(list: List<String>) { hasRooms.set(!list.isNullOrEmpty()) rooms.set(list.joinToString(", ")) } } //-------------------------------------------------------------------------------------------------- Mensa Model class OverviewMensaModel: OverviewableModels { val name = ObservableField<String>() } //-------------------------------------------------------------------------------------------------- Grade Model class OverviewGradeModel: OverviewableModels { val grades = ObservableField<String>() val credits = ObservableField<String>() } //-------------------------------------------------------------------------------------------------- Header Model class OverviewHeaderModel: OverviewableModels { val header = ObservableField<String>() val subheader = ObservableField<String>() }
mit
6d800a61344af9c636831dcd0c1d111c
33.812766
142
0.55709
4.869048
false
false
false
false
leafclick/intellij-community
platform/lang-impl/src/com/intellij/refactoring/suggested/PerformSuggestedRefactoring.kt
1
10684
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.suggested import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CustomShortcutSet import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.impl.LaterInvocator import com.intellij.openapi.command.executeCommand import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.markup.HighlighterLayer import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.suggested.SuggestedRefactoringExecution.NewParameterValue import com.intellij.ui.awt.RelativePoint import java.awt.Font import java.awt.Insets import java.awt.Point import java.awt.Toolkit import javax.swing.JComponent import javax.swing.UIManager internal fun performSuggestedRefactoring( project: Project, editor: Editor, popupAnchorComponent: JComponent?, popupAnchorPoint: Point?, showReviewBalloon: Boolean, actionPlace: String ) { PsiDocumentManager.getInstance(project).commitAllDocuments() val state = (SuggestedRefactoringProviderImpl.getInstance(project).state ?: return) .let { it.refactoringSupport.availability.refineSignaturesWithResolve(it) } if (state.syntaxError || state.oldSignature == state.newSignature) return val refactoringSupport = state.refactoringSupport when (val refactoringData = refactoringSupport.availability.detectAvailableRefactoring(state)) { is SuggestedRenameData -> { val popup = RenamePopup(refactoringData.oldName, refactoringData.declaration.name!!) fun doRefactor() { SuggestedRefactoringFeatureUsage.logEvent(SuggestedRefactoringFeatureUsage.REFACTORING_PERFORMED, refactoringData, state, actionPlace) performWithDumbEditor(editor) { refactoringSupport.execution.rename(refactoringData, project, editor) } // no refactoring availability anymore even if no usages updated SuggestedRefactoringProvider.getInstance(project).reset() } if (!showReviewBalloon || ApplicationManager.getApplication().isHeadlessEnvironment) { doRefactor() return } val rangeToHighlight = state.refactoringSupport.nameRange(state.declaration)!! val callbacks = createAndShowBalloon<Unit>( popup, project, editor, popupAnchorComponent, popupAnchorPoint, rangeToHighlight, commandName = RefactoringBundle.message("suggested.refactoring.rename.command.name"), doRefactoring = { doRefactor() }, onEnter = ::doRefactor, isEnterEnabled = { true }, isEscapeEnabled = { true }, onClosed = { isOk -> if (!isOk) { SuggestedRefactoringFeatureUsage.logEvent(SuggestedRefactoringFeatureUsage.POPUP_CANCELED, refactoringData, state, actionPlace) } } ) popup.onRefactor = { callbacks.onOk(Unit) } SuggestedRefactoringFeatureUsage.logEvent(SuggestedRefactoringFeatureUsage.POPUP_SHOWN, refactoringData, state, actionPlace) } is SuggestedChangeSignatureData -> { fun doRefactor(newParameterValues: List<NewParameterValue>) { SuggestedRefactoringFeatureUsage.logEvent(SuggestedRefactoringFeatureUsage.REFACTORING_PERFORMED, refactoringData, state, actionPlace) performWithDumbEditor(editor) { refactoringSupport.execution.changeSignature(refactoringData, newParameterValues, project, editor) } // no refactoring availability anymore even if no usages updated SuggestedRefactoringProvider.getInstance(project).reset() } val newParameterData = refactoringSupport.ui.extractNewParameterData(refactoringData) if (!showReviewBalloon || ApplicationManager.getApplication().isHeadlessEnvironment) { val newParameterValues = if (ApplicationManager.getApplication().isUnitTestMode) { // for testing newParameterData.indices.map { _suggestedChangeSignatureNewParameterValuesForTests?.invoke(it) ?: NewParameterValue.None } } else { newParameterData.map { NewParameterValue.None } } doRefactor(newParameterValues) return } val presentationModel = refactoringSupport.ui.buildSignatureChangePresentation( refactoringData.oldSignature, refactoringData.newSignature ) val screenSize = editor.component.graphicsConfiguration.device.defaultConfiguration.bounds.size val component = ChangeSignaturePopup( presentationModel, refactoringData.nameOfStuffToUpdate, newParameterData, project, refactoringSupport, refactoringData.declaration.language, editor.colorsScheme, screenSize ) val rangeToHighlight = state.refactoringSupport.signatureRange(refactoringData.declaration)!! val callbacks = createAndShowBalloon( component, project, editor, popupAnchorComponent, popupAnchorPoint, rangeToHighlight, commandName = RefactoringBundle.message("suggested.refactoring.change.signature.command.name", refactoringData.nameOfStuffToUpdate), doRefactoring = ::doRefactor, onEnter = component::onEnter, isEnterEnabled = component::isEnterEnabled, isEscapeEnabled = component::isEscapeEnabled, onClosed = { isOk -> if (!isOk) { SuggestedRefactoringFeatureUsage.logEvent(SuggestedRefactoringFeatureUsage.POPUP_CANCELED, refactoringData, state, actionPlace) } } ) component.onOk = callbacks.onOk component.onNext = callbacks.onNext SuggestedRefactoringFeatureUsage.logEvent(SuggestedRefactoringFeatureUsage.POPUP_SHOWN, refactoringData, state, actionPlace) } } } private data class BalloonCallbacks<TData>(val onOk: (TData) -> Unit, val onNext: () -> Unit) private fun <TData> createAndShowBalloon( content: JComponent, project: Project, editor: Editor, popupAnchorComponent: JComponent?, popupAnchorPoint: Point?, rangeToHighlight: TextRange, commandName: String, doRefactoring: (TData) -> Unit, onEnter: () -> Unit, isEnterEnabled: () -> Boolean, isEscapeEnabled: () -> Boolean, onClosed: (isOk: Boolean) -> Unit ): BalloonCallbacks<TData> { val builder = JBPopupFactory.getInstance() .createDialogBalloonBuilder(content, null) .setRequestFocus(true) .setHideOnClickOutside(true) .setCloseButtonEnabled(false) .setAnimationCycle(0) .setBlockClicksThroughBalloon(true) .setContentInsets(Insets(0, 0, 0, 0)) val borderColor = UIManager.getColor("InplaceRefactoringPopup.borderColor") if (borderColor != null) { builder.setBorderColor(borderColor) } val balloon = builder.createBalloon() positionAndShowBalloon(balloon, popupAnchorComponent, popupAnchorPoint, editor, rangeToHighlight) fun hideBalloonAndRefactor(data: TData) { balloon.hide(true) executeCommand(project, name = commandName, command = { doRefactoring(data) }) } object : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { onEnter() } override fun update(e: AnActionEvent) { e.presentation.isEnabled = isEnterEnabled() } }.registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER"), content, balloon) object : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { balloon.hide(false) } override fun update(e: AnActionEvent) { e.presentation.isEnabled = isEscapeEnabled() } }.registerCustomShortcutSet(CustomShortcutSet.fromString("ESCAPE"), content, balloon) val attributes = TextAttributes( null, editor.colorsScheme.getColor(EditorColors.CARET_ROW_COLOR), null, null, Font.PLAIN ) val highlighter = editor.markupModel.addRangeHighlighter( rangeToHighlight.startOffset, rangeToHighlight.endOffset, HighlighterLayer.FIRST, attributes, HighlighterTargetArea.LINES_IN_RANGE ) LaterInvocator.enterModal(balloon) Disposer.register(balloon, Disposable { LaterInvocator.leaveModal(balloon) editor.markupModel.removeHighlighter(highlighter) }) balloon.addListener(object : JBPopupListener { override fun onClosed(event: LightweightWindowEvent) { onClosed(event.isOk) } }) return BalloonCallbacks( onOk = ::hideBalloonAndRefactor, onNext = { balloon.revalidate() } ) } private fun positionAndShowBalloon( balloon: Balloon, popupAnchorComponent: JComponent?, popupAnchorPoint: Point?, editor: Editor, signatureRange: TextRange ) { if (popupAnchorComponent != null && popupAnchorPoint != null) { balloon.show(RelativePoint(popupAnchorComponent, popupAnchorPoint), Balloon.Position.below) } else { val top = RelativePoint(editor.contentComponent, editor.offsetToXY(signatureRange.startOffset)) val bottom = RelativePoint( editor.contentComponent, editor.offsetToXY(signatureRange.endOffset).apply { y += editor.lineHeight }) val caretXY = editor.offsetToXY(editor.caretModel.offset) val screenSize = Toolkit.getDefaultToolkit().screenSize if (top.screenPoint.y > screenSize.height - bottom.screenPoint.y) { balloon.show( RelativePoint(editor.contentComponent, Point(caretXY.x, top.originalPoint.y)), Balloon.Position.above ) } else { balloon.show( RelativePoint(editor.contentComponent, Point(caretXY.x, bottom.originalPoint.y)), Balloon.Position.below ) } } } private fun performWithDumbEditor(editor: Editor, action: () -> Unit) { (editor as? EditorImpl)?.startDumb() try { action() } finally { (editor as? EditorImpl)?.stopDumbLater() } } // for testing var _suggestedChangeSignatureNewParameterValuesForTests: ((index: Int) -> NewParameterValue)? = null
apache-2.0
745e11d418280ca455bd3647326d92a7
34.613333
142
0.740453
4.894182
false
false
false
false
blokadaorg/blokada
android5/app/src/main/java/ui/CommandActivity.kt
1
6198
/* * This file is part of Blokada. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package ui import android.app.IntentService import android.content.Intent import android.content.Intent.ACTION_VIEW import android.net.Uri import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import model.BlokadaException import repository.Repos import service.ContextService import service.EnvironmentService import service.LogService import service.NotificationService import ui.utils.cause import utils.ExecutingCommandNotification import utils.Logger import java.util.* enum class Command { OFF, ON, DNS, LOG, ACC, ESCAPE, TOAST, DOH } const val ACC_MANAGE = "manage_account" const val OFF = "off" const val ON = "on" private typealias Param = String class CommandActivity : AppCompatActivity() { private val log = Logger("Command") private lateinit var tunnelVM: TunnelViewModel private lateinit var settingsVM: SettingsViewModel private val env by lazy { EnvironmentService } private val appRepo by lazy { Repos.app } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) tunnelVM = ViewModelProvider(app()).get(TunnelViewModel::class.java) settingsVM = ViewModelProvider(app()).get(SettingsViewModel::class.java) interpretCommand(intent.data.toString())?.let { val (cmd, param) = it log.w("Received command: $cmd") try { execute(cmd, param) log.v("Command executed successfully") } catch (ex: Exception) { log.e("Could not execute command".cause(ex)) } } ?: run { log.e("Received unknown command: ${intent.data}") } finish() } private fun execute(command: Command, param: Param?) { when (command) { Command.OFF -> { if (env.isLibre()) tunnelVM.turnOff() else GlobalScope.launch { appRepo.pauseApp(Date()) } } Command.ON -> { if (env.isLibre()) tunnelVM.turnOn() else GlobalScope.launch { appRepo.unpauseApp() } } Command.LOG -> LogService.shareLog() Command.ACC -> { if (param == ACC_MANAGE) { log.v("Starting account management screen") val intent = Intent(this, MainActivity::class.java).also { it.flags = Intent.FLAG_ACTIVITY_NEW_TASK it.putExtra(MainActivity.ACTION, ACC_MANAGE) } startActivity(intent) } else throw BlokadaException("Unknown param for command ACC: $param, ignoring") } Command.ESCAPE -> { if (param == null) { settingsVM.setEscaped(true) } else { val versionCode = param.toInt() if (EnvironmentService.getVersionCode() <= versionCode) { settingsVM.setEscaped(true) } else { log.v("Ignoring escape command, too new version code") } } } Command.TOAST -> { Toast.makeText(this, param, Toast.LENGTH_LONG).show() } else -> { throw BlokadaException("Unknown command: $command") } } } private fun interpretCommand(input: String): Pair<Command, Param?>? { return when { input.startsWith("blocka://cmd/") || input.startsWith("http://cmd.blocka.net/")-> { input.replace("blocka://cmd/", "") .replace("http://cmd.blocka.net/", "") .trimEnd('/') .split("/") .let { try { Command.valueOf(it[0].toUpperCase()) to it.getOrNull(1) } catch (ex: Exception) { null } } } // Legacy commands to be removed in the future input.startsWith("blocka://log") -> Command.LOG to null input.startsWith("blocka://acc") -> Command.ACC to ACC_MANAGE else -> null } } private fun ensureParam(param: Param?): Param { return param ?: throw BlokadaException("Required param not provided") } } class CommandService : IntentService("cmd") { override fun onHandleIntent(intent: Intent?) { intent?.let { val ctx = ContextService.requireContext() val notification = NotificationService val n = ExecutingCommandNotification() startForeground(n.id, notification.build(n)) ctx.startActivity(Intent(ACTION_VIEW, it.data).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK }) } } } fun getIntentForCommand(command: Command, param: Param? = null): Intent { val ctx = ContextService.requireContext() return Intent(ctx, CommandService::class.java).apply { if (param == null) { data = Uri.parse("blocka://cmd/${command.name}") } else { data = Uri.parse("blocka://cmd/${command.name}/$param") } } } fun getIntentForCommand(cmd: String): Intent { val ctx = ContextService.requireContext() return Intent(ctx, CommandService::class.java).apply { data = Uri.parse("blocka://cmd/$cmd") } } fun executeCommand(cmd: Command, param: Param? = null) { val ctx = ContextService.requireContext() val intent = getIntentForCommand(cmd, param) ctx.startForegroundService(intent) }
mpl-2.0
6233f58177d74dfa547b9c38340c481a
32.502703
96
0.580604
4.628081
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/coroutines/multiModule/inlineFunctionWithOptionalParam.kt
2
711
// MODULE: lib // FILE: lib.kt inline fun foo(x: String = "OK"): String { return x + x } // MODULE: main(lib, support) // FILE: main.kt // WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* var result = "" fun builder(c: suspend () -> Unit) { c.startCoroutine(object : Continuation<Unit> { override val context = EmptyCoroutineContext override fun resume(value: Unit) { } override fun resumeWithException(exception: Throwable) { } }) } fun box(): String { builder { result = foo() } if (result != "OKOK") return "fail: $result" return "OK" }
apache-2.0
e49e7383da0680767d5945619cbdf4ef
20.545455
64
0.624473
3.781915
false
false
false
false
smmribeiro/intellij-community
platform/markdown-utils/test/com/intellij/markdown/utils/MarkdownToHtmlConverterTest.kt
9
3120
// 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.markdown.utils import com.intellij.markdown.utils.lang.HtmlSyntaxHighlighter import com.intellij.openapi.util.text.HtmlChunk import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.flavours.gfm.GFMFlavourDescriptor import org.intellij.markdown.html.GeneratingProvider import org.intellij.markdown.parser.LinkMap import org.junit.Test import java.net.URI import kotlin.test.assertEquals class MarkdownToHtmlConverterTest { private val emptyFlavourDescriptor = object : GFMFlavourDescriptor() { override fun createHtmlGeneratingProviders(linkMap: LinkMap, baseURI: URI?): Map<IElementType, GeneratingProvider> { val providers = super.createHtmlGeneratingProviders(linkMap, baseURI).toMutableMap() providers[MarkdownElementTypes.CODE_FENCE] = CodeFenceSyntaxHighlighterGeneratingProvider( object : HtmlSyntaxHighlighter { override fun color(language: String?, rawContent: String): HtmlChunk { return if (language == "empty") HtmlChunk.text(rawContent) else HtmlChunk.text(SYNTAX_HIGHLIGHTER_RESULT).wrapWith("pre") } } ) return providers } } private val converter = MarkdownToHtmlConverter(emptyFlavourDescriptor) @Test fun `java syntax highlighter call check`() { val markdownText = """ ```java public class A { public static void main(String[] args) { System.out.println("Hello, world!"); } } """.trimIndent() // language=HTML val htmlText = """ <body> <code class="language-java"> <pre>${SYNTAX_HIGHLIGHTER_RESULT}</pre> </code> </body> """.trimIndent() markdownText shouldBe htmlText } @Test fun `kotlin syntax highlighter call check`() { val markdownText = """ ```kotlin class A { companion object { @JvmStatic fun main(args: Array<String>) { println("Multi to multi suggestion") } } } """.trimIndent() // language=HTML val htmlText = """ <body> <code class="language-kotlin"> <pre>${SYNTAX_HIGHLIGHTER_RESULT}</pre> </code> </body> """.trimIndent() markdownText shouldBe htmlText } @Test fun `syntax highlighter call check without language`() { val markdownText = """ ```empty class A """.trimIndent() // language=HTML val htmlText = """ <body> <code class="language-empty"> class A </code> </body> """.trimIndent() markdownText shouldBe htmlText } private infix fun String.shouldBe(htmlText: String) { assertEquals( htmlText.lines().joinToString("") { it.trim() }, converter.convertMarkdownToHtml(this) ) } private companion object { private const val SYNTAX_HIGHLIGHTER_RESULT = "Empty line" } }
apache-2.0
1d7f307c29e8e8dd2173b839d3ad616e
26.377193
120
0.64391
4.581498
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/conventionNameCalls/ReplaceGetOrSetInspection.kt
2
5697
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.conventionNameCalls import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.inspections.AbstractApplicabilityBasedInspection import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.intentions.calleeName import org.jetbrains.kotlin.idea.intentions.isReceiverExpressionWithValue import org.jetbrains.kotlin.idea.intentions.toResolvedCall import org.jetbrains.kotlin.idea.util.calleeTextRangeInThis import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getChildOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.util.isValidOperator class ReplaceGetOrSetInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>( KtDotQualifiedExpression::class.java ) { private fun FunctionDescriptor.isExplicitOperator(): Boolean { return if (overriddenDescriptors.isEmpty()) containingDeclaration !is JavaClassDescriptor && isOperator else overriddenDescriptors.any { it.isExplicitOperator() } } private val operatorNames = setOf(OperatorNameConventions.GET, OperatorNameConventions.SET) override fun isApplicable(element: KtDotQualifiedExpression): Boolean { val callExpression = element.callExpression ?: return false val calleeName = (callExpression.calleeExpression as? KtSimpleNameExpression)?.getReferencedNameAsName() if (calleeName !in operatorNames) return false if (callExpression.typeArgumentList != null) return false val arguments = callExpression.valueArguments if (arguments.isEmpty()) return false if (arguments.any { it.isNamed() || it.isSpread }) return false val bindingContext = callExpression.analyze(BodyResolveMode.PARTIAL_WITH_CFA) val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return false if (!resolvedCall.isReallySuccess()) return false val target = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return false if (!target.isValidOperator() || target.name !in operatorNames) return false if (!element.isReceiverExpressionWithValue()) return false return target.name != OperatorNameConventions.SET || !element.isUsedAsExpression(bindingContext) } override fun inspectionText(element: KtDotQualifiedExpression) = KotlinBundle.message("should.be.replaced.with.indexing") override fun inspectionHighlightType(element: KtDotQualifiedExpression): ProblemHighlightType = if ((element.toResolvedCall(BodyResolveMode.PARTIAL)?.resultingDescriptor as? FunctionDescriptor)?.isExplicitOperator() == true) { ProblemHighlightType.GENERIC_ERROR_OR_WARNING } else { ProblemHighlightType.INFORMATION } override val defaultFixText: String get() = KotlinBundle.message("replace.get.or.set.call.with.indexing.operator") override fun fixText(element: KtDotQualifiedExpression): String { val callExpression = element.callExpression ?: return defaultFixText val resolvedCall = callExpression.resolveToCall() ?: return defaultFixText return KotlinBundle.message("replace.0.call.with.indexing.operator", resolvedCall.resultingDescriptor.name.asString()) } override fun inspectionHighlightRangeInElement(element: KtDotQualifiedExpression) = element.calleeTextRangeInThis() override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) { val allArguments = element.callExpression?.valueArguments ?: return assert(allArguments.isNotEmpty()) val isSet = element.calleeName == OperatorNameConventions.SET.identifier val newExpression = KtPsiFactory(element).buildExpression { appendExpression(element.receiverExpression) appendFixedText("[") val arguments = if (isSet) allArguments.dropLast(1) else allArguments appendExpressions(arguments.map { it.getArgumentExpression() }) appendFixedText("]") if (isSet) { appendFixedText("=") appendExpression(allArguments.last().getArgumentExpression()) } } val newElement = element.replace(newExpression) if (editor != null) { moveCaret(editor, isSet, newElement) } } private fun moveCaret(editor: Editor, isSet: Boolean, newElement: PsiElement) { val arrayAccessExpression = if (isSet) { newElement.getChildOfType() } else { newElement as? KtArrayAccessExpression } ?: return arrayAccessExpression.leftBracket?.startOffset?.let { editor.caretModel.moveToOffset(it) } } }
apache-2.0
589adef516d3ad9fbe2dbb2119844307
46.87395
158
0.754432
5.547225
false
false
false
false
smmribeiro/intellij-community
plugins/toml/core/src/main/kotlin/org/toml/lang/psi/TomlPsiFactory.kt
2
3060
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.toml.lang.psi import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileFactory import com.intellij.psi.PsiParserFacade import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.LocalTimeCounter class TomlPsiFactory(private val project: Project, private val markGenerated: Boolean = true) { private fun createFile(text: CharSequence): TomlFile = PsiFileFactory.getInstance(project) .createFileFromText( "DUMMY.toml", TomlFileType, text, /*modificationStamp =*/ LocalTimeCounter.currentTime(), // default value /*eventSystemEnabled =*/ false, // default value /*markAsCopy =*/ markGenerated // `true` by default ) as TomlFile private inline fun <reified T : TomlElement> createFromText(code: String): T? = createFile(code).descendantOfTypeStrict() // Copied from org.rust.lang.core.psi.ext as it's not available here private inline fun <reified T : PsiElement> PsiElement.descendantOfTypeStrict(): T? = PsiTreeUtil.findChildOfType(this, T::class.java, /* strict */ true) fun createNewline(): PsiElement = createWhitespace("\n") fun createWhitespace(ws: String): PsiElement = PsiParserFacade.SERVICE.getInstance(project).createWhiteSpaceFromText(ws) fun createLiteral(value: String): TomlLiteral = // If you're creating a string value, like `serde = "1.0.90"` make sure that the `value` parameter actually // contains the quote in the beginning and the end. E.g.: `createValue("\"1.0.90\"")` createFromText("dummy = $value") ?: error("Failed to create TomlLiteral") fun createKeySegment(key: String): TomlKeySegment = createFromText("$key = \"dummy\"") ?: error("Failed to create TomlKeySegment") fun createKey(key: String): TomlKey = createFromText("$key = \"dummy\"") ?: error("Failed to create TomlKey") fun createKeyValue(text: String): TomlKeyValue = // Make sure that `text` includes the equals sign in the middle like so: "serde = \"1.0.90\"" createFromText(text) ?: error("Failed to create TomlKeyValue") fun createKeyValue(key: String, value: String): TomlKeyValue = createFromText("$key = $value") ?: error("Failed to create TomlKeyValue") fun createTable(name: String): TomlTable = createFromText("[$name]") ?: error("Failed to create TomlTableHeader") fun createTableHeader(name: String): TomlTableHeader = createFromText("[$name]") ?: error("Failed to create TomlTableHeader") fun createArray(contents: String): TomlArray = createFromText("dummy = [$contents]") ?: error("Failed to create TomlArray") fun createInlineTable(contents: String): TomlInlineTable = createFromText("dummy = {$contents}") ?: error("Failed to create TomlInlineTable") }
apache-2.0
6cb7fb77cf2450fd4a33b8a410822442
43.347826
115
0.680719
4.519941
false
false
false
false
vanniktech/lint-rules
lint-rules-rxjava2-lint/src/main/java/com/vanniktech/lintrules/rxjava2/RxJava2DefaultSchedulerDetector.kt
1
2525
@file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final. package com.vanniktech.lintrules.rxjava2 import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope.JAVA_FILE import com.android.tools.lint.detector.api.Severity.WARNING import com.intellij.codeInsight.AnnotationUtil import com.intellij.psi.PsiMethod import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UMethod import org.jetbrains.uast.tryResolve import org.jetbrains.uast.visitor.AbstractUastVisitor import java.util.EnumSet val ISSUE_DEFAULT_SCHEDULER = Issue.create( "RxJava2DefaultScheduler", "Pass a scheduler instead of relying on the default Scheduler.", "Calling this method will rely on a default scheduler. This is not necessary the best default. Being explicit and taking the overload for passing one is preferred.", CORRECTNESS, PRIORITY, WARNING, Implementation(RxJava2DefaultSchedulerDetector::class.java, EnumSet.of(JAVA_FILE)), ) class RxJava2DefaultSchedulerDetector : Detector(), Detector.UastScanner { override fun getApplicableUastTypes() = listOf(UMethod::class.java) override fun createUastHandler(context: JavaContext) = RxJava2DefaultSchedulerHandler(context) class RxJava2DefaultSchedulerHandler(private val context: JavaContext) : UElementHandler() { override fun visitMethod(node: UMethod) { node.accept(RxJava2DefaultSchedulerVisitor(context)) } } class RxJava2DefaultSchedulerVisitor(private val context: JavaContext) : AbstractUastVisitor() { override fun visitCallExpression(node: UCallExpression): Boolean { val identifier = node.methodIdentifier identifier?.uastParent?.let { val method = it.tryResolve() as? PsiMethod val annotation = AnnotationUtil.findAnnotation(method, "io.reactivex.annotations.SchedulerSupport") if (annotation != null) { val value = AnnotationUtil.getStringAttributeValue(annotation, null) if (!("none" == value || "custom" == value)) { context.report(ISSUE_DEFAULT_SCHEDULER, context.getNameLocation(node), "${identifier.name}() is using its default scheduler") } } } return false } } }
apache-2.0
0ffd4139bc065362511edee613d0a112
41.083333
167
0.769109
4.453263
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/gui/canvas/layout/LayoutThree.kt
1
5701
package com.cout970.modeler.gui.canvas.layout import com.cout970.glutilities.event.EventKeyUpdate import com.cout970.modeler.core.config.Config import com.cout970.modeler.gui.Gui import com.cout970.modeler.gui.canvas.CanvasContainer import com.cout970.modeler.util.next import org.joml.Vector2f /** * Created by cout970 on 2017/06/09. */ class LayoutThree(override val container: CanvasContainer) : ICanvasLayout { var horizontalSplitter = 0.5f var verticalSplitter = 0.5f var mode: Mode = Mode.LEFT override fun updateCanvas() { when (mode) { Mode.LEFT -> { container.canvas[0].apply { size = Vector2f(container.panel.size.x * horizontalSplitter, container.panel.size.y) position = Vector2f() } container.canvas[1].apply { size = Vector2f(container.panel.size.x * (1 - horizontalSplitter), container.panel.size.y * verticalSplitter) position = Vector2f(container.panel.size.x * horizontalSplitter, 0f) } container.canvas[2].apply { size = Vector2f(container.panel.size.x * (1 - horizontalSplitter), container.panel.size.y * (1 - verticalSplitter)) position = Vector2f(container.panel.size.x * horizontalSplitter, container.panel.size.y * verticalSplitter) } } Mode.RIGHT -> { container.canvas[0].apply { size = Vector2f(container.panel.size.x * horizontalSplitter, container.panel.size.y) position = Vector2f(container.panel.size.x * (1 - horizontalSplitter), 0f) } container.canvas[1].apply { size = Vector2f(container.panel.size.x * (1 - horizontalSplitter), container.panel.size.y * verticalSplitter) position = Vector2f() } container.canvas[2].apply { size = Vector2f(container.panel.size.x * (1 - horizontalSplitter), container.panel.size.y * (1 - verticalSplitter)) position = Vector2f(0f, container.panel.size.y * verticalSplitter) } } Mode.TOP -> { container.canvas[0].apply { size = Vector2f(container.panel.size.x, container.panel.size.y * verticalSplitter) position = Vector2f() } container.canvas[1].apply { size = Vector2f(container.panel.size.x * horizontalSplitter, container.panel.size.y * (1 - verticalSplitter)) position = Vector2f(0f, container.panel.size.y * verticalSplitter) } container.canvas[2].apply { size = Vector2f(container.panel.size.x * (1 - horizontalSplitter), container.panel.size.y * (1 - verticalSplitter)) position = Vector2f(container.panel.size.x * horizontalSplitter, container.panel.size.y * verticalSplitter) } } Mode.BOTTOM -> { container.canvas[0].apply { size = Vector2f(container.panel.size.x, container.panel.size.y * verticalSplitter) position = Vector2f(0f, container.panel.size.y * (1 - verticalSplitter)) } container.canvas[1].apply { size = Vector2f(container.panel.size.x * horizontalSplitter, container.panel.size.y * (1 - verticalSplitter)) position = Vector2f() } container.canvas[2].apply { size = Vector2f(container.panel.size.x * (1 - horizontalSplitter), container.panel.size.y * (1 - verticalSplitter)) position = Vector2f(container.panel.size.x * horizontalSplitter, 0f) } } } } override fun onEvent(gui: Gui, e: EventKeyUpdate): Boolean { Config.keyBindings.apply { when { layoutChangeMode.check(e) -> runAction("layout.change.mode") moveLayoutSplitterLeft.check(e) -> runAction("move.splitter.left") moveLayoutSplitterRight.check(e) -> runAction("move.splitter.right") moveLayoutSplitterUp.check(e) -> runAction("move.splitter.up") moveLayoutSplitterDown.check(e) -> runAction("move.splitter.down") newCanvas.check(e) -> runAction("canvas.new") deleteCanvas.check(e) -> runAction("canvas.delete") else -> return false } } gui.root.reRender() return true } override fun runAction(action: String) { when (action) { "layout.change.mode" -> mode = mode.next() "move.splitter.left" -> horizontalSplitter -= 1f / 32f "move.splitter.right" -> horizontalSplitter += 1f / 32f "move.splitter.up" -> verticalSplitter -= 1f / 32f "move.splitter.down" -> verticalSplitter += 1f / 32f "canvas.new" -> { container.newCanvas() container.selectLayout() } "canvas.delete" -> { container.removeCanvas(container.canvas.lastIndex) container.selectLayout() } } } enum class Mode { LEFT, RIGHT, TOP, BOTTOM } }
gpl-3.0
57506dce6950b1fd4381db5b8cbc1612
43.546875
104
0.536923
4.467868
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ScopeFunctionConversionInspection.kt
1
17469
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.SmartPsiElementPointer import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.refactoring.getThisLabelName import org.jetbrains.kotlin.idea.refactoring.rename.KotlinVariableInplaceRenameHandler import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.getReceiverTargetDescriptor import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getOrCreateParameterList import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingContext.FUNCTION import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.resolve.scopes.utils.collectDescriptorsFiltered import org.jetbrains.kotlin.resolve.scopes.utils.findVariable import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection private val counterpartNames = mapOf( "apply" to "also", "run" to "let", "also" to "apply", "let" to "run" ) class ScopeFunctionConversionInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return callExpressionVisitor { expression -> val counterpartName = getCounterpart(expression) if (counterpartName != null) { holder.registerProblem( expression.calleeExpression!!, KotlinBundle.message("call.is.replaceable.with.another.scope.function"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, if (counterpartName == "also" || counterpartName == "let") ConvertScopeFunctionToParameter(counterpartName) else ConvertScopeFunctionToReceiver(counterpartName) ) } } } } private fun getCounterpart(expression: KtCallExpression): String? { val callee = expression.calleeExpression as? KtNameReferenceExpression ?: return null val calleeName = callee.getReferencedName() val counterpartName = counterpartNames[calleeName] val lambdaExpression = expression.lambdaArguments.singleOrNull()?.getLambdaExpression() if (counterpartName != null && lambdaExpression != null) { if (lambdaExpression.valueParameters.isNotEmpty()) { return null } val bindingContext = callee.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val resolvedCall = callee.getResolvedCall(bindingContext) ?: return null val descriptor = resolvedCall.resultingDescriptor if (descriptor.dispatchReceiverParameter == null && descriptor.extensionReceiverParameter == null) return null if (descriptor.fqNameSafe.asString() == "kotlin.$calleeName" && nameResolvesToStdlib(expression, bindingContext, counterpartName)) { return counterpartName } } return null } private fun nameResolvesToStdlib(expression: KtCallExpression, bindingContext: BindingContext, name: String): Boolean { val scope = expression.getResolutionScope(bindingContext) ?: return true val descriptors = scope.collectDescriptorsFiltered(nameFilter = { it.asString() == name }) return descriptors.isNotEmpty() && descriptors.all { it.fqNameSafe.asString() == "kotlin.$name" } } class Replacement<T : PsiElement> private constructor( private val elementPointer: SmartPsiElementPointer<T>, private val replacementFactory: KtPsiFactory.(T) -> PsiElement ) { companion object { fun <T : PsiElement> create(element: T, replacementFactory: KtPsiFactory.(T) -> PsiElement): Replacement<T> { return Replacement(element.createSmartPointer(), replacementFactory) } } fun apply(factory: KtPsiFactory) { elementPointer.element?.let { it.replace(factory.replacementFactory(it)) } } val endOffset get() = elementPointer.element!!.endOffset } class ReplacementCollection(private val project: Project) { private val replacements = mutableListOf<Replacement<out PsiElement>>() var createParameter: KtPsiFactory.() -> PsiElement? = { null } var elementToRename: PsiElement? = null fun <T : PsiElement> add(element: T, replacementFactory: KtPsiFactory.(T) -> PsiElement) { replacements.add(Replacement.create(element, replacementFactory)) } fun apply() { val factory = KtPsiFactory(project) elementToRename = factory.createParameter() // Calls need to be processed in outside-in order replacements.sortBy { it.endOffset } for (replacement in replacements) { replacement.apply(factory) } } fun isNotEmpty() = replacements.isNotEmpty() } abstract class ConvertScopeFunctionFix(private val counterpartName: String) : LocalQuickFix { override fun getFamilyName() = KotlinBundle.message("convert.scope.function.fix.family.name", counterpartName) override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) { val callee = problemDescriptor.psiElement as KtNameReferenceExpression val callExpression = callee.parent as? KtCallExpression ?: return val bindingContext = callExpression.analyze() val lambda = callExpression.lambdaArguments.firstOrNull() ?: return val functionLiteral = lambda.getLambdaExpression()?.functionLiteral ?: return val lambdaDescriptor = bindingContext[FUNCTION, functionLiteral] ?: return functionLiteral.valueParameterList?.delete() functionLiteral.arrow?.delete() val replacements = ReplacementCollection(project) analyzeLambda(bindingContext, lambda, lambdaDescriptor, replacements) callee.replace(KtPsiFactory(project).createExpression(counterpartName) as KtNameReferenceExpression) replacements.apply() postprocessLambda(lambda) if (replacements.isNotEmpty() && replacements.elementToRename != null && !isUnitTestMode()) { replacements.elementToRename!!.startInPlaceRename() } } protected abstract fun postprocessLambda(lambda: KtLambdaArgument) protected abstract fun analyzeLambda( bindingContext: BindingContext, lambda: KtLambdaArgument, lambdaDescriptor: SimpleFunctionDescriptor, replacements: ReplacementCollection ) } class ConvertScopeFunctionToParameter(counterpartName: String) : ConvertScopeFunctionFix(counterpartName) { override fun analyzeLambda( bindingContext: BindingContext, lambda: KtLambdaArgument, lambdaDescriptor: SimpleFunctionDescriptor, replacements: ReplacementCollection ) { val project = lambda.project val factory = KtPsiFactory(project) val functionLiteral = lambda.getLambdaExpression()?.functionLiteral val lambdaExtensionReceiver = lambdaDescriptor.extensionReceiverParameter val lambdaDispatchReceiver = lambdaDescriptor.dispatchReceiverParameter var parameterName = "it" val scopes = mutableSetOf<LexicalScope>() if (functionLiteral != null && needUniqueNameForParameter(lambda, scopes)) { val parameterType = lambdaExtensionReceiver?.type ?: lambdaDispatchReceiver?.type parameterName = findUniqueParameterName(parameterType, scopes) replacements.createParameter = { val lambdaParameterList = functionLiteral.getOrCreateParameterList() val parameterToAdd = createLambdaParameterList(parameterName).parameters.first() lambdaParameterList.addParameterBefore(parameterToAdd, lambdaParameterList.parameters.firstOrNull()) } } lambda.accept(object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { super.visitSimpleNameExpression(expression) if (expression is KtOperationReferenceExpression) return val resolvedCall = expression.getResolvedCall(bindingContext) ?: return val dispatchReceiverTarget = resolvedCall.dispatchReceiver?.getReceiverTargetDescriptor(bindingContext) val extensionReceiverTarget = resolvedCall.extensionReceiver?.getReceiverTargetDescriptor(bindingContext) if (dispatchReceiverTarget == lambdaDescriptor || extensionReceiverTarget == lambdaDescriptor) { val parent = expression.parent if (parent is KtCallExpression && expression == parent.calleeExpression) { if ((parent.parent as? KtQualifiedExpression)?.receiverExpression !is KtThisExpression) { replacements.add(parent) { element -> factory.createExpressionByPattern("$0.$1", parameterName, element) } } } else if (parent is KtQualifiedExpression && parent.receiverExpression is KtThisExpression) { // do nothing } else { val referencedName = expression.getReferencedName() replacements.add(expression) { createExpression("$parameterName.$referencedName") } } } } override fun visitThisExpression(expression: KtThisExpression) { val resolvedCall = expression.getResolvedCall(bindingContext) ?: return if (resolvedCall.resultingDescriptor == lambdaDispatchReceiver || resolvedCall.resultingDescriptor == lambdaExtensionReceiver ) { replacements.add(expression) { createExpression(parameterName) } } } }) } override fun postprocessLambda(lambda: KtLambdaArgument) { val filter = { element: PsiElement -> if (element is KtThisExpression && element.getLabelName() != null) ShortenReferences.FilterResult.PROCESS else ShortenReferences.FilterResult.GO_INSIDE } ShortenReferences{ ShortenReferences.Options(removeThisLabels = true) }.process(lambda, filter) } private fun needUniqueNameForParameter( lambdaArgument: KtLambdaArgument, scopes: MutableSet<LexicalScope> ): Boolean { val resolutionScope = lambdaArgument.getResolutionScope() scopes.add(resolutionScope) var needUniqueName = false if (resolutionScope.findVariable(Name.identifier("it"), NoLookupLocation.FROM_IDE) != null) { needUniqueName = true // Don't return here - we still need to gather the list of nested scopes } lambdaArgument.accept(object : KtTreeVisitorVoid() { override fun visitDeclaration(dcl: KtDeclaration) { super.visitDeclaration(dcl) checkNeedUniqueName(dcl) } override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) { super.visitLambdaExpression(lambdaExpression) lambdaExpression.bodyExpression?.statements?.firstOrNull()?.let { checkNeedUniqueName(it) } } private fun checkNeedUniqueName(dcl: KtElement) { val nestedResolutionScope = dcl.getResolutionScope() scopes.add(nestedResolutionScope) if (nestedResolutionScope.findVariable(Name.identifier("it"), NoLookupLocation.FROM_IDE) != null) { needUniqueName = true } } }) return needUniqueName } private fun findUniqueParameterName( parameterType: KotlinType?, resolutionScopes: Collection<LexicalScope> ): String { fun isNameUnique(parameterName: String): Boolean { return resolutionScopes.none { it.findVariable(Name.identifier(parameterName), NoLookupLocation.FROM_IDE) != null } } return if (parameterType != null) Fe10KotlinNameSuggester.suggestNamesByType(parameterType, ::isNameUnique).first() else { Fe10KotlinNameSuggester.suggestNameByName("p", ::isNameUnique) } } } class ConvertScopeFunctionToReceiver(counterpartName: String) : ConvertScopeFunctionFix(counterpartName) { override fun analyzeLambda( bindingContext: BindingContext, lambda: KtLambdaArgument, lambdaDescriptor: SimpleFunctionDescriptor, replacements: ReplacementCollection ) { lambda.accept(object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { super.visitSimpleNameExpression(expression) if (expression.getReferencedName() == "it") { val result = expression.resolveMainReferenceToDescriptors().singleOrNull() if (result is ValueParameterDescriptor && result.containingDeclaration == lambdaDescriptor) { replacements.add(expression) { createThisExpression() } } } else { val resolvedCall = expression.getResolvedCall(bindingContext) ?: return val dispatchReceiver = resolvedCall.dispatchReceiver if (dispatchReceiver is ImplicitReceiver) { val parent = expression.parent val thisLabelName = dispatchReceiver.declarationDescriptor.getThisLabelName() if (parent is KtCallExpression && expression == parent.calleeExpression) { replacements.add(parent) { element -> createExpressionByPattern("this@$0.$1", thisLabelName, element) } } else { val referencedName = expression.getReferencedName() replacements.add(expression) { createExpression("this@$thisLabelName.$referencedName") } } } } } override fun visitThisExpression(expression: KtThisExpression) { val resolvedCall = expression.getResolvedCall(bindingContext) ?: return val qualifierName = resolvedCall.resultingDescriptor.containingDeclaration.name replacements.add(expression) { createThisExpression(qualifierName.asString()) } } }) } override fun postprocessLambda(lambda: KtLambdaArgument) { val filter = { element: PsiElement -> if (element is KtThisExpression && element.getLabelName() != null) ShortenReferences.FilterResult.PROCESS else if (element is KtQualifiedExpression && element.receiverExpression is KtThisExpression) ShortenReferences.FilterResult.PROCESS else ShortenReferences.FilterResult.GO_INSIDE } ShortenReferences { ShortenReferences.Options(removeThis = true, removeThisLabels = true) }.process(lambda, filter) } } private fun PsiElement.startInPlaceRename() { val project = project val document = containingFile.viewProvider.document ?: return val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return if (editor.document == document) { PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) editor.caretModel.moveToOffset(startOffset) KotlinVariableInplaceRenameHandler().doRename(this, editor, null) } }
apache-2.0
269fd45f14a7dca9a8f73bfc272aed24
46.341463
158
0.683611
6.076174
false
false
false
false
anthonycr/Lightning-Browser
app/src/main/java/acr/browser/lightning/browser/tab/DrawerTabRecyclerViewAdapter.kt
1
3202
package acr.browser.lightning.browser.tab import acr.browser.lightning.R import acr.browser.lightning.browser.tab.view.BackgroundDrawable import acr.browser.lightning.extensions.desaturate import acr.browser.lightning.extensions.inflater import android.graphics.Bitmap import android.view.ViewGroup import androidx.core.widget.TextViewCompat import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter /** * The adapter that renders tabs in the drawer list form. * * @param onClick Invoked when the tab is clicked. * @param onLongClick Invoked when the tab is long pressed. * @param onCloseClick Invoked when the tab's close button is clicked. */ class DrawerTabRecyclerViewAdapter( private val onClick: (Int) -> Unit, private val onLongClick: (Int) -> Unit, private val onCloseClick: (Int) -> Unit, ) : ListAdapter<TabViewState, TabViewHolder>( object : DiffUtil.ItemCallback<TabViewState>() { override fun areItemsTheSame(oldItem: TabViewState, newItem: TabViewState): Boolean = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: TabViewState, newItem: TabViewState): Boolean = oldItem == newItem } ) { override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): TabViewHolder { val view = viewGroup.context.inflater.inflate(R.layout.tab_list_item, viewGroup, false) view.background = BackgroundDrawable(view.context) return TabViewHolder( view, onClick = onClick, onLongClick = onLongClick, onCloseClick = onCloseClick ) } override fun onBindViewHolder(holder: TabViewHolder, position: Int) { holder.exitButton.tag = position val tab = getItem(position) holder.txtTitle.text = tab.title updateViewHolderAppearance(holder, tab.isSelected) updateViewHolderFavicon(holder, tab.icon, tab.isSelected) updateViewHolderBackground(holder, tab.isSelected) } private fun updateViewHolderFavicon( viewHolder: TabViewHolder, favicon: Bitmap?, isForeground: Boolean ) { favicon?.let { if (isForeground) { viewHolder.favicon.setImageBitmap(it) } else { viewHolder.favicon.setImageBitmap(it.desaturate()) } } ?: viewHolder.favicon.setImageResource(R.drawable.ic_webpage) } private fun updateViewHolderBackground(viewHolder: TabViewHolder, isForeground: Boolean) { val verticalBackground = viewHolder.layout.background as BackgroundDrawable verticalBackground.isCrossFadeEnabled = false if (isForeground) { verticalBackground.startTransition(200) } else { verticalBackground.reverseTransition(200) } } private fun updateViewHolderAppearance( viewHolder: TabViewHolder, isForeground: Boolean ) { if (isForeground) { TextViewCompat.setTextAppearance(viewHolder.txtTitle, R.style.boldText) } else { TextViewCompat.setTextAppearance(viewHolder.txtTitle, R.style.normalText) } } }
mpl-2.0
cd580186ab3eee4a0c1867a2caae9e30
34.577778
96
0.68832
4.873668
false
false
false
false
Zhouzhouzhou/AndroidDemo
app/src/main/java/com/zhou/android/kotlin/album/AlbumScrollListener.kt
1
1487
package com.zhou.android.kotlin.album import android.support.v7.widget.RecyclerView import android.support.v7.widget.SnapHelper open class AlbumScrollListener : RecyclerView.OnScrollListener { private var helper: SnapHelper private var currentPosition = RecyclerView.NO_POSITION constructor(helper: SnapHelper) { [email protected] = helper } override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val layoutManager = recyclerView?.layoutManager var position = 0 layoutManager?.also { val view = helper.findSnapView(it) view?.apply { position = it.getPosition(this) } } if (position == RecyclerView.NO_POSITION) { return } if (position != currentPosition) { currentPosition = position onPageSelected(position) } } override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (currentPosition == RecyclerView.NO_POSITION) return if (newState == RecyclerView.SCROLL_STATE_IDLE) { onPageScrolled(currentPosition, 0f, 0) } } public fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } open fun onPageSelected(position: Int) { } }
mit
d20777c9b473ebcb2855f197a91d8828
27.615385
96
0.644923
5.040678
false
false
false
false
feelfreelinux/WykopMobilny
app/src/test/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/mikroblog/entry/EntryDetailPresenterTest.kt
1
1818
package io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.entry import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import io.github.feelfreelinux.wykopmobilny.TestSchedulers import io.github.feelfreelinux.wykopmobilny.api.entries.EntriesApi import io.github.feelfreelinux.wykopmobilny.models.dataclass.Entry import io.github.feelfreelinux.wykopmobilny.ui.fragments.entries.EntriesInteractor import io.github.feelfreelinux.wykopmobilny.ui.fragments.entrycomments.EntryCommentInteractor import io.reactivex.Single import org.junit.Before import org.junit.Test import java.io.IOException class EntryDetailPresenterTest { lateinit var systemUnderTest: EntryDetailPresenter val mockOfView = mock<EntryDetailView>() val mockOfEntriesApi = mock<EntriesApi>() val entriesInteractor = EntriesInteractor(mockOfEntriesApi) val commentsInteractor = EntryCommentInteractor(mockOfEntriesApi) val schedulers = TestSchedulers() @Before fun setup() { systemUnderTest = EntryDetailPresenter(schedulers, mockOfEntriesApi, entriesInteractor, commentsInteractor) systemUnderTest.subscribe(mockOfView) } @Test fun testSuccess() { val testEntry = mock<Entry>() systemUnderTest.entryId = 12 whenever(mockOfEntriesApi.getEntry(any())).thenReturn(Single.just(testEntry)) systemUnderTest.loadData() verify(mockOfView).showEntry(any()) } @Test fun testFailure() { systemUnderTest.entryId = 12 whenever(mockOfEntriesApi.getEntry(any())).thenReturn(Single.error(IOException())) systemUnderTest.loadData() verify(mockOfView).showErrorDialog(any()) } }
mit
c3e0e6da1fa66ab426705ea4ef389d31
32.072727
115
0.761826
4.848
false
true
false
false
jwren/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/TaskResult.kt
3
4572
// 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.tools.projectWizard.core sealed class TaskResult<out T : Any> data class Success<T : Any>(val value: T) : TaskResult<T>() data class Failure(val errors: List<Error>) : TaskResult<Nothing>() { constructor(vararg errors: Error) : this(errors.toList()) } val TaskResult<Any>.isSuccess get() = this is Success<*> fun <T : Any> success(value: T): TaskResult<T> = Success(value) fun <T : Any> failure(vararg errors: Error): TaskResult<T> = Failure(*errors) val <T : Any> TaskResult<T>.asNullable: T? get() = safeAs<Success<T>>()?.value inline fun <T : Any> TaskResult<T>.onSuccess(action: (T) -> Unit) = also { if (this is Success<T>) { action(value) } } inline fun <T : Any> TaskResult<T>.onFailure(handler: (List<Error>) -> Unit) = apply { if (this is Failure) { handler(errors) } } @Suppress("UNCHECKED_CAST") inline fun <A : Any, B : Any, R : Any> TaskResult<A>.mappend( other: TaskResult<B>, op: (A, B) -> R ): TaskResult<R> = mappendM(other) { a, b -> success(op(a, b)) } @Suppress("UNCHECKED_CAST") inline fun <A : Any, B : Any, R : Any> TaskResult<A>.mappendM( other: TaskResult<B>, op: (A, B) -> TaskResult<R> ): TaskResult<R> = when { this is Success<*> && other is Success<*> -> op(value as A, other.value as B) this is Success<*> && other is Failure -> other this is Failure && other is Success<*> -> this this is Failure && other is Failure -> Failure(errors + other.errors) else -> error("Can not happen") } infix fun <T : Any> TaskResult<*>.andThen(other: TaskResult<T>): TaskResult<T> = mappendM(other) { _, _ -> other } infix fun <T : Any> TaskResult<T>.andThenIgnoring(other: TaskResult<Unit>): TaskResult<T> = mappendM(other) { _, _ -> this } operator fun <T : Any> TaskResult<List<T>>.plus(other: TaskResult<List<T>>): TaskResult<Unit> = mappend(other) { _, _ -> Unit } fun <T : Any> T?.toResult(failure: () -> Error): TaskResult<T> = this?.let { Success(it) } ?: Failure( failure() ) fun <T : Any> T.asSuccess(): Success<T> = Success(this) inline fun <T : Any> TaskResult<T>.raise(returnExpression: (Failure) -> (Unit)): T = when (this) { is Failure -> { returnExpression(this) error("fail should return out of the function") } is Success -> value } fun <T : Any> Iterable<TaskResult<T>>.sequence(): TaskResult<List<T>> = fold(success(emptyList())) { acc, result -> acc.mappend(result) { a, r -> a + r } } fun <T : Any> Iterable<TaskResult<T>>.sequenceIgnore(): TaskResult<Unit> = fold<TaskResult<T>, TaskResult<Unit>>(UNIT_SUCCESS) { acc, result -> acc.mappend(result) { _, _ -> Unit } } fun <T : Any> Iterable<T>.mapSequenceIgnore(f: (T) -> TaskResult<*>): TaskResult<Unit> = fold<T, TaskResult<Unit>>(UNIT_SUCCESS) { acc, result -> acc.mappend(f(result)) { _, _ -> Unit } } fun <T : Any, R : Any> Iterable<T>.mapSequence(f: (T) -> TaskResult<R>): TaskResult<List<R>> = map(f).sequence() fun <T : Any> Sequence<TaskResult<T>>.sequenceFailFirst(): TaskResult<List<T>> = fold(success(emptyList())) { acc, result -> if (acc.isSuccess) acc.mappend(result) { a, r -> a + r } else acc } fun <T : Any, R : Any> TaskResult<T>.map(f: (T) -> R): TaskResult<R> = when (this) { is Failure -> this is Success<T> -> Success(f(value)) } fun <T : Any> TaskResult<T>.mapFailure(f: (List<Error>) -> Error): TaskResult<T> = when (this) { is Failure -> Failure(f(errors)) is Success<T> -> this } fun <T : Any> TaskResult<T>.recover(f: (Failure) -> TaskResult<T>): TaskResult<T> = when (this) { is Failure -> f(this) is Success<T> -> this } fun <T : Any, R : Any> TaskResult<T>.flatMap(f: (T) -> TaskResult<R>): TaskResult<R> = when (this) { is Failure -> this is Success<T> -> f(value) } fun <T : Any> TaskResult<T>.withAssert(assertion: (T) -> Error?): TaskResult<T> = when (this) { is Failure -> this is Success<T> -> assertion(value)?.let { Failure(it) } ?: this } fun <T : Any> TaskResult<T>.getOrElse(default: () -> T): T = when (this) { is Success<T> -> value is Failure -> default() } fun <T : Any> TaskResult<T>.ignore(): TaskResult<Unit> = when (this) { is Failure -> this is Success<T> -> UNIT_SUCCESS } val UNIT_SUCCESS = Success(Unit)
apache-2.0
947919fa7a7a79f2a5b22e2798dfc507
31.425532
158
0.608924
3.235669
false
false
false
false
jwren/intellij-community
java/java-features-trainer/src/com/intellij/java/ift/lesson/essential/JavaOnboardingTourLesson.kt
1
25732
// 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.java.ift.lesson.essential import com.intellij.codeInsight.daemon.impl.analysis.HighlightingFeature import com.intellij.execution.ExecutionBundle import com.intellij.execution.RunManager import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.actions.searcheverywhere.SearchEverywhereManagerImpl import com.intellij.ide.actions.searcheverywhere.SearchEverywhereUI import com.intellij.ide.ui.UISettings import com.intellij.ide.util.PropertiesComponent import com.intellij.ide.util.gotoByName.GotoActionModel import com.intellij.idea.ActionsBundle import com.intellij.java.ift.JavaLessonsBundle import com.intellij.java.ift.JavaProjectUtil import com.intellij.java.ift.lesson.run.highlightRunGutters import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.ActionMenuItem import com.intellij.openapi.application.invokeLater import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.actions.ToggleCaseAction import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.module.LanguageLevelUtil import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.SdkType import com.intellij.openapi.roots.ui.configuration.SdkDetector import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.ex.MultiLineLabel import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.WindowStateService import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.impl.FocusManagerImpl import com.intellij.toolWindow.StripeButton import com.intellij.ui.UIBundle import com.intellij.ui.components.fields.ExtendableTextField import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.tree.TreeVisitor import com.intellij.util.ui.UIUtil import com.intellij.util.ui.tree.TreeUtil import com.intellij.xdebugger.XDebuggerManager import com.siyeh.InspectionGadgetsBundle import com.siyeh.IntentionPowerPackBundle import kotlinx.serialization.json.JsonObjectBuilder import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.put import org.jetbrains.annotations.Nls import training.FeaturesTrainerIcons import training.dsl.* import training.dsl.LessonUtil.adjustSearchEverywherePosition import training.dsl.LessonUtil.checkEditorModification import training.dsl.LessonUtil.restoreIfModified import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.dsl.LessonUtil.restorePopupPosition import training.learn.LearnBundle import training.learn.LessonsBundle import training.learn.course.KLesson import training.learn.course.LessonProperties import training.learn.lesson.LessonManager import training.learn.lesson.general.run.clearBreakpoints import training.learn.lesson.general.run.toggleBreakpointTask import training.project.ProjectUtils import training.ui.LearningUiHighlightingManager import training.ui.LearningUiManager import training.util.* import java.awt.Point import java.awt.event.KeyEvent import java.util.concurrent.CompletableFuture import javax.swing.JTree import javax.swing.JWindow import javax.swing.tree.TreePath class JavaOnboardingTourLesson : KLesson("java.onboarding", JavaLessonsBundle.message("java.onboarding.lesson.name")) { private lateinit var openLearnTaskId: TaskContext.TaskId private var useDelay: Boolean = false private val demoConfigurationName: String = "Welcome" private val demoFileDirectory: String = "src" private val demoFileName: String = "$demoConfigurationName.java" private val uiSettings get() = UISettings.getInstance() override val properties = LessonProperties( canStartInDumbMode = true, openFileAtStart = false ) override val testScriptProperties = TaskTestContext.TestScriptProperties(skipTesting = true) private var backupPopupLocation: Point? = null private var hideToolStripesPreference = false private var showNavigationBarPreference = true val sample: LessonSample = parseLessonSample(""" import java.util.Arrays; import java.util.List; class Welcome { public static void main(String[] args) { int[] array = {5, 6, 7, 8}; System.out.println("AVERAGE of array " + Arrays.toString(array) + " is " + findAverage(array)); } private static double findAverage(int[] values) { double result = 0; <caret id=3/>for (int i = 0; i < values.length; i++) { result += values[i]; } <caret>return result<caret id=2/>; } } """.trimIndent()) override val lessonContent: LessonContext.() -> Unit = { prepareRuntimeTask { useDelay = true invokeActionForFocusContext(getActionById("Stop")) configurations().forEach { runManager().removeConfiguration(it) } val root = ProjectUtils.getCurrentLearningProjectRoot() val srcDir = root.findChild(demoFileDirectory) ?: error("'src' directory not found.") if (srcDir.findChild(demoFileName) == null) invokeLater { runWriteAction { srcDir.createChildData(this, demoFileName) // todo: This file shows with .java extension in the Project view and this extension disappears when user open it // (because we fill the file after the user open it) Fill the file immediately in this place? } } } clearBreakpoints() checkUiSettings() projectTasks() prepareSample(sample, checkSdkConfiguration = false) openLearnToolwindow() sdkConfigurationTasks() waitIndexingTasks() runTasks() debugTasks() completionSteps() waitBeforeContinue(500) contextActions() waitBeforeContinue(500) searchEverywhereTasks() task { text(JavaLessonsBundle.message("java.onboarding.epilog", getCallBackActionId("CloseProject"), LessonUtil.returnToWelcomeScreenRemark(), LearningUiManager.addCallback { LearningUiManager.resetModulesView() })) } } override fun onLessonEnd(project: Project, lessonEndInfo: LessonEndInfo) { prepareFeedbackData(project, lessonEndInfo) restorePopupPosition(project, SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY, backupPopupLocation) backupPopupLocation = null uiSettings.hideToolStripes = hideToolStripesPreference uiSettings.showNavigationBar = showNavigationBarPreference uiSettings.fireUISettingsChanged() if (!lessonEndInfo.lessonPassed) { LessonUtil.showFeedbackNotification(this, project) return } val dataContextPromise = DataManager.getInstance().dataContextFromFocusAsync invokeLater { val result = MessageDialogBuilder.yesNoCancel(JavaLessonsBundle.message("java.onboarding.finish.title"), JavaLessonsBundle.message("java.onboarding.finish.text", LessonUtil.returnToWelcomeScreenRemark())) .yesText(JavaLessonsBundle.message("java.onboarding.finish.exit")) .noText(JavaLessonsBundle.message("java.onboarding.finish.modules")) .icon(FeaturesTrainerIcons.Img.PluginIcon) .show(project) when (result) { Messages.YES -> invokeLater { LessonManager.instance.stopLesson() val closeAction = getActionById("CloseProject") dataContextPromise.onSuccess { context -> invokeLater { val event = AnActionEvent.createFromAnAction(closeAction, null, ActionPlaces.LEARN_TOOLWINDOW, context) ActionUtil.performActionDumbAwareWithCallbacks(closeAction, event) } } } Messages.NO -> invokeLater { LearningUiManager.resetModulesView() } } if (result != Messages.YES) { LessonUtil.showFeedbackNotification(this, project) } } } private fun prepareFeedbackData(project: Project, lessonEndInfo: LessonEndInfo) { val configPropertyName = "ift.idea.onboarding.feedback.proposed" if (PropertiesComponent.getInstance().getBoolean(configPropertyName, false)) { return } val primaryLanguage = module.primaryLanguage if (primaryLanguage == null) { thisLogger().error("Onboarding lesson has no language support for some magical reason") return } val jdkVersionsFuture = CompletableFuture<List<String>>() runBackgroundableTask(ProjectBundle.message("progress.title.detecting.sdks"), project, false) { indicator -> val jdkVersions = mutableListOf<String>() SdkDetector.getInstance().detectSdks(JavaSdk.getInstance(), indicator, object : SdkDetector.DetectedSdkListener { override fun onSdkDetected(type: SdkType, version: String, home: String) { jdkVersions.add(version) } override fun onSearchCompleted() { jdkVersionsFuture.complete(jdkVersions) } }) } val currentJdk = JavaProjectUtil.getProjectJdk(project) @Suppress("HardCodedStringLiteral") val currentJdkVersion: @NlsSafe String = currentJdk?.let { JavaSdk.getInstance().getVersionString(it) } ?: "none" val module = ModuleManager.getInstance(project).modules.first() @Suppress("HardCodedStringLiteral") val currentLanguageLevel: @NlsSafe String = LanguageLevelUtil.getEffectiveLanguageLevel(module).name primaryLanguage.onboardingFeedbackData = object : OnboardingFeedbackData("IDEA Onboarding Tour Feedback", lessonEndInfo) { override val feedbackReportId = "idea_onboarding_tour" override val additionalFeedbackFormatVersion: Int = 0 private val jdkVersions: List<String>? by lazy { if (jdkVersionsFuture.isDone) jdkVersionsFuture.get() else null } override val addAdditionalSystemData: JsonObjectBuilder.() -> Unit = { put("current_jdk", currentJdkVersion) put("language_level", currentLanguageLevel) put("found_jdk", buildJsonArray { for (version in jdkVersions ?: emptyList()) { add(JsonPrimitive(version)) } }) } override val addRowsForUserAgreement: Panel.() -> Unit = { row(JavaLessonsBundle.message("java.onboarding.feedback.system.found.jdks")) { @Suppress("HardCodedStringLiteral") val versions: @NlsSafe String = jdkVersions?.joinToString("\n") ?: "none" cell(MultiLineLabel(versions)) } row(JavaLessonsBundle.message("java.onboarding.feedback.system.current.jdk")) { label(currentJdkVersion) } row(JavaLessonsBundle.message("java.onboarding.feedback.system.lang.level")) { label(currentLanguageLevel) } } override fun feedbackHasBeenProposed() { PropertiesComponent.getInstance().setValue(configPropertyName, true, false) } } } private fun getCallBackActionId(@Suppress("SameParameterValue") actionId: String): Int { val action = getActionById(actionId) return LearningUiManager.addCallback { invokeActionForFocusContext(action) } } private fun LessonContext.debugTasks() { clearBreakpoints() var logicalPosition = LogicalPosition(0, 0) prepareRuntimeTask { logicalPosition = editor.offsetToLogicalPosition(sample.startOffset) } caret(sample.startOffset) toggleBreakpointTask(sample, { logicalPosition }, checkLine = false) { text(JavaLessonsBundle.message("java.onboarding.balloon.click.here"), LearningBalloonConfig(Balloon.Position.below, width = 0, duplicateMessage = false)) text(JavaLessonsBundle.message("java.onboarding.toggle.breakpoint.1", code("6.5"), code("findAverage"), code("26"))) text(JavaLessonsBundle.message("java.onboarding.toggle.breakpoint.2")) } highlightButtonById("Debug") actionTask("Debug") { showBalloonOnHighlightingComponent(JavaLessonsBundle.message("java.onboarding.balloon.start.debugging")) restoreState { lineWithBreakpoints() != setOf(logicalPosition.line) } restoreIfModified(sample) JavaLessonsBundle.message("java.onboarding.start.debugging", icon(AllIcons.Actions.StartDebugger)) } highlightDebugActionsToolbar() task { rehighlightPreviousUi = true text(JavaLessonsBundle.message("java.onboarding.balloon.about.debug.panel", strong(UIBundle.message("tool.window.name.debug")), if (Registry.`is`("debugger.new.tool.window.layout")) 0 else 1, strong(LessonsBundle.message("debug.workflow.lesson.name")))) proceedLink() restoreIfModified(sample) } highlightButtonById("Stop") task { showBalloonOnHighlightingComponent( JavaLessonsBundle.message("java.onboarding.balloon.stop.debugging")) { list -> list.minByOrNull { it.locationOnScreen.y } } text(JavaLessonsBundle.message("java.onboarding.stop.debugging", icon(AllIcons.Actions.Suspend))) restoreIfModified(sample) stateCheck { XDebuggerManager.getInstance(project).currentSession == null } } prepareRuntimeTask { LearningUiHighlightingManager.clearHighlights() } } private fun LessonContext.waitIndexingTasks() { task { triggerAndBorderHighlight().component { progress: NonOpaquePanel -> progress.javaClass.name.contains("InlineProgressPanel") } } task { text(JavaLessonsBundle.message("java.onboarding.indexing.description")) text(JavaLessonsBundle.message("java.onboarding.wait.indexing"), LearningBalloonConfig(Balloon.Position.above, 0)) waitSmartModeStep() } waitBeforeContinue(300) prepareRuntimeTask { LearningUiHighlightingManager.clearHighlights() } } private fun LessonContext.runTasks() { task { highlightRunGutters(2, highlightInside = true, usePulsation = true) } val runItem = ExecutionBundle.message("default.runner.start.action.text").dropMnemonic() + " '$demoConfigurationName.main()'" task { text(JavaLessonsBundle.message("java.onboarding.context.menu")) triggerAndFullHighlight().component { ui: ActionMenuItem -> ui.text == runItem } restoreIfModified(sample) } task { text(JavaLessonsBundle.message("java.onboarding.run.sample", strong(runItem), action("RunClass"))) checkToolWindowState("Run", true) timerCheck { configurations().isNotEmpty() } restoreIfModified(sample) rehighlightPreviousUi = true } highlightRunToolbar() task { text(JavaLessonsBundle.message("java.onboarding.temporary.configuration.description", icon(AllIcons.Actions.Execute), icon(AllIcons.Actions.StartDebugger), icon(AllIcons.Actions.Profile), icon(AllIcons.General.RunWithCoverage))) proceedLink() restoreIfModified(sample) } } private fun LessonContext.openLearnToolwindow() { task { triggerAndFullHighlight { usePulsation = true }.component { stripe: StripeButton -> stripe.windowInfo.id == "Learn" } } task { openLearnTaskId = taskId text(JavaLessonsBundle.message("java.onboarding.balloon.open.learn.toolbar", strong(LearnBundle.message("toolwindow.stripe.Learn"))), LearningBalloonConfig(Balloon.Position.atRight, width = 0, duplicateMessage = true)) stateCheck { ToolWindowManager.getInstance(project).getToolWindow("Learn")?.isVisible == true } restoreIfModified(sample) } prepareRuntimeTask { LearningUiHighlightingManager.clearHighlights() requestEditorFocus() } } private fun LessonContext.checkUiSettings() { hideToolStripesPreference = uiSettings.hideToolStripes showNavigationBarPreference = uiSettings.showNavigationBar showInvalidDebugLayoutWarning() if (!hideToolStripesPreference && (showNavigationBarPreference || uiSettings.showMainToolbar)) { // a small hack to have same tasks count. It is needed to track statistics result. task { } task { } return } task { text(JavaLessonsBundle.message("java.onboarding.change.ui.settings")) proceedLink() } prepareRuntimeTask { uiSettings.hideToolStripes = false uiSettings.showNavigationBar = true uiSettings.fireUISettingsChanged() } } private fun LessonContext.projectTasks() { prepareRuntimeTask { LessonUtil.hideStandardToolwindows(project) } task { triggerAndFullHighlight { usePulsation = true }.component { stripe: StripeButton -> stripe.windowInfo.id == "Project" } } lateinit var openProjectViewTask: TaskContext.TaskId task { openProjectViewTask = taskId var projectDirExpanded = false text(JavaLessonsBundle.message("java.onboarding.project.view.description", action("ActivateProjectToolWindow"))) text(JavaLessonsBundle.message("java.onboarding.balloon.project.view"), LearningBalloonConfig(Balloon.Position.atRight, width = 0)) triggerUI().treeItem { tree: JTree, path: TreePath -> val result = path.pathCount >= 2 && path.getPathComponent(1).isToStringContains("IdeaLearningProject") if (result) { if (!projectDirExpanded) { invokeLater { tree.expandPath(path) } } projectDirExpanded = true } result } } task { var srcDirCollapsed = false triggerAndBorderHighlight().treeItem { tree: JTree, path: TreePath -> val result = path.pathCount >= 3 && path.getPathComponent(1).isToStringContains("IdeaLearningProject") && path.getPathComponent(2).isToStringContains(demoFileDirectory) if (result) { if (!srcDirCollapsed) { invokeLater { tree.collapsePath(path) } } srcDirCollapsed = true } result } } fun isDemoFilePath(path: TreePath) = path.pathCount >= 4 && path.getPathComponent(3).isToStringContains(demoFileName) task { text(JavaLessonsBundle.message("java.onboarding.balloon.source.directory", strong(demoFileDirectory)), LearningBalloonConfig(Balloon.Position.atRight, duplicateMessage = true, width = 0)) triggerAndBorderHighlight().treeItem { _: JTree, path: TreePath -> isDemoFilePath(path) } restoreByUi(openProjectViewTask) } task { text(JavaLessonsBundle.message("java.onboarding.balloon.open.file", strong(demoFileName)), LearningBalloonConfig(Balloon.Position.atRight, duplicateMessage = true, width = 0)) stateCheck l@{ if (FileEditorManager.getInstance(project).selectedTextEditor == null) return@l false virtualFile.name == demoFileName } restoreState { (previous.ui as? JTree)?.takeIf { tree -> TreeUtil.visitVisibleRows(tree, TreeVisitor { path -> if (isDemoFilePath(path)) TreeVisitor.Action.INTERRUPT else TreeVisitor.Action.CONTINUE }) != null }?.isShowing?.not() ?: true } } } private fun LessonContext.completionSteps() { prepareRuntimeTask { setSample(sample.insertAtPosition(2, " / values<caret>")) FocusManagerImpl.getInstance(project).requestFocusInProject(editor.contentComponent, project) } task { text(JavaLessonsBundle.message("java.onboarding.type.division", code(" / values"))) text(JavaLessonsBundle.message("java.onboarding.invoke.completion")) triggerAndBorderHighlight().listItem { // no highlighting it.isToStringContains("length") } proposeRestoreForInvalidText(".") } task { text(JavaLessonsBundle.message("java.onboarding.choose.values.item", code("length"), action("EditorChooseLookupItem"))) text(JavaLessonsBundle.message("java.onboarding.invoke.completion.tip", action("CodeCompletion"))) stateCheck { checkEditorModification(sample, modificationPositionId = 2, needChange = "/values.length") } } } private fun LessonContext.contextActions() { val quickFixMessage = InspectionGadgetsBundle.message("foreach.replace.quickfix") caret(sample.getPosition(3)) task("ShowIntentionActions") { text(JavaLessonsBundle.message("java.onboarding.invoke.intention.for.warning.1")) text(JavaLessonsBundle.message("java.onboarding.invoke.intention.for.warning.2", action(it))) triggerAndBorderHighlight().listItem { item -> item.isToStringContains(quickFixMessage) } restoreIfModifiedOrMoved() } task { text(JavaLessonsBundle.message("java.onboarding.select.fix", strong(quickFixMessage))) stateCheck { editor.document.text.contains("for (int value : values)") } restoreByUi(delayMillis = defaultRestoreDelay) } fun getIntentionMessage(project: Project): @Nls String { val module = ModuleManager.getInstance(project).modules.firstOrNull() ?: error("Not found modules in project '${project.name}'") val langLevel = LanguageLevelUtil.getEffectiveLanguageLevel(module) val messageKey = if (langLevel.isAtLeast(HighlightingFeature.TEXT_BLOCKS.level)) { "replace.concatenation.with.format.string.intention.name.formatted" } else "replace.concatenation.with.format.string.intention.name" return IntentionPowerPackBundle.message(messageKey) } caret("RAGE") task("ShowIntentionActions") { text(JavaLessonsBundle.message("java.onboarding.invoke.intention.for.code", action(it))) val intentionMessage = getIntentionMessage(project) triggerAndBorderHighlight().listItem { item -> item.isToStringContains(intentionMessage) } restoreIfModifiedOrMoved() } task { text(JavaLessonsBundle.message("java.onboarding.apply.intention", strong(getIntentionMessage(project)), LessonUtil.rawEnter())) stateCheck { val text = editor.document.text text.contains("System.out.printf") || text.contains("MessageFormat.format") } restoreByUi(delayMillis = defaultRestoreDelay) } } private fun LessonContext.searchEverywhereTasks() { val toggleCase = ActionsBundle.message("action.EditorToggleCase.text") caret("AVERAGE", select = true) task("SearchEverywhere") { text(JavaLessonsBundle.message("java.onboarding.invoke.search.everywhere.1", strong(toggleCase), code("AVERAGE"))) text(JavaLessonsBundle.message("java.onboarding.invoke.search.everywhere.2", LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT), LessonUtil.actionName(it))) triggerAndBorderHighlight().component { ui: ExtendableTextField -> UIUtil.getParentOfType(SearchEverywhereUI::class.java, ui) != null } restoreIfModifiedOrMoved() } task { transparentRestore = true before { if (backupPopupLocation != null) return@before val ui = previous.ui ?: return@before val popupWindow = UIUtil.getParentOfType(JWindow::class.java, ui) ?: return@before val oldPopupLocation = WindowStateService.getInstance(project).getLocation(SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY) if (adjustSearchEverywherePosition(popupWindow, "of array ") || LessonUtil.adjustPopupPosition(project, popupWindow)) { backupPopupLocation = oldPopupLocation } } text(JavaLessonsBundle.message("java.onboarding.search.everywhere.description", strong("AVERAGE"), strong(JavaLessonsBundle.message("toggle.case.part")))) triggerAndBorderHighlight().listItem { item -> val value = (item as? GotoActionModel.MatchedValue)?.value (value as? GotoActionModel.ActionWrapper)?.action is ToggleCaseAction } restoreByUi() restoreIfModifiedOrMoved() } actionTask("EditorToggleCase") { restoreByUi(delayMillis = defaultRestoreDelay) JavaLessonsBundle.message("java.onboarding.apply.action", strong(toggleCase), LessonUtil.rawEnter()) } text(JavaLessonsBundle.message("java.onboarding.case.changed")) } private fun TaskRuntimeContext.runManager() = RunManager.getInstance(project) private fun TaskRuntimeContext.configurations() = runManager().allSettings.filter { it.name.contains(demoConfigurationName) } }
apache-2.0
18faeefb4cf500d7f1be0cd45c9e7796
37.696241
139
0.702433
5.123855
false
false
false
false
hotchemi/PermissionsDispatcher
ktx-sample/src/main/java/permissions/dispatcher/ktx/sample/MainFragment.kt
1
2129
package permissions.dispatcher.ktx.sample import android.Manifest import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.Toast import androidx.fragment.app.Fragment import permissions.dispatcher.PermissionRequest import permissions.dispatcher.ktx.PermissionsRequester import permissions.dispatcher.ktx.sample.camera.CameraPreviewFragment import permissions.dispatcher.ktx.constructPermissionsRequest class MainFragment : Fragment() { private lateinit var permissionsRequester: PermissionsRequester override fun onAttach(context: Context?) { super.onAttach(context) permissionsRequester = constructPermissionsRequest(Manifest.permission.CAMERA, onShowRationale = ::onCameraShowRationale, onPermissionDenied = ::onCameraDenied, onNeverAskAgain = ::onCameraNeverAskAgain) { fragmentManager?.beginTransaction() ?.replace(R.id.sample_content_fragment, CameraPreviewFragment.newInstance()) ?.addToBackStack("camera") ?.commitAllowingStateLoss() } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_main, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val buttonCamera: Button = view.findViewById(R.id.button_camera) buttonCamera.setOnClickListener { permissionsRequester.launch() } } private fun onCameraDenied() { Toast.makeText(requireContext(), R.string.permission_camera_denied, Toast.LENGTH_SHORT).show() } private fun onCameraShowRationale(request: PermissionRequest) { request.proceed() } private fun onCameraNeverAskAgain() { Toast.makeText(requireContext(), R.string.permission_camera_never_ask_again, Toast.LENGTH_SHORT).show() } }
apache-2.0
4b217aad2feae031dec1cc60ce588f58
37.017857
116
0.732738
5.154964
false
false
false
false
androidx/androidx
inspection/inspection-gradle-plugin/src/main/kotlin/androidx/inspection/gradle/GenerateInspectionPlatformVersionTask.kt
3
4217
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.inspection.gradle import com.android.build.api.variant.Variant import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.Project import org.gradle.api.artifacts.ArtifactCollection import org.gradle.api.artifacts.component.ModuleComponentIdentifier import org.gradle.api.artifacts.component.ProjectComponentIdentifier import org.gradle.api.attributes.Attribute import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.FileCollection import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Internal import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.TaskProvider import org.gradle.work.DisableCachingByDefault import java.io.File /** * Generates a file into META-INF/ folder that has version of androidx.inspection used * during complication. Android Studio checks compatibility of its version with version required * by inspector. */ @DisableCachingByDefault(because = "Simply generates a small file and doesn't benefit from caching") abstract class GenerateInspectionPlatformVersionTask : DefaultTask() { // ArtCollection can't be exposed as input as it is, so below there is "getCompileInputs" // that adds it properly as input. @get:Internal abstract var compileClasspath: ArtifactCollection @PathSensitive(PathSensitivity.NONE) @InputFiles fun getCompileInputs(): FileCollection = compileClasspath.artifactFiles @get:OutputDirectory abstract val outputDir: DirectoryProperty @Input fun getVersion(): String { val artifacts = compileClasspath.artifacts val projectDep = artifacts.any { (it.id.componentIdentifier as? ProjectComponentIdentifier)?.projectPath == ":inspection:inspection" } val prebuiltVersion = artifacts.mapNotNull { it.id.componentIdentifier as? ModuleComponentIdentifier }.firstOrNull { id -> id.group == "androidx.inspection" && id.module == "inspection" }?.version return if (projectDep) { inspectionProjectVersion.get() } else prebuiltVersion ?: throw GradleException( "Inspector must have a dependency on androidx.inspection" ) } @get:Internal abstract val inspectionProjectVersion: Property<String> @TaskAction fun exec() { val file = File(outputDir.asFile.get(), "META-INF/androidx_inspection.min_version") file.parentFile.mkdirs() file.writeText(getVersion()) } } fun Project.registerGenerateInspectionPlatformVersionTask( variant: Variant ): TaskProvider<GenerateInspectionPlatformVersionTask> { val name = variant.taskName("generateInspectionPlatformVersion") return tasks.register(name, GenerateInspectionPlatformVersionTask::class.java) { task -> @Suppress("UnstableApiUsage") task.compileClasspath = variant.compileConfiguration.incoming.artifactView { artifact -> artifact.attributes { it.attribute(Attribute.of("artifactType", String::class.java), "android-classes") } }.artifacts task.outputDir.set(taskWorkingDir(variant, "inspectionVersion")) task.inspectionProjectVersion.set( project.provider { project.project(":inspection:inspection").version.toString() } ) } }
apache-2.0
e49927cce603e86b2a828d24f9aa8f27
37.336364
100
0.732037
4.639164
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/firebase/viewmodels/GroupViewModel.kt
1
2088
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.firebase.viewmodels import android.util.Log import androidx.lifecycle.ViewModel import com.app.playhvz.app.HvzData import com.app.playhvz.firebase.classmodels.Group import com.app.playhvz.firebase.constants.GroupPath import com.app.playhvz.firebase.utils.DataConverterUtil class GroupViewModel : ViewModel() { companion object { private val TAG = GroupViewModel::class.qualifiedName } private var group: HvzData<Group> = HvzData() fun getGroup( gameId: String, groupId: String ): HvzData<Group> { if (groupId in group.docIdListeners) { // We're already listening to changes on this group id. return group } else { stopListening() } group.docIdListeners[groupId] = GroupPath.GROUP_DOCUMENT_REFERENCE(gameId, groupId).addSnapshotListener { snapshot, e -> if (e != null) { Log.w(TAG, "Listen failed.", e) return@addSnapshotListener } if (snapshot == null || !snapshot.exists()) { return@addSnapshotListener } group.value = DataConverterUtil.convertSnapshotToGroup(snapshot) } return group } private fun stopListening() { for (id in group.docIdListeners.keys) { group.docIdListeners[id]!!.remove() group.docIdListeners.remove(id) } } }
apache-2.0
2de0d06f9b74def541ec488f30069abc
32.15873
100
0.64272
4.529284
false
false
false
false
androidx/androidx
compose/material/material/src/commonMain/kotlin/androidx/compose/material/AlertDialog.kt
3
11330
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.layout.AlignmentLine import androidx.compose.ui.layout.FirstBaseline import androidx.compose.ui.layout.LastBaseline import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.Placeable import androidx.compose.ui.layout.layoutId import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.util.fastForEachIndexed import kotlin.math.max @Composable internal fun AlertDialogContent( buttons: @Composable () -> Unit, modifier: Modifier = Modifier, title: (@Composable () -> Unit)? = null, text: @Composable (() -> Unit)? = null, shape: Shape = MaterialTheme.shapes.medium, backgroundColor: Color = MaterialTheme.colors.surface, contentColor: Color = contentColorFor(backgroundColor), ) { Surface( modifier = modifier, shape = shape, color = backgroundColor, contentColor = contentColor ) { Column { AlertDialogBaselineLayout( title = title?.let { @Composable { CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.high) { val textStyle = MaterialTheme.typography.subtitle1 ProvideTextStyle(textStyle, title) } } }, text = text?.let { @Composable { CompositionLocalProvider( LocalContentAlpha provides ContentAlpha.medium ) { val textStyle = MaterialTheme.typography.body2 ProvideTextStyle(textStyle, text) } } } ) buttons() } } } /** * Layout that will add spacing between the top of the layout and [title]'s first baseline, and * [title]'s last baseline and [text]'s first baseline. * * If [title] and/or [text] do not have any baselines, the spacing will just be applied from the * edge of their layouts instead as a best effort implementation. */ @Composable internal fun ColumnScope.AlertDialogBaselineLayout( title: @Composable (() -> Unit)?, text: @Composable (() -> Unit)? ) { Layout( { title?.let { title -> Box(TitlePadding.layoutId("title").align(Alignment.Start)) { title() } } text?.let { text -> Box(TextPadding.layoutId("text").align(Alignment.Start)) { text() } } }, Modifier.weight(1f, false) ) { measurables, constraints -> // Measure with loose constraints for height as we don't want the text to take up more // space than it needs val titlePlaceable = measurables.firstOrNull { it.layoutId == "title" }?.measure( constraints.copy(minHeight = 0) ) val textPlaceable = measurables.firstOrNull { it.layoutId == "text" }?.measure( constraints.copy(minHeight = 0) ) val layoutWidth = max(titlePlaceable?.width ?: 0, textPlaceable?.width ?: 0) val firstTitleBaseline = titlePlaceable?.get(FirstBaseline)?.let { baseline -> if (baseline == AlignmentLine.Unspecified) null else baseline } ?: 0 val lastTitleBaseline = titlePlaceable?.get(LastBaseline)?.let { baseline -> if (baseline == AlignmentLine.Unspecified) null else baseline } ?: 0 val titleOffset = TitleBaselineDistanceFromTop.roundToPx() // Place the title so that its first baseline is titleOffset from the top val titlePositionY = titleOffset - firstTitleBaseline val firstTextBaseline = textPlaceable?.get(FirstBaseline)?.let { baseline -> if (baseline == AlignmentLine.Unspecified) null else baseline } ?: 0 val textOffset = if (titlePlaceable == null) { TextBaselineDistanceFromTop.roundToPx() } else { TextBaselineDistanceFromTitle.roundToPx() } // Combined height of title and spacing above val titleHeightWithSpacing = titlePlaceable?.let { it.height + titlePositionY } ?: 0 // Align the bottom baseline of the text with the bottom baseline of the title, and then // add the offset val textPositionY = if (titlePlaceable == null) { // If there is no title, just place the text offset from the top of the dialog textOffset - firstTextBaseline } else { if (lastTitleBaseline == 0) { // If `title` has no baseline, just place the text's baseline textOffset from the // bottom of the title titleHeightWithSpacing - firstTextBaseline + textOffset } else { // Otherwise place the text's baseline textOffset from the title's last baseline (titlePositionY + lastTitleBaseline) - firstTextBaseline + textOffset } } // Combined height of text and spacing above val textHeightWithSpacing = textPlaceable?.let { if (lastTitleBaseline == 0) { textPlaceable.height + textOffset - firstTextBaseline } else { textPlaceable.height + textOffset - firstTextBaseline - ((titlePlaceable?.height ?: 0) - lastTitleBaseline) } } ?: 0 val layoutHeight = titleHeightWithSpacing + textHeightWithSpacing layout(layoutWidth, layoutHeight) { titlePlaceable?.place(0, titlePositionY) textPlaceable?.place(0, textPositionY) } } } /** * Simple clone of FlowRow that arranges its children in a horizontal flow with limited * customization. */ @Composable internal fun AlertDialogFlowRow( mainAxisSpacing: Dp, crossAxisSpacing: Dp, content: @Composable () -> Unit ) { Layout(content) { measurables, constraints -> val sequences = mutableListOf<List<Placeable>>() val crossAxisSizes = mutableListOf<Int>() val crossAxisPositions = mutableListOf<Int>() var mainAxisSpace = 0 var crossAxisSpace = 0 val currentSequence = mutableListOf<Placeable>() var currentMainAxisSize = 0 var currentCrossAxisSize = 0 val childConstraints = Constraints(maxWidth = constraints.maxWidth) // Return whether the placeable can be added to the current sequence. fun canAddToCurrentSequence(placeable: Placeable) = currentSequence.isEmpty() || currentMainAxisSize + mainAxisSpacing.roundToPx() + placeable.width <= constraints.maxWidth // Store current sequence information and start a new sequence. fun startNewSequence() { if (sequences.isNotEmpty()) { crossAxisSpace += crossAxisSpacing.roundToPx() } sequences += currentSequence.toList() crossAxisSizes += currentCrossAxisSize crossAxisPositions += crossAxisSpace crossAxisSpace += currentCrossAxisSize mainAxisSpace = max(mainAxisSpace, currentMainAxisSize) currentSequence.clear() currentMainAxisSize = 0 currentCrossAxisSize = 0 } for (measurable in measurables) { // Ask the child for its preferred size. val placeable = measurable.measure(childConstraints) // Start a new sequence if there is not enough space. if (!canAddToCurrentSequence(placeable)) startNewSequence() // Add the child to the current sequence. if (currentSequence.isNotEmpty()) { currentMainAxisSize += mainAxisSpacing.roundToPx() } currentSequence.add(placeable) currentMainAxisSize += placeable.width currentCrossAxisSize = max(currentCrossAxisSize, placeable.height) } if (currentSequence.isNotEmpty()) startNewSequence() val mainAxisLayoutSize = if (constraints.maxWidth != Constraints.Infinity) { constraints.maxWidth } else { max(mainAxisSpace, constraints.minWidth) } val crossAxisLayoutSize = max(crossAxisSpace, constraints.minHeight) val layoutWidth = mainAxisLayoutSize val layoutHeight = crossAxisLayoutSize layout(layoutWidth, layoutHeight) { sequences.fastForEachIndexed { i, placeables -> val childrenMainAxisSizes = IntArray(placeables.size) { j -> placeables[j].width + if (j < placeables.lastIndex) mainAxisSpacing.roundToPx() else 0 } val arrangement = Arrangement.Bottom // TODO(soboleva): rtl support // Handle vertical direction val mainAxisPositions = IntArray(childrenMainAxisSizes.size) { 0 } with(arrangement) { arrange(mainAxisLayoutSize, childrenMainAxisSizes, mainAxisPositions) } placeables.fastForEachIndexed { j, placeable -> placeable.place( x = mainAxisPositions[j], y = crossAxisPositions[i] ) } } } } } private val TitlePadding = Modifier.padding(start = 24.dp, end = 24.dp) private val TextPadding = Modifier.padding(start = 24.dp, end = 24.dp, bottom = 28.dp) // Baseline distance from the first line of the title to the top of the dialog private val TitleBaselineDistanceFromTop = 40.sp // Baseline distance from the first line of the text to the last line of the title private val TextBaselineDistanceFromTitle = 36.sp // For dialogs with no title, baseline distance from the first line of the text to the top of the // dialog private val TextBaselineDistanceFromTop = 38.sp
apache-2.0
d8dc0d6f0b90d1bd8f1f76e5dd5ea242
38.068966
97
0.628244
5.235675
false
false
false
false
androidx/androidx
wear/watchface/watchface-client/src/main/java/androidx/wear/watchface/client/DeviceConfig.kt
3
3491
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.watchface.client import androidx.annotation.RestrictTo typealias WireDeviceConfig = androidx.wear.watchface.data.DeviceConfig /** * Describes the hardware configuration of the device the watch face is running on. * * @param hasLowBitAmbient Whether or not the watch hardware supports low bit ambient support. * @param hasBurnInProtection Whether or not the watch hardware supports burn in protection. * @param analogPreviewReferenceTimeMillis UTC reference time for screenshots of analog watch faces * in milliseconds since the epoch. * @param digitalPreviewReferenceTimeMillis UTC reference time for screenshots of digital watch * faces in milliseconds since the epoch. */ public class DeviceConfig( @get:JvmName("hasLowBitAmbient") public val hasLowBitAmbient: Boolean, @get:JvmName("hasBurnInProtection") public val hasBurnInProtection: Boolean, public val analogPreviewReferenceTimeMillis: Long, public val digitalPreviewReferenceTimeMillis: Long ) { /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public fun asWireDeviceConfig(): WireDeviceConfig = WireDeviceConfig( hasLowBitAmbient, hasBurnInProtection, analogPreviewReferenceTimeMillis, digitalPreviewReferenceTimeMillis ) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as DeviceConfig if (hasLowBitAmbient != other.hasLowBitAmbient) { return false } if (hasBurnInProtection != other.hasBurnInProtection) { return false } if (analogPreviewReferenceTimeMillis != other.analogPreviewReferenceTimeMillis) { return false } if (digitalPreviewReferenceTimeMillis != other.digitalPreviewReferenceTimeMillis) { return false } return true } override fun hashCode(): Int { var result = hasLowBitAmbient.hashCode() result = 31 * result + hasBurnInProtection.hashCode() result = 31 * result + analogPreviewReferenceTimeMillis.hashCode() result = 31 * result + digitalPreviewReferenceTimeMillis.hashCode() return result } override fun toString(): String { return "DeviceConfig(hasLowBitAmbient=$hasLowBitAmbient, " + "hasBurnInProtection=$hasBurnInProtection, " + "analogPreviewReferenceTimeMillis=$analogPreviewReferenceTimeMillis, " + "digitalPreviewReferenceTimeMillis=$digitalPreviewReferenceTimeMillis)" } } /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public fun WireDeviceConfig.asApiDeviceConfig(): DeviceConfig = DeviceConfig( hasLowBitAmbient, hasBurnInProtection, analogPreviewReferenceTimeMillis, digitalPreviewReferenceTimeMillis )
apache-2.0
51d3f7d71f94f033ed4bcb06581252fe
36.148936
99
0.723288
4.756131
false
true
false
false
yschimke/okhttp
okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt
1
6158
/* * Copyright (C) 2022 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.io.Closeable import java.net.InetSocketAddress import java.net.Proxy import java.net.ProxySelector import java.net.Socket import java.util.concurrent.TimeUnit import javax.net.SocketFactory import javax.net.ssl.HostnameVerifier import javax.net.ssl.HttpsURLConnection import javax.net.ssl.SSLSocketFactory import okhttp3.internal.RecordingOkAuthenticator import okhttp3.internal.concurrent.TaskFaker import okhttp3.internal.concurrent.TaskRunner import okhttp3.internal.connection.RealCall import okhttp3.internal.connection.RealConnection import okhttp3.internal.connection.RealConnectionPool import okhttp3.internal.connection.RealRoutePlanner import okhttp3.internal.http.RealInterceptorChain import okhttp3.internal.http.RecordingProxySelector import okhttp3.tls.HandshakeCertificates import okhttp3.tls.internal.TlsUtil.localhost /** * OkHttp is usually tested with functional tests: these use public APIs to confirm behavior against * MockWebServer. In cases where logic is particularly tricky, we use unit tests. This class makes * it easy to get sample values to use in such tests. * * This class is pretty fast and loose with default values: it attempts to provide values that are * well-formed, but doesn't guarantee values are internally consistent. Callers must take care to * configure the factory when sample values impact the correctness of the test. */ class TestValueFactory : Closeable { var taskFaker: TaskFaker = TaskFaker() var taskRunner: TaskRunner = taskFaker.taskRunner var dns: Dns = Dns.SYSTEM var proxy: Proxy = Proxy.NO_PROXY var proxySelector: ProxySelector = RecordingProxySelector() var proxyAuthenticator: Authenticator = RecordingOkAuthenticator("password", null) var connectionSpecs: List<ConnectionSpec> = listOf( ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS, ConnectionSpec.CLEARTEXT, ) var protocols: List<Protocol> = listOf( Protocol.HTTP_1_1, ) var handshakeCertificates: HandshakeCertificates = localhost() var sslSocketFactory: SSLSocketFactory? = handshakeCertificates.sslSocketFactory() var hostnameVerifier: HostnameVerifier? = HttpsURLConnection.getDefaultHostnameVerifier() var uriHost: String = "example.com" var uriPort: Int = 1 fun newConnection( pool: RealConnectionPool, route: Route, idleAtNanos: Long = Long.MAX_VALUE, taskRunner: TaskRunner = this.taskRunner, ): RealConnection { val result = RealConnection.newTestConnection( taskRunner = taskRunner, connectionPool = pool, route = route, socket = Socket(), idleAtNs = idleAtNanos ) synchronized(result) { pool.put(result) } return result } fun newConnectionPool( taskRunner: TaskRunner = this.taskRunner, maxIdleConnections: Int = Int.MAX_VALUE, ): RealConnectionPool { return RealConnectionPool( taskRunner = taskRunner, maxIdleConnections = maxIdleConnections, keepAliveDuration = 100L, timeUnit = TimeUnit.NANOSECONDS ) } /** Returns an address that's without an SSL socket factory or hostname verifier. */ fun newAddress( uriHost: String = this.uriHost, uriPort: Int = this.uriPort, proxy: Proxy? = null, proxySelector: ProxySelector = this.proxySelector, ): Address { return Address( uriHost = uriHost, uriPort = uriPort, dns = dns, socketFactory = SocketFactory.getDefault(), sslSocketFactory = null, hostnameVerifier = null, certificatePinner = null, proxyAuthenticator = proxyAuthenticator, proxy = proxy, protocols = protocols, connectionSpecs = connectionSpecs, proxySelector = proxySelector, ) } fun newHttpsAddress( uriHost: String = this.uriHost, uriPort: Int = this.uriPort, proxy: Proxy? = null, proxySelector: ProxySelector = this.proxySelector, sslSocketFactory: SSLSocketFactory? = this.sslSocketFactory, hostnameVerifier: HostnameVerifier? = this.hostnameVerifier, ): Address { return Address( uriHost = uriHost, uriPort = uriPort, dns = dns, socketFactory = SocketFactory.getDefault(), sslSocketFactory = sslSocketFactory, hostnameVerifier = hostnameVerifier, certificatePinner = null, proxyAuthenticator = proxyAuthenticator, proxy = proxy, protocols = protocols, connectionSpecs = connectionSpecs, proxySelector = proxySelector, ) } fun newRoute( address: Address = newAddress(), proxy: Proxy = this.proxy, socketAddress: InetSocketAddress = InetSocketAddress.createUnresolved(uriHost, uriPort) ): Route { return Route( address = address, proxy = proxy, socketAddress = socketAddress ) } fun newChain( call: RealCall, ): RealInterceptorChain { return RealInterceptorChain( call = call, interceptors = listOf(), index = 0, exchange = null, request = call.request(), connectTimeoutMillis = 10_000, readTimeoutMillis = 10_000, writeTimeoutMillis = 10_000 ) } fun newRequest(address: Address): Request { return Request.Builder() .url(address.url) .build() } fun newRoutePlanner( client: OkHttpClient, address: Address = newAddress(), ): RealRoutePlanner { val call = RealCall(client, newRequest(address), forWebSocket = false) return RealRoutePlanner(client, address, call, newChain(call)) } override fun close() { taskFaker.close() } }
apache-2.0
1fc7cb02412ff135eadb2bea24b62b70
31.240838
100
0.724099
4.491612
false
false
false
false
siosio/intellij-community
platform/statistics/src/com/intellij/internal/statistic/beans/MetricEventUtil.kt
1
6020
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.beans import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.openapi.util.Comparing import org.jetbrains.annotations.ApiStatus /** * Reports numerical or string value of the setting if it's not default. */ @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, Any>, eventId: String) { addIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, null) } /** * Reports numerical or string value of the setting if it's not default. */ @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, Any>, eventId: String, data: FeatureUsageData?) { addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { when (it) { is Int -> newMetric(eventId, it, data) is Float -> newMetric(eventId, it, data) else -> newMetric(eventId, it.toString(), data) } } } /** * Reports the value of boolean setting (i.e. enabled or disabled) if it's not default. */ @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addBoolIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, Boolean>, eventId: String) { addBoolIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, null) } /** * Reports the value of boolean setting (i.e. enabled or disabled) if it's not default. */ @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addBoolIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, Boolean>, eventId: String, data: FeatureUsageData?) { addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { newBooleanMetric(eventId, it, data) } } /** * Adds counter value if count is greater than 0 */ @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addCounterIfNotZero(set: MutableSet<in MetricEvent>, eventId: String, count: Int) { if (count > 0) { set.add(newCounterMetric(eventId, count)) } } /** * Adds counter value if count is greater than 0 */ @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addCounterIfNotZero(set: MutableSet<in MetricEvent>, eventId: String, count: Int, data: FeatureUsageData?) { if (count > 0) { set.add(newCounterMetric(eventId, count, data)) } } @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addCounterIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, Int>, eventId: String) { addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { newCounterMetric(eventId, it) } } @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addCounterIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, Int>, eventId: String, data: FeatureUsageData?) { addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { newCounterMetric(eventId, it, data) } } @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T, V : Enum<*>> addEnumIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, V>, eventId: String) { addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { newMetric(eventId, it, null) } } @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T, V> addMetricIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: (T) -> V, eventIdFunc: (V) -> MetricEvent) { val value = valueFunction(settingsBean) val defaultValue = valueFunction(defaultSettingsBean) if (!Comparing.equal(value, defaultValue)) { set.add(eventIdFunc(value)) } } interface MetricDifferenceBuilder<T> { fun add(eventId: String, valueFunction: (T) -> Any) fun addBool(eventId: String, valueFunction: (T) -> Boolean) } @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addMetricsIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, data: FeatureUsageData, callback: MetricDifferenceBuilder<T>.() -> Unit) { callback(object : MetricDifferenceBuilder<T> { override fun add(eventId: String, valueFunction: (T) -> Any) { addIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, data) } override fun addBool(eventId: String, valueFunction: (T) -> Boolean) { addBoolIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, data) } }) }
apache-2.0
4785ca44e47ade83629f3c8e9dcb9704
45.666667
140
0.720598
4.123288
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertEnumToSealedClassIntention.kt
1
6614
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject import org.jetbrains.kotlin.idea.project.platform import org.jetbrains.kotlin.idea.refactoring.withExpectedActuals import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe class ConvertEnumToSealedClassIntention : SelfTargetingRangeIntention<KtClass>( KtClass::class.java, KotlinBundle.lazyMessage("convert.to.sealed.class") ) { override fun applicabilityRange(element: KtClass): TextRange? { if (element.getClassKeyword() == null) return null val nameIdentifier = element.nameIdentifier ?: return null val enumKeyword = element.modifierList?.getModifier(KtTokens.ENUM_KEYWORD) ?: return null return TextRange(enumKeyword.startOffset, nameIdentifier.endOffset) } override fun applyTo(element: KtClass, editor: Editor?) { val name = element.name ?: return if (name.isEmpty()) return for (klass in element.withExpectedActuals()) { klass as? KtClass ?: continue val classDescriptor = klass.resolveToDescriptorIfAny() ?: continue val isExpect = classDescriptor.isExpect val isActual = classDescriptor.isActual klass.removeModifier(KtTokens.ENUM_KEYWORD) klass.addModifier(KtTokens.SEALED_KEYWORD) val psiFactory = KtPsiFactory(klass) val objects = mutableListOf<KtObjectDeclaration>() for (member in klass.declarations) { if (member !is KtEnumEntry) continue val obj = psiFactory.createDeclaration<KtObjectDeclaration>("object ${member.name}") val initializers = member.initializerList?.initializers ?: emptyList() if (initializers.isNotEmpty()) { initializers.forEach { obj.addSuperTypeListEntry(psiFactory.createSuperTypeCallEntry("${klass.name}${it.text}")) } } else { val defaultEntry = if (isExpect) psiFactory.createSuperTypeEntry(name) else psiFactory.createSuperTypeCallEntry("$name()") obj.addSuperTypeListEntry(defaultEntry) } if (isActual) { obj.addModifier(KtTokens.ACTUAL_KEYWORD) } member.body?.let { body -> obj.add(body) } obj.addComments(member) member.delete() klass.addDeclaration(obj) objects.add(obj) } if (element.platform.isJvm()) { val enumEntryNames = objects.map { it.nameAsSafeName.asString() } val targetClassName = klass.name if (enumEntryNames.isNotEmpty() && targetClassName != null) { val companionObject = klass.getOrCreateCompanionObject() companionObject.addValuesFunction(targetClassName, enumEntryNames, psiFactory) companionObject.addValueOfFunction(targetClassName, classDescriptor, enumEntryNames, psiFactory) } } klass.body?.let { body -> body.allChildren .takeWhile { it !is KtDeclaration } .firstOrNull { it.node.elementType == KtTokens.SEMICOLON } ?.let { semicolon -> val nonWhiteSibling = semicolon.siblings(forward = true, withItself = false).firstOrNull { it !is PsiWhiteSpace } body.deleteChildRange(semicolon, nonWhiteSibling?.prevSibling ?: semicolon) if (nonWhiteSibling != null) { CodeStyleManager.getInstance(klass.project).reformat(nonWhiteSibling.firstChild ?: nonWhiteSibling) } } } } } private fun KtObjectDeclaration.addValuesFunction(targetClassName: String, enumEntryNames: List<String>, psiFactory: KtPsiFactory) { val functionText = "fun values(): Array<${targetClassName}> { return arrayOf(${enumEntryNames.joinToString()}) }" addDeclaration(psiFactory.createFunction(functionText)) } private fun KtObjectDeclaration.addValueOfFunction( targetClassName: String, classDescriptor: ClassDescriptor, enumEntryNames: List<String>, psiFactory: KtPsiFactory ) { val classFqName = classDescriptor.fqNameSafe.asString() val functionText = buildString { append("fun valueOf(value: String): $targetClassName {") append("return when(value) {") enumEntryNames.forEach { append("\"$it\" -> $it\n") } append("else -> throw IllegalArgumentException(\"No object $classFqName.\$value\")") append("}") append("}") } addDeclaration(psiFactory.createFunction(functionText)) } private fun KtObjectDeclaration.addComments(enumEntry: KtEnumEntry) { val (headComments, tailComments) = enumEntry.allChildren.toList().let { children -> children.takeWhile { it.isCommentOrWhiteSpace() } to children.takeLastWhile { it.isCommentOrWhiteSpace() } } if (headComments.isNotEmpty()) { val anchor = this.allChildren.first() headComments.forEach { addBefore(it, anchor) } } if (tailComments.isNotEmpty()) { val anchor = this.allChildren.last() tailComments.reversed().forEach { addAfter(it, anchor) } } } private fun PsiElement.isCommentOrWhiteSpace() = this is PsiComment || this is PsiWhiteSpace }
apache-2.0
9609f4d2046680adc347a9797a9ab96a
43.993197
158
0.649531
5.461602
false
false
false
false