repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/services/UriHelper.kt
1
4541
package com.pr0gramm.app.services import android.content.Context import android.net.Uri import androidx.core.net.toUri import com.pr0gramm.app.api.pr0gramm.Thumbnail import com.pr0gramm.app.feed.FeedItem import com.pr0gramm.app.feed.FeedType import com.pr0gramm.app.services.preloading.PreloadManager import com.pr0gramm.app.util.di.injector /** * A little helper class to work with URLs */ class UriHelper private constructor(context: Context) { private val preloadManager: PreloadManager by lazy { context.injector.instance<PreloadManager>() } fun thumbnail(item: Thumbnail): Uri { val preloaded = preloadManager[item.id] if (preloaded != null) return preloaded.thumbnail.toUri() return NoPreload.thumbnail(item) } fun fullThumbnail(item: Thumbnail): Uri { val preloaded = preloadManager[item.id] if (preloaded?.thumbnailFull != null) return preloaded.thumbnailFull.toUri() return NoPreload.thumbnail(item, full = true) } fun media(item: FeedItem, hq: Boolean = false): Uri { if (hq && item.fullsize.isNotEmpty()) return NoPreload.media(item, true) val preloaded = preloadManager[item.id] if (preloaded != null) return preloaded.media.toUri() return NoPreload.media(item, highQuality = false) } fun image(id: Long, image: String): Uri { val preloaded = preloadManager[id] if (preloaded != null) return preloaded.media.toUri() return NoPreload.image(image) } fun base(): Uri { return start().build() } fun user(name: String): Uri { return start().appendPath("user").appendPath(name).build() } fun post(type: FeedType, itemId: Long): Uri { return start().path(FEED_TYPES[type]) .appendPath(itemId.toString()) .build() } fun post(type: FeedType, itemId: Long, commentId: Long): Uri { return start().path(FEED_TYPES[type]) .appendEncodedPath("$itemId:comment$commentId") .build() } fun uploads(user: String): Uri { return start().path("/user/$user/uploads").build() } fun badgeImageUrl(image: String): Uri { if (image.startsWith("http://") || image.startsWith("https://")) { return Uri.parse(image) } if (image.startsWith("//")) { return Uri.parse("https:$image") } val builder = Uri.parse("https://pr0gramm.com/media/badges/").buildUpon() return if (image.startsWith("/")) { builder.path(image).build() } else { builder.appendEncodedPath(image).build() } } private fun start(): Uri.Builder { return Uri.Builder() .scheme("https") .authority("pr0gramm.com") } object NoPreload { fun media(item: FeedItem, highQuality: Boolean = false): Uri { return if (highQuality && !item.isVideo) absoluteJoin(start("full"), item.fullsize) else absoluteJoin(start(if (item.isVideo) "vid" else "img"), item.image) } fun image(image: String): Uri { return absoluteJoin(start("img"), image) } fun thumbnail(item: Thumbnail, full: Boolean = false): Uri { var path = item.thumbnail ?: "" if (full) { path = path.replace(".jpg", "-original.webp") } return absoluteJoin(start("thumb"), path) } private fun absoluteJoin(builder: Uri.Builder, path: String): Uri { if (path.startsWith("http://") || path.startsWith("https://")) { return Uri.parse(path) } if (path.startsWith("//")) { return Uri.parse("https:$path") } val normalized = if (path.startsWith("/")) path else "/$path" return builder.path(normalized).build() } private fun start(subdomain: String): Uri.Builder { return Uri.Builder() .scheme("https") .authority("$subdomain.pr0gramm.com") } } companion object { fun of(context: Context): UriHelper { return UriHelper(context) } private val FEED_TYPES = mapOf( FeedType.NEW to "new", FeedType.PROMOTED to "top", FeedType.STALK to "stalk") } }
mit
539be064b59120515762ff2cf64b3d8c
28.679739
102
0.569258
4.408738
false
false
false
false
Mauin/detekt
detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/extensions/DetektExtension.kt
1
1723
package io.gitlab.arturbosch.detekt.extensions import groovy.lang.Closure import org.gradle.api.Project import org.gradle.api.file.FileCollection import org.gradle.api.plugins.quality.CodeQualityExtension import org.gradle.api.reporting.ReportingExtension import org.gradle.util.ConfigureUtil import java.io.File /** * @author Artur Bosch * @author Said Tahsin Dane * @author Marvin Ramin * @author Markus Schwarz */ open class DetektExtension(project: Project) : CodeQualityExtension() { val defaultReportsDir: File = project.layout.buildDirectory.get() .dir(ReportingExtension.DEFAULT_REPORTS_DIR_NAME) .dir("detekt").asFile val reports = DetektReports() fun reports(configure: DetektReports.() -> Unit) = reports.configure() fun reports(configure: Closure<*>): DetektReports = ConfigureUtil.configure(configure, reports) val idea = IdeaExtension() fun idea(configure: IdeaExtension.() -> Unit) = idea.configure() fun idea(configure: Closure<*>): IdeaExtension = ConfigureUtil.configure(configure, idea) var input: FileCollection = project.files(DEFAULT_SRC_DIR_JAVA, DEFAULT_SRC_DIR_KOTLIN) var baseline: File? = null var config: FileCollection? = null var debug: Boolean = DEFAULT_DEBUG_VALUE var parallel: Boolean = DEFAULT_PARALLEL_VALUE var disableDefaultRuleSets: Boolean = DEFAULT_DISABLE_RULESETS_VALUE var filters: String? = null var plugins: String? = null companion object { const val DEFAULT_SRC_DIR_JAVA = "src/main/java" const val DEFAULT_SRC_DIR_KOTLIN = "src/main/kotlin" const val DEFAULT_DEBUG_VALUE = false const val DEFAULT_PARALLEL_VALUE = false const val DEFAULT_DISABLE_RULESETS_VALUE = false const val DEFAULT_REPORT_ENABLED_VALUE = true } }
apache-2.0
88ca546c4a89b0a4ea7465f21f2d0061
29.767857
96
0.763784
3.697425
false
true
false
false
clappr/clappr-android
clappr/src/test/kotlin/io/clappr/player/plugin/PluginTest.kt
1
1957
package io.clappr.player.plugin import android.annotation.SuppressLint import androidx.test.core.app.ApplicationProvider import io.clappr.player.base.BaseObject import io.clappr.player.base.InternalEvent import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [23]) class PluginTest { class TestPlugin: Plugin, BaseObject() @Before fun setup() { BaseObject.applicationContext = ApplicationProvider.getApplicationContext() } @Test fun shouldStartDisabled() { val plugin = TestPlugin() assertTrue("plugin enabled", plugin.state == Plugin.State.DISABLED) } @Test fun shouldStopListeningOnDestroy() { val triggerObject = BaseObject() val plugin = TestPlugin() var numberOfTriggers = 0 plugin.listenTo(triggerObject, "pluginTest") { numberOfTriggers++ } triggerObject.trigger("pluginTest") assertEquals("no trigger", 1, numberOfTriggers) plugin.destroy() triggerObject.trigger("pluginTest") assertEquals("no trigger", 1, numberOfTriggers) } @SuppressLint("IgnoreWithoutReason") @Test @Ignore fun shouldTriggerEventsOnDestroy() { val listenObject = BaseObject() val plugin = TestPlugin() var willDestroyCalled = false var didDestroyCalled = false listenObject.listenTo(plugin, InternalEvent.WILL_DESTROY.value) { willDestroyCalled = true } listenObject.listenTo(plugin, InternalEvent.DID_DESTROY.value) { didDestroyCalled = true } plugin.destroy() assertTrue("Will destroy not triggered", willDestroyCalled) assertTrue("Did destroy not triggered", didDestroyCalled) } }
bsd-3-clause
15134bfb03b749e9894b0874cd10dcf9
29.123077
100
0.71487
4.773171
false
true
false
false
AcapellaSoft/Aconite
aconite-client/src/io/aconite/client/FunctionProxies.kt
1
7862
package io.aconite.client import io.aconite.AconiteException import io.aconite.Request import io.aconite.Response import io.aconite.parser.* import kotlin.reflect.KFunction internal interface FunctionProxy { suspend fun call(url: String, request: Request, args: Array<Any?>): Any? } internal class FunctionModuleProxy( val client: AconiteClient, desc: ModuleMethodDesc ): FunctionProxy { private val appliers = buildAppliers(client, desc.arguments) private val response = desc.response private val returnCls = desc.response.clazz private val url = desc.url override suspend fun call(url: String, request: Request, args: Array<Any?>): Any? { val appliedRequest = request.apply(appliers, args) val appliedUrl = url + this.url.format(appliedRequest.path) val handler = client.moduleFactory.create(response) val module = KotlinProxyFactory.create(returnCls) { fn, innerArgs -> handler.invoke(fn, appliedUrl, appliedRequest, innerArgs) } return module } } internal class FunctionMethodProxy( private val client: AconiteClient, desc: HttpMethodDesc ): FunctionProxy { private val appliers = buildAppliers(client, desc.arguments) private val responseDeserializer = responseDeserializer(client, desc) private val url = desc.url private val method = desc.method override suspend fun call(url: String, request: Request, args: Array<Any?>): Any? { val appliedRequest = request.apply(appliers, args).copy(method = method) val appliedUrl = url + this.url.format(appliedRequest.path) val response = client.acceptor.accept(appliedUrl, appliedRequest) return responseDeserializer(response) } } typealias ResponseDeserializer = (response: Response) -> Any? private class ResponseToDeserializer( private val client: AconiteClient, private val fn: KFunction<*> ) : ResponseDesc.Visitor<ResponseDeserializer> { override fun body(desc: BodyResponseDesc): ResponseDeserializer { val bodyDeserializer = client.bodySerializer.create(fn, desc.type) ?: throw AconiteException("No suitable serializer found for response body of method '$fn'") return { r -> r.body?.let { bodyDeserializer.deserialize(it) } } } override fun complex(desc: ComplexResponseDesc): ResponseDeserializer { val transformers = transformResponseParams(client, desc.fields) return { r -> val params = transformers.map { it.process(r) } desc.constructor.call(*params.toTypedArray()) } } } private fun responseDeserializer(client: AconiteClient, desc: HttpMethodDesc): ResponseDeserializer { val responseToDeserializer = ResponseToDeserializer(client, desc.resolvedFunction) return desc.response.visit(responseToDeserializer) } private class ArgumentToApplier(private val client: AconiteClient) : ArgumentDesc.Visitor<ArgumentApplier> { override fun header(desc: HeaderArgumentDesc) = HeaderApplier(client, desc) override fun path(desc: PathArgumentDesc) = PathApplier(client, desc) override fun query(desc: QueryArgumentDesc) = QueryApplier(client, desc) override fun body(desc: BodyArgumentDesc) = BodyApplier(client, desc) } private fun buildAppliers(client: AconiteClient, arguments: List<ArgumentDesc>) : List<ArgumentApplier> { val argumentToApplier = ArgumentToApplier(client) return arguments.map { it.visit(argumentToApplier) } } private interface ArgumentApplier { fun apply(request: Request, value: Any?): Request } private class BodyApplier(client: AconiteClient, desc: BodyArgumentDesc): ArgumentApplier { private val serializer = client.bodySerializer.create(desc.parameter, desc.parameter.type) ?: throw AconiteException("No suitable serializer found for body parameter '${desc.parameter}'") override fun apply(request: Request, value: Any?): Request { val serialized = serializer.serialize(value) return request.copy(body = serialized) } } private class HeaderApplier(client: AconiteClient, desc: HeaderArgumentDesc): ArgumentApplier { private val serializer = client.stringSerializer.create(desc.parameter, desc.parameter.type) ?: throw AconiteException("No suitable serializer found for header parameter '${desc.parameter}'") val name = desc.name override fun apply(request: Request, value: Any?): Request { val serialized = serializer.serialize(value) ?: return request return request.copy( headers = request.headers + Pair(name, serialized) ) } } private class PathApplier(client: AconiteClient, desc: PathArgumentDesc): ArgumentApplier { private val serializer = client.stringSerializer.create(desc.parameter, desc.parameter.type) ?: throw AconiteException("No suitable serializer found for path parameter '${desc.parameter}'") val name = desc.name override fun apply(request: Request, value: Any?): Request { val serialized = serializer.serialize(value) ?: return request return request.copy( path = request.path + Pair(name, serialized) ) } } private class QueryApplier(client: AconiteClient, desc: QueryArgumentDesc): ArgumentApplier { private val serializer = client.stringSerializer.create(desc.parameter, desc.parameter.type) ?: throw AconiteException("No suitable serializer found for query parameter '${desc.parameter}'") val name = desc.name override fun apply(request: Request, value: Any?): Request { val serialized = serializer.serialize(value) ?: return request return request.copy( query = request.query + Pair(name, serialized) ) } } private fun Request.apply(appliers: List<ArgumentApplier>, values: Array<Any?>): Request { var appliedRequest = this for (i in 0 until appliers.size) appliedRequest = appliers[i].apply(appliedRequest, values[i]) return appliedRequest } private class FieldToTransformer(private val client: AconiteClient) : FieldDesc.Visitor<ResponseTransformer> { override fun header(desc: HeaderFieldDesc) = HeaderResponseTransformer(client, desc) override fun body(desc: BodyFieldDesc) = BodyResponseTransformer(client, desc) } fun transformResponseParams(client: AconiteClient, fields: List<FieldDesc>): List<ResponseTransformer> { val fieldToTransformer = FieldToTransformer(client) return fields.map { it.visit(fieldToTransformer) } } interface ResponseTransformer { fun process(response: Response): Any? } class BodyResponseTransformer(client: AconiteClient, desc: BodyFieldDesc) : ResponseTransformer { private val deserializer = client.bodySerializer.create(desc.property, desc.property.returnType) ?: throw AconiteException("No suitable serializer found for body property '${desc.property}'") private val optional = desc.isOptional override fun process(response: Response): Any? { val body = response.body return if (optional && body == null) { null } else { deserializer.deserialize(body!!) } } } class HeaderResponseTransformer(client: AconiteClient, desc: HeaderFieldDesc) : ResponseTransformer { private val deserializer = client.stringSerializer.create(desc.property, desc.property.returnType) ?: throw AconiteException("No suitable serializer found for header property '${desc.property}'") private val name = desc.name private val optional = desc.isOptional override fun process(response: Response): Any? { val header = response.headers[name] return if (optional && header == null) { null } else { deserializer.deserialize(header!!) } } }
mit
88395e52afdf16e47ee69f06296132a8
39.323077
110
0.71216
4.657583
false
false
false
false
JVMDeveloperID/kotlin-android-example
app/src/main/kotlin/com/gojek/sample/kotlin/internal/data/local/dao/ContactsDao.kt
1
1409
package com.gojek.sample.kotlin.internal.data.local.dao import com.gojek.sample.kotlin.extensions.membersOf import com.gojek.sample.kotlin.internal.data.local.realm.ContactsRealm import io.realm.Realm import io.realm.RealmResults import io.realm.internal.IOException class ContactsDao : Dao<ContactsRealm> { override fun saveOrUpdate(data: ContactsRealm) { val realm: Realm = Realm.getDefaultInstance() realm.executeTransactionAsync({ realm -> realm.insertOrUpdate(data) }, { realm.close() }) { realm.close() } } override fun findAll(): List<ContactsRealm> { val realm: Realm = Realm.getDefaultInstance() val data: RealmResults<ContactsRealm> = realm.where(membersOf<ContactsRealm>()).findAll() realm.close() return data } override fun findOne(): ContactsRealm { try { val realm: Realm = Realm.getDefaultInstance() val data: ContactsRealm = realm.copyFromRealm(realm.where(membersOf<ContactsRealm>()).findFirst()) realm.close() return data } catch (e: IOException) { e.printStackTrace() return ContactsRealm() } } override fun delete() { val realm: Realm = Realm.getDefaultInstance() realm.executeTransactionAsync({ realm -> realm.delete(membersOf<ContactsRealm>()) }, { realm.close() }) { realm.close() } } }
apache-2.0
074a904937065ea668c2f49555e6d029
33.390244
129
0.662881
4.665563
false
false
false
false
GeoffreyMetais/vlc-android
application/moviepedia/src/main/java/org/videolan/moviepedia/provider/MediaScrapingTvshowProvider.kt
1
6804
/* * ************************************************************************ * MoviepediaTvshowProvider.kt * ************************************************************************* * Copyright © 2019 VLC authors and VideoLAN * Author: Nicolas POMEPUY * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * ************************************************************************** * * */ package org.videolan.moviepedia.provider import android.content.Context import androidx.annotation.MainThread import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.videolan.medialibrary.interfaces.Medialibrary import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.moviepedia.database.models.MediaMetadataWithImages import org.videolan.moviepedia.repository.MediaMetadataRepository import org.videolan.moviepedia.viewmodel.Season import org.videolan.resources.CONTENT_EPISODE import org.videolan.resources.CONTENT_RESUME import org.videolan.resources.interfaces.IMediaContentResolver import org.videolan.resources.util.getFromMl class MediaScrapingTvshowProvider(private val context: Context) { @MainThread fun getFirstResumableEpisode(medialibrary: Medialibrary, mediaMetadataEpisodes: List<MediaMetadataWithImages>): MediaMetadataWithImages? { val seasons = ArrayList<Season>() mediaMetadataEpisodes.forEach { episode -> val season = seasons.firstOrNull { it.seasonNumber == episode.metadata.season } ?: Season(episode.metadata.season ?: 0).also { seasons.add(it) } season.episodes.add(episode) } return seasons.asSequence().mapNotNull { season -> season.episodes.sortBy { episode -> episode.metadata.episode } season.episodes.asSequence().firstOrNull { episode -> if (episode.media == null) episode.media = episode.metadata.mlId?.let { medialibrary.getMedia(it) } episode.media?.let { media -> media.seen < 1 } == true } }.firstOrNull() } suspend fun getAllSeasons(tvShow: MediaMetadataWithImages): List<Season> { val mediaMetadataRepository = MediaMetadataRepository.getInstance(context) val mediaMetadataEpisodes = mediaMetadataRepository.getTvShowEpisodes(tvShow.metadata.moviepediaId) val seasons = ArrayList<Season>() mediaMetadataEpisodes.forEach { episode -> val existingSeason = seasons.firstOrNull { it.seasonNumber == episode.metadata.season } val season = if (existingSeason == null) { val newSeason = Season(episode.metadata.season ?: 0) seasons.add(newSeason) newSeason } else existingSeason season.episodes.add(episode) } seasons.forEach { season -> season.episodes.sortBy { episode -> episode.metadata.episode } //retrieve ML media season.episodes.forEach { episode -> if (episode.media == null) { episode.metadata.mlId?.let { val fromMl = context.getFromMl { getMedia(it) } episode.media = fromMl } } } } return seasons } fun getShowIdForEpisode(id: String): String? { val mediaMetadataRepository = MediaMetadataRepository.getInstance(context) mediaMetadataRepository.getMediaById(id)?.metadata?.showId?.let { return mediaMetadataRepository.getTvshow(it)?.metadata?.moviepediaId } return null } suspend fun getResumeMediasById(id: String): List<MediaWrapper> { val mediaMetadataRepository = MediaMetadataRepository.getInstance(context) val mediasToPlay = ArrayList<MediaWrapper>() mediaMetadataRepository.getTvshow(id)?.let { tvShow -> val seasons = getAllSeasons(tvShow) return getResumeMedias(seasons) } return mediasToPlay } fun getResumeMedias(seasons: List<Season>?): List<MediaWrapper> { val mediasToPlay = ArrayList<MediaWrapper>() var firstResumableFound = false seasons?.forEach { it.episodes.forEach { episode -> episode.media?.let { media -> if (media.seen < 1 || firstResumableFound) { firstResumableFound = true mediasToPlay.add(media) } } } } return mediasToPlay } suspend fun getAllEpisodesForShow(id: String): List<MediaMetadataWithImages> { val mediaMetadataRepository = MediaMetadataRepository.getInstance(context) return mediaMetadataRepository.getTvshow(id)?.let { tvShow -> getAllSeasons(tvShow).flatMap { it.episodes } } ?: emptyList() } fun getAllMedias(seasons: List<Season>?): List<MediaWrapper> { return seasons?.flatMap { it.episodes }?.mapNotNull { it.media } ?: emptyList() } companion object { fun getProviders() = listOf(ResumeResolver, TvShowResolver) } } private object ResumeResolver : IMediaContentResolver { override val prefix = CONTENT_RESUME override suspend fun getList(context: Context, id: String): Pair<List<MediaWrapper>, Int>? { val provider = MediaScrapingTvshowProvider(context) return withContext(Dispatchers.IO) { Pair(provider.getResumeMediasById(id.substringAfter(prefix)), 0) } } } private object TvShowResolver : IMediaContentResolver { override val prefix = CONTENT_EPISODE override suspend fun getList(context: Context, id: String): Pair<List<MediaWrapper>, Int>? { val provider = MediaScrapingTvshowProvider(context) val moviepediaId = id.substringAfter(prefix) return withContext(Dispatchers.IO) { provider.getShowIdForEpisode(moviepediaId)?.let { provider.getAllEpisodesForShow(it) } }?.let { Pair(it.mapNotNull { episode -> episode.media }, it.indexOfFirst { it.metadata.moviepediaId == moviepediaId }) } } }
gpl-2.0
363114a66c681ae207e1ee0ec0ebb4cb
42.608974
142
0.650595
5.225038
false
false
false
false
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/migration/impl/DataMigration.kt
1
7790
package cc.aoeiuv020.panovel.migration.impl import android.content.Context import android.net.Uri import cc.aoeiuv020.gson.toBean import cc.aoeiuv020.jsonpath.get import cc.aoeiuv020.jsonpath.jsonPath import cc.aoeiuv020.panovel.data.DataManager import cc.aoeiuv020.panovel.data.entity.NovelMinimal import cc.aoeiuv020.panovel.data.entity.NovelWithProgress import cc.aoeiuv020.panovel.migration.Migration import cc.aoeiuv020.panovel.settings.* import cc.aoeiuv020.panovel.util.VersionName import cc.aoeiuv020.string.divide import com.google.gson.JsonArray import com.google.gson.JsonElement import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.error import java.io.File /** * Created by AoEiuV020 on 2018.05.30-19:21:52. */ class DataMigration : Migration(), AnkoLogger { override val to: VersionName = VersionName("2.2.2") override val message: String = "书架列表,书单列表,设置," override fun migrate(ctx: Context, from: VersionName) { import(ctx.getExternalFilesDir(null)) import(ctx.filesDir) } private fun import(base: File) { importBookshelf(base) importBookList(base) importSettings(base) } private fun importMargins(base: File, margins: Margins) { val map = mapOf<String, (JsonElement) -> Unit>( "enabled" to { value -> margins.enabled = value.asBoolean }, "left" to { value -> margins.left = value.asInt }, "top" to { value -> margins.top = value.asInt }, "right" to { value -> margins.right = value.asInt }, "bottom" to { value -> margins.bottom = value.asInt } ) base.listFiles()?.forEach { file -> val setter = map[file.name] ?: return@forEach file.readText().toBean<JsonElement>().let(setter) } } private fun importSettings(base: File) { val list = base.resolve("Settings").listFiles() ?: return val map = mapOf<String, (JsonElement) -> Unit>( "backPressOutOfFullScreen" to { value -> ReaderSettings.backPressOutOfFullScreen = value.asBoolean }, "adEnabled" to { value -> AdSettings.adEnabled = value.asBoolean }, "BookSmallLayout" to { value -> ListSettings.largeView = !value.asBoolean }, "fullScreenClickNextPage" to { value -> ReaderSettings.fullScreenClickNextPage = value.asBoolean }, "volumeKeyScroll" to { value -> ReaderSettings.volumeKeyScroll = value.asBoolean }, "reportCrash" to { value -> OtherSettings.reportCrash = value.asBoolean }, "bookshelfRedDotColor" to { value -> ListSettings.dotColor = value.asInt }, "bookshelfRedDotSize" to { value -> ListSettings.dotSize = value.asFloat }, "fullScreenDelay" to { value -> ReaderSettings.fullScreenDelay = value.asInt }, "textSize" to { value -> ReaderSettings.textSize = value.asInt }, "lineSpacing" to { value -> ReaderSettings.lineSpacing = value.asInt }, "paragraphSpacing" to { value -> ReaderSettings.paragraphSpacing = value.asInt }, "messageSize" to { value -> ReaderSettings.messageSize = value.asInt }, "autoRefreshInterval" to { value -> ReaderSettings.autoRefreshInterval = value.asInt }, "textColor" to { value -> ReaderSettings.textColor = value.asInt }, "backgroundColor" to { value -> ReaderSettings.backgroundColor = value.asInt }, "historyCount" to { value -> GeneralSettings.historyCount = value.asInt }, "downloadThreadCount" to { value -> DownloadSettings.downloadThreadsLimit = value.asInt }, "chapterColorDefault" to { value -> OtherSettings.chapterColorDefault = value.asInt }, "chapterColorCached" to { value -> OtherSettings.chapterColorCached = value.asInt }, "chapterColorReadAt" to { value -> OtherSettings.chapterColorReadAt = value.asInt }, "animationSpeed" to { value -> ReaderSettings.animationSpeed = value.asFloat }, "centerPercent" to { value -> ReaderSettings.centerPercent = value.asFloat }, "dateFormat" to { value -> ReaderSettings.dateFormat = value.asString }, "animationMode" to { value -> ReaderSettings.animationMode = value.asString.toBean() }, "shareExpiration" to { value -> OtherSettings.shareExpiration = value.asString.toBean() } ) val marginsMap = mapOf( "contentMargins" to ReaderSettings.contentMargins, "paginationMargins" to ReaderSettings.paginationMargins, "bookNameMargins" to ReaderSettings.bookNameMargins, "chapterNameMargins" to ReaderSettings.chapterNameMargins, "timeMargins" to ReaderSettings.timeMargins, "batteryMargins" to ReaderSettings.batteryMargins ) list.forEach { file -> val setter = map[file.name] ?: return@forEach if (file.isFile) { file.readText().toBean<JsonElement>().let(setter) } else if (file.isDirectory) { val margins = marginsMap[file.name] ?: return@forEach importMargins(file, margins) } } list.forEach { file -> // 导入字体和背景图, when (file.name) { "font" -> ReaderSettings.font = Uri.fromFile(file) "backgroundImage" -> ReaderSettings.backgroundImage = Uri.fromFile(file) } } } // 旧版requester有两种情况,一个对象包含extra或者竖线|分隔类名和extra, private fun getDetailFromRequester(requester: JsonElement): String = if (requester.isJsonObject) { requester.jsonPath.get("$.extra") } else { requester.asString.divide('|').second } private fun importBookshelf(base: File) { val progress = base.resolve("Progress") val list = base.resolve("Bookshelf").listFiles()?.map { val novel = it.readText().jsonPath.run { NovelWithProgress(site = get("$.site"), author = get("$.author"), name = get("$.name"), detail = getDetailFromRequester(get("$.requester"))) } try { progress.resolve(novel.run { "$name.$author.$site" }) .takeIf { it.exists() } ?.readText()?.jsonPath?.run { novel.readAtChapterIndex = get("chapter") novel.readAtTextIndex = get("text") } } catch (e: Exception) { error("旧版书架中的小说<${novel.run { "$name.$author.$site" }}>阅读进度读取失败,", e) // 进度次要,异常不抛出去, } novel } ?: return DataManager.importBookshelfWithProgress(list) } private fun importBookList(base: File) { base.resolve("BookList").listFiles()?.forEach { it.readText().jsonPath.run { val name = get<String>("$.name") val list = get<JsonArray>("$.list").map { it.jsonPath.run { NovelMinimal(site = get("$.site"), author = get("$.author"), name = get("$.name"), detail = getDetailFromRequester(get("$.requester"))) } } DataManager.importBookList(name, list) } } } }
gpl-3.0
790b7e6c06c7cb378badb47307c7fe99
44.778443
99
0.586342
4.768559
false
false
false
false
graphql-java/graphql-java-tools
src/main/kotlin/graphql/kickstart/tools/DictionaryTypeResolver.kt
1
1942
package graphql.kickstart.tools import graphql.TypeResolutionEnvironment import graphql.kickstart.tools.util.BiMap import graphql.kickstart.tools.util.JavaType import graphql.language.TypeDefinition import graphql.schema.GraphQLInterfaceType import graphql.schema.GraphQLObjectType import graphql.schema.GraphQLUnionType import graphql.schema.TypeResolver /** * @author Andrew Potter */ internal abstract class DictionaryTypeResolver( private val dictionary: BiMap<JavaType, TypeDefinition<*>> ) : TypeResolver { private fun <T> getTypeDefinition(clazz: Class<T>): TypeDefinition<*>? { return dictionary[clazz] ?: (if (clazz.superclass == null) null else getTypeDefinition(clazz.superclass)) ?: clazz.interfaces.mapNotNull { getTypeDefinition(it) }.firstOrNull() } override fun getType(env: TypeResolutionEnvironment): GraphQLObjectType? { val clazz = env.getObject<Any>().javaClass val name = getTypeDefinition(clazz)?.name ?: clazz.simpleName return env.schema.getObjectType(name) ?: throw TypeResolverError(getError(name)) } abstract fun getError(name: String): String } internal class InterfaceTypeResolver( dictionary: BiMap<JavaType, TypeDefinition<*>>, private val thisInterface: GraphQLInterfaceType ) : DictionaryTypeResolver( dictionary ) { override fun getError(name: String) = "Expected object type with name '$name' to implement interface '${thisInterface.name}', but it doesn't!" } internal class UnionTypeResolver( dictionary: BiMap<JavaType, TypeDefinition<*>>, private val thisUnion: GraphQLUnionType ) : DictionaryTypeResolver( dictionary ) { override fun getError(name: String) = "Expected object type with name '$name' to exist for union '${thisUnion.name}', but it doesn't!" } internal class TypeResolverError(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
mit
30f91b9a8756ffc3c4a75bd80ce0c954
37.078431
146
0.744078
4.771499
false
false
false
false
gpolitis/jitsi-videobridge
jvb/src/test/kotlin/org/jitsi/ConfigTest.kt
1
1809
/* * Copyright @ 2018 - present 8x8, 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 org.jitsi import io.kotest.core.spec.IsolationMode import io.kotest.core.spec.Spec import io.kotest.core.spec.style.ShouldSpec import org.jitsi.config.useLegacyConfig import org.jitsi.config.useNewConfig import org.jitsi.metaconfig.MetaconfigSettings /** * A helper class for testing configuration properties */ abstract class ConfigTest : ShouldSpec() { override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf override fun beforeSpec(spec: Spec) { super.beforeSpec(spec) MetaconfigSettings.cacheEnabled = false } override fun afterSpec(spec: Spec) { super.afterSpec(spec) MetaconfigSettings.cacheEnabled = true } inline fun withLegacyConfig(props: String, block: () -> Unit) { useLegacyConfig(name = "legacy-${this::class.simpleName}", props = props, block = block) } inline fun withNewConfig(config: String, block: () -> Unit) { useNewConfig("new-${this::class.simpleName}", config, false, block) } inline fun withNewConfig(config: String, loadDefaults: Boolean, block: () -> Unit) { useNewConfig("new-${this::class.simpleName}", config, loadDefaults, block) } }
apache-2.0
7f3f640cf2b1ae41a721b12f2b669452
33.132075
96
0.713654
4.236534
false
true
false
false
rcgroot/open-gpstracker-ng
studio/features/src/test/java/nl/sogeti/android/gpstracker/ng/features/graphs/GraphSpeedConverterTest.kt
1
2428
package nl.sogeti.android.gpstracker.ng.features.graphs import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.closeTo import org.junit.Before import org.junit.Test class GraphSpeedConverterTest { private lateinit var sut: GraphSpeedConverter @Before fun setUp() { sut = GraphSpeedConverter() } @Test fun roundTrip() { listOf(1F, 2F, 3F, 4F, 5F, 6F, 7F).forEach { // Act val result = sut.yValueToSpeed(sut.speedToYValue(it)) // Assert assertThat(it.toDouble(), fCloseTo(result, .0005F)) } } @Test fun slow() { // Act val result = sut.speedToYValue(MPS_FOR_5_KMP) // Assert assertThat(result.toDouble(), fCloseTo(12F, 0.1F)) } @Test fun medium() { // Act val result = sut.speedToYValue(MPS_FOR_10_KMP) // Assert assertThat(result.toDouble(), fCloseTo(6F, 0.1F)) } @Test fun fast() { // Act val result = sut.speedToYValue(MPS_FOR_20_KMP) // Assert assertThat(result.toDouble(), fCloseTo(3F, 0.1F)) } @Test fun speedHalfTheSpeed() { val reference = sut.speedToYValue(MPS_FOR_10_KMP) // e.g. 6 minute per kilometer // Act val higherY = sut.speedToYValue(MPS_FOR_5_KMP) // e.g. 12 minute per kilometer // Assert assertThat(reference * 2, `is`(higherY)) } @Test fun speedDoubleTheSpeed() { val reference = sut.speedToYValue(MPS_FOR_10_KMP) // e.g. 6 minute per kilometer // Act val lowerY = sut.speedToYValue(MPS_FOR_20_KMP) // e.g. 3 minute per kilometer // Assert assertThat(reference / 2, `is`(lowerY)) } @Test fun infiniteSpeed() { val nearZero = sut.speedToYValue(Float.MAX_VALUE) // Assert assertThat(nearZero.toDouble(), closeTo(.0, 0.00000005)) } @Test fun noSpeed() { val nearZero = sut.speedToYValue(0F) // Assert assertThat(nearZero.toDouble(), closeTo(.0, 0.00000005)) } private fun fCloseTo(result: Float, epsilon: Float) = closeTo(result.toDouble(), epsilon.toDouble()) companion object { const val MPS_FOR_20_KMP = 20F / 3.6F const val MPS_FOR_10_KMP = 10F / 3.6F const val MPS_FOR_5_KMP = 5F / 3.6F } }
gpl-3.0
f35d340bf354200de4c21b7d5379fb87
25.681319
104
0.59061
3.70687
false
true
false
false
soywiz/korge
@old/korge-spriter/src/commonMain/kotlin/com/soywiz/korge/ext/spriter/com/brashmonkey/spriter/Player.kt
1
37791
package com.soywiz.korge.ext.spriter.com.brashmonkey.spriter import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Entity.CharacterMap import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Entity.ObjectInfo import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Mainline.Key.BoneRef import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Mainline.Key.ObjectRef import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Player.PlayerListener import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Timeline.Key.Bone import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Timeline.Key.Object import kotlin.math.sign /** * A Player instance is responsible for updating an [Animation] properly. * With the [.update] method an instance of this class will increase its current time * and update the current set animation ([.setAnimation]). * A Player can be positioned with [.setPivot], scaled with [.setScale], * flipped with [.flip] and rotated [.setAngle]. * A Player has various methods for runtime object manipulation such as [.setBone] or [.setObject]. * Events like the ending of an animation can be observed with the [PlayerListener] interface. * Character maps can be changed on the fly, just by assigning a character maps to [.characterMaps], setting it to `null` will remove the current character map. * @author Trixt0r */ @Suppress("unused", "MemberVisibilityCanBePrivate", "PropertyName") open class Player /** * Creates a [Player] instance with the given entity. * @param entity the entity this player will animate */ (entity: Entity) { var _entity: Entity = Entity.DUMMY var _animation: Animation = Animation.DUMMY var _time: Int = 0 var speed: Int = 15 var tweenedKeys: Array<Timeline.Key> = emptyArray() var unmappedTweenedKeys: Array<Timeline.Key> = emptyArray() private var tempTweenedKeys: Array<Timeline.Key>? = null private var tempUnmappedTweenedKeys: Array<Timeline.Key>? = null private val listeners: MutableList<PlayerListener> = ArrayList() val attachments: List<Attachment> = ArrayList() var root = Bone(Point(0f, 0f)) private val position = Point(0f, 0f) private val pivot = Point(0f, 0f) private val objToTimeline = HashMap<Object, Timeline.Key>() private var angle: Float = 0.toFloat() private var dirty = true var characterMaps: Array<CharacterMap> = emptyArray() private val rect: Rectangle = Rectangle(0f, 0f, 0f, 0f) val prevBBox: Box = Box() private val boneIterator: BoneIterator = BoneIterator() private val objectIterator: ObjectIterator = ObjectIterator() /** * Returns the current main line key based on the current [.time]. * @return the current main line key */ var currentKey: Mainline.Key? = null private set private var prevKey: Mainline.Key? = null var copyObjects = true init { this.setEntity(entity) } /** * Updates this player. * This means the current time gets increased by [.speed] and is applied to the current animation. */ open fun update() { for (i in listeners.indices) { listeners[i].preProcess(this) } if (dirty) this.updateRoot() this._animation.update(_time, root) this.currentKey = this._animation.currentKey if (prevKey != currentKey) { for (i in listeners.indices) { listeners[i].mainlineKeyChanged(prevKey, currentKey) } prevKey = currentKey } if (copyObjects) { tweenedKeys = tempTweenedKeys!! unmappedTweenedKeys = tempUnmappedTweenedKeys!! this.copyObjects() } else { tweenedKeys = _animation.tweenedKeys unmappedTweenedKeys = _animation.unmappedTweenedKeys } for (i in attachments.indices) { attachments[i].update() } for (i in listeners.indices) { listeners[i].postProcess(this) } this.increaseTime() } private fun copyObjects() { for (i in _animation.tweenedKeys.indices) { this.tweenedKeys[i].active = _animation.tweenedKeys[i].active this.unmappedTweenedKeys[i].active = _animation.unmappedTweenedKeys[i].active this.tweenedKeys[i].`object`().set(_animation.tweenedKeys[i].`object`()) this.unmappedTweenedKeys[i].`object`().set(_animation.unmappedTweenedKeys[i].`object`()) } } private fun increaseTime() { _time += speed if (_time > _animation.length) { _time -= _animation.length for (i in listeners.indices) { listeners[i].animationFinished(_animation) } } if (_time < 0) { for (i in listeners.indices) { listeners[i].animationFinished(_animation) } _time += _animation.length } } private fun updateRoot() { this.root._angle = angle this.root.position.set(pivot) this.root.position.rotate(angle) this.root.position.translate(position) dirty = false } /** * Returns a time line bone at the given index. * @param index the index of the bone * * * @return the bone with the given index. */ fun getBone(index: Int): Bone { return this.unmappedTweenedKeys[currentKey!!.getBoneRef(index)!!.timeline].`object`() } /** * Returns a time line object at the given index. * @param index the index of the object * * * @return the object with the given index. */ fun getObject(index: Int): Object { return this.unmappedTweenedKeys[currentKey!!.getObjectRef(index)!!.timeline].`object`() } /** * Returns the index of a time line bone with the given name. * @param name the name of the bone * * * @return the index of the bone or -1 if no bone exists with the given name */ fun getBoneIndex(name: String): Int { for (ref in currentKey!!.boneRefs) if (_animation.getTimeline(ref.timeline).name == name) return ref.id return -1 } /** * Returns a time line bone with the given name. * @param name the name of the bone * * * @return the bone with the given name * * * @throws IndexOutOfBoundsException if no bone exists with the given name * * * @throws NullPointerException if no bone exists with the given name */ fun getBone(name: String): Bone { return this.unmappedTweenedKeys[_animation.getTimeline(name)!!.id].`object`() } /** * Returns a bone reference for the given time line bone. * @param bone the time line bone * * * @return the bone reference for the given bone * * * @throws NullPointerException if no reference for the given bone was found */ fun getBoneRef(bone: Bone): BoneRef? { return this.currentKey!!.getBoneRefTimeline(this.objToTimeline[bone]!!.id) } /** * Returns the index of a time line object with the given name. * @param name the name of the object * * * @return the index of the object or -1 if no object exists with the given name */ fun getObjectIndex(name: String): Int { for (ref in currentKey!!.objectRefs) if (_animation.getTimeline(ref.timeline).name == name) return ref.id return -1 } /** * Returns a time line object with the given name. * @param name the name of the object * * * @return the object with the given name * * * @throws IndexOutOfBoundsException if no object exists with the given name * * * @throws NullPointerException if no object exists with the given name */ fun getObject(name: String): Object { return this.unmappedTweenedKeys[_animation.getTimeline(name)!!.id].`object`() } /** * Returns a object reference for the given time line bone. * @param object the time line object * * * @return the object reference for the given bone * * * @throws NullPointerException if no reference for the given object was found */ fun getObjectRef(`object`: Object): ObjectRef? { return this.currentKey!!.getObjectRefTimeline(this.objToTimeline[`object`]!!.id) } /** * Returns the name for the given bone or object. * @param boneOrObject the bone or object * * * @return the name of the bone or object * * * @throws NullPointerException if no name for the given bone or object was found */ fun getNameFor(boneOrObject: Bone): String { return this._animation.getTimeline(objToTimeline[boneOrObject]!!.id).name } /** * Returns the object info for the given bone or object. * @param boneOrObject the bone or object * * * @return the object info of the bone or object * * * @throws NullPointerException if no object info for the given bone or object was found */ fun getObjectInfoFor(boneOrObject: Bone): ObjectInfo { return this._animation.getTimeline(objToTimeline[boneOrObject]!!.id).objectInfo } /** * Returns the time line key for the given bone or object * @param boneOrObject the bone or object * * * @return the time line key of the bone or object, or null if no time line key was found */ fun getKeyFor(boneOrObject: Bone): Timeline.Key { return objToTimeline[boneOrObject]!! } /** * Calculates and returns a [Box] for the given bone or object. * @param boneOrObject the bone or object to calculate the bounding box for * * * @return the box for the given bone or object * * * @throws NullPointerException if no object info for the given bone or object exists */ fun getBox(boneOrObject: Bone): Box { val info = getObjectInfoFor(boneOrObject) this.prevBBox.calcFor(boneOrObject, info) return this.prevBBox } /** * Returns whether the given point at x,y lies inside the box of the given bone or object. * @param boneOrObject the bone or object * * * @param x the x value of the point * * * @param y the y value of the point * * * @return `true` if x,y lies inside the box of the given bone or object * * * @throws NullPointerException if no object info for the given bone or object exists */ fun collidesFor(boneOrObject: Bone, x: Float, y: Float): Boolean { val info = getObjectInfoFor(boneOrObject) this.prevBBox.calcFor(boneOrObject, info) return this.prevBBox.collides(boneOrObject, info, x, y) } /** * Returns whether the given point lies inside the box of the given bone or object. * @param boneOrObject the bone or object * * * @param point the point * * * @return `true` if the point lies inside the box of the given bone or object * * * @throws NullPointerException if no object info for the given bone or object exists */ fun collidesFor(boneOrObject: Bone, point: Point): Boolean { return this.collidesFor(boneOrObject, point.x, point.y) } /** * Returns whether the given area collides with the box of the given bone or object. * @param boneOrObject the bone or object * * * @param area the rectangular area * * * @return `true` if the area collides with the bone or object */ fun collidesFor(boneOrObject: Bone, area: Rectangle): Boolean { val info = getObjectInfoFor(boneOrObject) this.prevBBox.calcFor(boneOrObject, info) return this.prevBBox.isInside(area) } /** * Sets the given values of the bone with the given name. * @param name the name of the bone * * * @param x the new x value of the bone * * * @param y the new y value of the bone * * * @param angle the new angle of the bone * * * @param scaleX the new scale in x direction of the bone * * * @param scaleY the new scale in y direction of the bone * * * @throws SpriterException if no bone exists of the given name */ fun setBone(name: String, x: Float, y: Float, angle: Float, scaleX: Float, scaleY: Float) { val index = getBoneIndex(name) if (index == -1) throw SpriterException("No bone found of name \"$name\"") val ref = currentKey!!.getBoneRef(index) val bone = getBone(index) bone[x, y, angle, scaleX, scaleY, 0f] = 0f unmapObjects(ref) } /** * Sets the given values of the bone with the given name. * @param name the name of the bone * * * @param position the new position of the bone * * * @param angle the new angle of the bone * * * @param scale the new scale of the bone * * * @throws SpriterException if no bone exists of the given name */ fun setBone(name: String, position: Point, angle: Float, scale: Point) { this.setBone(name, position.x, position.y, angle, scale.x, scale.y) } /** * Sets the given values of the bone with the given name. * @param name the name of the bone * * * @param x the new x value of the bone * * * @param y the new y value of the bone * * * @param angle the new angle of the bone * * * @throws SpriterException if no bone exists of the given name */ fun setBone(name: String, x: Float, y: Float, angle: Float) { val b = getBone(name) setBone(name, x, y, angle, b.scale.x, b.scale.y) } /** * Sets the given values of the bone with the given name. * @param name the name of the bone * * * @param position the new position of the bone * * * @param angle the new angle of the bone * * * @throws SpriterException if no bone exists of the given name */ fun setBone(name: String, position: Point, angle: Float) { val b = getBone(name) setBone(name, position.x, position.y, angle, b.scale.x, b.scale.y) } /** * Sets the position of the bone with the given name. * @param name the name of the bone * * * @param x the new x value of the bone * * * @param y the new y value of the bone * * * @throws SpriterException if no bone exists of the given name */ fun setBone(name: String, x: Float, y: Float) { val b = getBone(name) setBone(name, x, y, b._angle) } /** * Sets the position of the bone with the given name. * @param name the name of the bone * * * @param position the new position of the bone * * * @throws SpriterException if no bone exists of the given name */ fun setBone(name: String, position: Point) { setBone(name, position.x, position.y) } /** * Sets the angle of the bone with the given name * @param name the name of the bone * * * @param angle the new angle of the bone * * * @throws SpriterException if no bone exists of the given name */ fun setBone(name: String, angle: Float) { val b = getBone(name) setBone(name, b.position.x, b.position.y, angle) } /** * Sets the values of the bone with the given name to the values of the given bone * @param name the name of the bone * * * @param bone the bone with the new values * * * @throws SpriterException if no bone exists of the given name */ fun setBone(name: String, bone: Bone) { setBone(name, bone.position, bone._angle, bone.scale) } /** * Sets the given values of the object with the given name. * @param name the name of the object * * * @param x the new position in x direction of the object * * * @param y the new position in y direction of the object * * * @param angle the new angle of the object * * * @param scaleX the new scale in x direction of the object * * * @param scaleY the new scale in y direction of the object * * * @param pivotX the new pivot in x direction of the object * * * @param pivotY the new pivot in y direction of the object * * * @param alpha the new alpha value of the object * * * @param folder the new folder index of the object * * * @param file the new file index of the object * * * @throws SpriterException if no object exists of the given name */ fun setObject( name: String, x: Float, y: Float, angle: Float, scaleX: Float, scaleY: Float, pivotX: Float, pivotY: Float, alpha: Float, folder: Int, file: Int ) { val index = getObjectIndex(name) if (index == -1) throw SpriterException("No object found for name \"$name\"") val ref = currentKey!!.getObjectRef(index) val `object` = getObject(index) `object`[x, y, angle, scaleX, scaleY, pivotX, pivotY, alpha, folder] = file unmapObjects(ref) } /** * Sets the given values of the object with the given name. * @param name the name of the object * * * @param position the new position of the object * * * @param angle the new angle of the object * * * @param scale the new scale of the object * * * @param pivot the new pivot of the object * * * @param alpha the new alpha value of the object * * * @param ref the new file reference of the object * * * @throws SpriterException if no object exists of the given name */ fun setObject( name: String, position: Point, angle: Float, scale: Point, pivot: Point, alpha: Float, ref: FileReference ) { this.setObject( name, position.x, position.y, angle, scale.x, scale.y, pivot.x, pivot.y, alpha, ref.folder, ref.file ) } /** * Sets the given values of the object with the given name. * @param name the name of the object * * * @param x the new position in x direction of the object * * * @param y the new position in y direction of the object * * * @param angle the new angle of the object * * * @param scaleX the new scale in x direction of the object * * * @param scaleY the new scale in y direction of the object * * * @throws SpriterException if no object exists of the given name */ fun setObject(name: String, x: Float, y: Float, angle: Float, scaleX: Float, scaleY: Float) { val b = getObject(name) setObject(name, x, y, angle, scaleX, scaleY, b.pivot.x, b.pivot.y, b.alpha, b.ref.folder, b.ref.file) } /** * Sets the given values of the object with the given name. * @param name the name of the object * * * @param x the new position in x direction of the object * * * @param y the new position in y direction of the object * * * @param angle the new angle of the object * * * @throws SpriterException if no object exists of the given name */ fun setObject(name: String, x: Float, y: Float, angle: Float) { val b = getObject(name) setObject(name, x, y, angle, b.scale.x, b.scale.y) } /** * Sets the given values of the object with the given name. * @param name the name of the object * * * @param position the new position of the object * * * @param angle the new angle of the object * * * @throws SpriterException if no object exists of the given name */ fun setObject(name: String, position: Point, angle: Float) { val b = getObject(name) setObject(name, position.x, position.y, angle, b.scale.x, b.scale.y) } /** * Sets the position of the object with the given name. * @param name the name of the object * * * @param x the new position in x direction of the object * * * @param y the new position in y direction of the object * * * @throws SpriterException if no object exists of the given name */ fun setObject(name: String, x: Float, y: Float) { val b = getObject(name) setObject(name, x, y, b._angle) } /** * Sets the position of the object with the given name. * @param name the name of the object * * * @param position the new position of the object * * * @throws SpriterException if no object exists of the given name */ fun setObject(name: String, position: Point) { setObject(name, position.x, position.y) } /** * Sets the position of the object with the given name. * @param name the name of the object * * * @param angle the new angle of the object * * * @throws SpriterException if no object exists of the given name */ fun setObject(name: String, angle: Float) { val b = getObject(name) setObject(name, b.position.x, b.position.y, angle) } /** * Sets the position of the object with the given name. * @param name the name of the object * * * @param alpha the new alpha value of the object * * * @param folder the new folder index of the object * * * @param file the new file index of the object * * * @throws SpriterException if no object exists of the given name */ fun setObject(name: String, alpha: Float, folder: Int, file: Int) { val b = getObject(name) setObject( name, b.position.x, b.position.y, b._angle, b.scale.x, b.scale.y, b.pivot.x, b.pivot.y, alpha, folder, file ) } /** * Sets the values of the object with the given name to the values of the given object. * @param name the name of the object * * * @param object the object with the new values * * * @throws SpriterException if no object exists of the given name */ fun setObject(name: String, `object`: Object) { setObject( name, `object`.position, `object`._angle, `object`.scale, `object`.pivot, `object`.alpha, `object`.ref ) } /** * Maps all object from the parent's coordinate system to the global coordinate system. * @param base the root bone to start at. Set it to `null` to traverse the whole bone hierarchy. */ fun unmapObjects(base: BoneRef?) { val start = if (base == null) -1 else base.id - 1 for (i in start + 1 until currentKey!!.boneRefs.size) { val ref = currentKey!!.getBoneRef(i)!! if (ref.parent !== base && base !== null) continue val parent = if (ref.parent == null) this.root else this.unmappedTweenedKeys[ref.parent.timeline].`object`() unmappedTweenedKeys[ref.timeline].`object`().set(tweenedKeys[ref.timeline].`object`()) unmappedTweenedKeys[ref.timeline].`object`().unmap(parent) unmapObjects(ref) } for (ref in currentKey!!.objectRefs) { if (ref.parent !== base && base !== null) continue val parent = if (ref.parent == null) this.root else this.unmappedTweenedKeys[ref.parent.timeline].`object`() unmappedTweenedKeys[ref.timeline].`object`().set(tweenedKeys[ref.timeline].`object`()) unmappedTweenedKeys[ref.timeline].`object`().unmap(parent) } } /** * Sets the entity for this player instance. * The animation will be switched to the first one of the new entity. * @param entity the new entity * * * @throws SpriterException if the entity is `null` */ open fun setEntity(entity: Entity?) { if (entity == null) throw SpriterException("entity can not be null!") this._entity = entity val maxAnims = entity.animationWithMostTimelines.timelines() tweenedKeys = Array(maxAnims) { Timeline.Key.DUMMY } unmappedTweenedKeys = Array(maxAnims) { Timeline.Key.DUMMY } for (i in 0 until maxAnims) { val key = Timeline.Key(i) val keyU = Timeline.Key(i) key.setObject(Object(Point(0f, 0f))) keyU.setObject(Object(Point(0f, 0f))) tweenedKeys[i] = key unmappedTweenedKeys[i] = keyU this.objToTimeline[keyU.`object`()] = keyU } this.tempTweenedKeys = tweenedKeys this.tempUnmappedTweenedKeys = unmappedTweenedKeys this.setAnimation(entity.getAnimation(0)) } /** * Returns the current set entity. * @return the current entity */ fun getEntity(): Entity { return this._entity } /** * Sets the animation of this player. * @param animation the new animation * * * @throws SpriterException if the animation is `null` or the current animation is not a member of the current set entity */ open fun setAnimation(animation: Animation?) { val prevAnim = this._animation if (animation === this._animation) return if (animation == null) throw SpriterException("animation can not be null!") if (!this._entity.containsAnimation(animation) && animation.id != -1) throw SpriterException("animation has to be in the same entity as the current set one!") if (animation !== this._animation) _time = 0 this._animation = animation val tempTime = this._time this._time = 0 this.update() this._time = tempTime for (i in listeners.indices) { listeners[i].animationChanged(prevAnim, animation) } } /** * Sets the animation of this player to the one with the given name. * @param name the name of the animation * * * @throws SpriterException if no animation exists with the given name */ fun setAnimation(name: String) { this.setAnimation(_entity.getAnimation(name)) } /** * Sets the animation of this player to the one with the given index. * @param index the index of the animation * * * @throws IndexOutOfBoundsException if the index is out of range */ fun setAnimation(index: Int) { this.setAnimation(_entity.getAnimation(index)) } /** * Returns the current set animation. * @return the current animation */ fun getAnimation(): Animation { return this._animation } /** * Returns a bounding box for this player. * The bounding box is calculated for all bones and object starting from the given root. * @param root the starting root. Set it to null to calculate the bounding box for the whole player * * * @return the bounding box */ fun getBoundingRectangle(root: BoneRef?): Rectangle { val boneRoot = if (root == null) this.root else this.unmappedTweenedKeys[root.timeline].`object`() this.rect.set(boneRoot.position.x, boneRoot.position.y, boneRoot.position.x, boneRoot.position.y) this.calcBoundingRectangle(root) this.rect.calculateSize() return this.rect } /** * Returns a bounding box for this player. * The bounding box is calculated for all bones and object starting from the given root. * @param root the starting root. Set it to null to calculate the bounding box for the whole player * * * @return the bounding box */ fun getBoudingRectangle(root: Bone?): Rectangle { return this.getBoundingRectangle(if (root == null) null else getBoneRef(root)) } private fun calcBoundingRectangle(root: BoneRef?) { for (ref in currentKey!!.boneRefs) { if (ref.parent !== root && root !== null) continue val bone = this.unmappedTweenedKeys[ref.timeline].`object`() this.prevBBox.calcFor(bone, _animation.getTimeline(ref.timeline).objectInfo) Rectangle.setBiggerRectangle(rect, this.prevBBox.boundingRect, rect) this.calcBoundingRectangle(ref) } for (ref in currentKey!!.objectRefs) { if (ref.parent !== root) continue val bone = this.unmappedTweenedKeys[ref.timeline].`object`() this.prevBBox.calcFor(bone, _animation.getTimeline(ref.timeline).objectInfo) Rectangle.setBiggerRectangle(rect, this.prevBBox.boundingRect, rect) } } /** * Returns the current time. * The player will make sure that the current time is always between 0 and [Animation.length]. * @return the current time */ fun getTime(): Int { return _time } /** * Sets the time for the current time. * The player will make sure that the new time will not exceed the time bounds of the current animation. * @param time the new time * * * @return this player to enable chained operations */ fun setTime(time: Int): Player { this._time = time val prevSpeed = this.speed this.speed = 0 this.increaseTime() this.speed = prevSpeed return this } /** * Sets the scale of this player to the given one. * Only uniform scaling is supported. * @param scale the new scale. 1f means 100% scale. * * * @return this player to enable chained operations */ fun setScale(scale: Float): Player { this.root.scale.set(scale * flippedX(), scale * flippedY()) return this } /** * Scales this player based on the current set scale. * @param scale the scaling factor. 1f means no scale. * * * @return this player to enable chained operations */ fun scale(scale: Float): Player { this.root.scale.scale(scale, scale) return this } /** * Returns the current scale. * @return the current scale */ val scale: Float get() = root.scale.x /** * Flips this player around the x and y axis. * @param x whether to flip the player around the x axis * * * @param y whether to flip the player around the y axis * * * @return this player to enable chained operations */ fun flip(x: Boolean, y: Boolean): Player { if (x) this.flipX() if (y) this.flipY() return this } /** * Flips the player around the x axis. * @return this player to enable chained operations */ fun flipX(): Player { this.root.scale.x = this.root.scale.x * -1 return this } /** * Flips the player around the y axis. * @return this player to enable chained operations */ fun flipY(): Player { this.root.scale.y = this.root.scale.y * -1 return this } /** * Returns whether this player is flipped around the x axis. * @return 1 if this player is not flipped, -1 if it is flipped */ fun flippedX(): Int { return sign(root.scale.x).toInt() } /** * Returns whether this player is flipped around the y axis. * @return 1 if this player is not flipped, -1 if it is flipped */ fun flippedY(): Int { return sign(root.scale.y).toInt() } /** * Sets the position of this player to the given coordinates. * @param x the new position in x direction * * * @param y the new position in y direction * * * @return this player to enable chained operations */ fun setPosition(x: Float, y: Float): Player { this.dirty = true this.position.set(x, y) return this } /** * Sets the position of the player to the given one. * @param position the new position * * * @return this player to enable chained operations */ fun setPosition(position: Point): Player { return this.setPosition(position.x, position.y) } /** * Adds the given coordinates to the current position of this player. * @param x the amount in x direction * * * @param y the amount in y direction * * * @return this player to enable chained operations */ fun translatePosition(x: Float, y: Float): Player { return this.setPosition(position.x + x, position.y + y) } /** * Adds the given amount to the current position of this player. * @param amount the amount to add * * * @return this player to enable chained operations */ fun translate(amount: Point): Player { return this.translatePosition(amount.x, amount.y) } /** * Returns the current position in x direction. * @return the current position in x direction */ val x: Float get() = position.x /** * Returns the current position in y direction. * @return the current position in y direction */ val y: Float get() = position.y /** * Sets the angle of this player to the given angle. * @param angle the angle in degrees * * * @return this player to enable chained operations */ fun setAngle(angle: Float): Player { this.dirty = true this.angle = angle return this } /** * Rotates this player by the given angle. * @param angle the angle in degrees * * * @return this player to enable chained operations */ fun rotate(angle: Float): Player { return this.setAngle(angle + this.angle) } /** * Returns the current set angle. * @return the current angle */ fun getAngle(): Float { return this.angle } /** * Sets the pivot, i.e. origin, of this player. * A pivot at (0,0) means that the origin of the played animation will have the same one as in Spriter. * @param x the new pivot in x direction * * * @param y the new pivot in y direction * * * @return this player to enable chained operations */ fun setPivot(x: Float, y: Float): Player { this.dirty = true this.pivot.set(x, y) return this } /** * Sets the pivot, i.e. origin, of this player. * A pivot at (0,0) means that the origin of the played animation will have the same one as in Spriter. * @param pivot the new pivot * * * @return this player to enable chained operations */ fun setPivot(pivot: Point): Player { return this.setPivot(pivot.x, pivot.y) } /** * Translates the current set pivot position by the given amount. * @param x the amount in x direction * * * @param y the amount in y direction * * * @return this player to enable chained operations */ fun translatePivot(x: Float, y: Float): Player { return this.setPivot(pivot.x + x, pivot.y + y) } /** * Adds the given amount to the current set pivot position. * @param amount the amount to add * * * @return this player to enable chained operations */ fun translatePivot(amount: Point): Player { return this.translatePivot(amount.x, amount.y) } /** * Returns the current set pivot in x direction. * @return the pivot in x direction */ val pivotX: Float get() = pivot.x /** * Returns the current set pivot in y direction. * @return the pivot in y direction */ val pivotY: Float get() = pivot.y /** * Appends a listener to the listeners list of this player. * @param listener the listener to add */ fun addListener(listener: PlayerListener) { this.listeners.add(listener) } /** * Removes a listener from the listeners list of this player. * @param listener the listener to remove */ fun removeListener(listener: PlayerListener) { this.listeners.remove(listener) } /** * Returns an iterator to iterate over all time line bones in the current animation. * @return the bone iterator */ fun boneIterator(): Iterator<Bone> { return this.boneIterator(this.currentKey!!.boneRefs[0]) } /** * Returns an iterator to iterate over all time line bones in the current animation starting at a given root. * @param start the bone reference to start at * * * @return the bone iterator */ fun boneIterator(start: BoneRef): Iterator<Bone> { this.boneIterator.index = start.id return this.boneIterator } /** * Returns an iterator to iterate over all time line objects in the current animation. * @return the object iterator */ fun objectIterator(): Iterator<Object> { return this.objectIterator(this.currentKey!!.objectRefs[0]) } /** * Returns an iterator to iterate over all time line objects in the current animation starting at a given root. * @param start the object reference to start at * * * @return the object iterator */ fun objectIterator(start: ObjectRef): Iterator<Object> { this.objectIterator.index = start.id return this.objectIterator } /** * An iterator to iterate over all time line objects in the current animation. * @author Trixt0r */ inner class ObjectIterator : MutableIterator<Object> { var index = 0 override fun hasNext(): Boolean { return index < currentKey!!.objectRefs.size } override fun next(): Object { return unmappedTweenedKeys[currentKey!!.objectRefs[index++].timeline].`object`() } override fun remove() { throw SpriterException("remove() is not supported by this iterator!") } } /** * An iterator to iterate over all time line bones in the current animation. * @author Trixt0r */ inner class BoneIterator : MutableIterator<Bone> { var index = 0 override fun hasNext(): Boolean { return index < currentKey!!.boneRefs.size } override fun next(): Bone { return unmappedTweenedKeys[currentKey!!.boneRefs[index++].timeline].`object`() } override fun remove() { throw SpriterException("remove() is not supported by this iterator!") } } /** * A listener to listen for specific events which can occur during the runtime of a [Player] instance. * @author Trixt0r */ interface PlayerListener { /** * Gets called if the current animation has reached it's end or it's beginning (depends on the current set [Player.speed]). * @param animation the animation which finished. */ fun animationFinished(animation: Animation) /** * Gets called if the animation of the player gets changed. * If [Player.setAnimation] gets called and the new animation is the same as the previous one, this method will not be called. * @param oldAnim the old animation * * * @param newAnim the new animation */ fun animationChanged(oldAnim: Animation, newAnim: Animation) /** * Gets called before a player updates the current animation. * @param player the player which is calling this method. */ fun preProcess(player: Player) /** * Gets called after a player updated the current animation. * @param player the player which is calling this method. */ fun postProcess(player: Player) /** * Gets called if the mainline key gets changed. * If [Player.speed] is big enough it can happen that mainline keys between the previous and the new mainline key will be ignored. * @param prevKey the previous mainline key * * * @param newKey the new mainline key */ fun mainlineKeyChanged(prevKey: Mainline.Key?, newKey: Mainline.Key?) } /** * An attachment is an abstract object which can be attached to a [Player] object. * An attachment extends a [Bone] which means that [Bone.position], [Bone.scale] and [Bone._angle] can be set to change the relative position to its [Attachment.parent] * The [Player] object will make sure that the attachment will be transformed relative to its [Attachment.parent]. * @author Trixt0r */ abstract class Attachment /** * Creates a new attachment * @param parent the parent of this attachment */ (parent: Bone) : Bone() { /** * Returns the current set parent. * @return the parent */ /** * Sets the parent of this attachment. * * * @throws SpriterException if parent is `null` */ var parent: Bone? = parent set(parent) { if (parent == null) throw SpriterException("The parent cannot be null!") field = parent } private val positionTemp: Point = Point() private val scaleTemp: Point = Point() private var angleTemp: Float = 0.toFloat() fun update() { //Save relative positions this.positionTemp.set(super.position) this.scaleTemp.set(super.scale) this.angleTemp = super._angle super.unmap(this.parent!!) this.setPosition(super.position.x, super.position.y) this.setScale(super.scale.x, super.scale.y) this.setAngle(super._angle) //Load realtive positions super.position.set(this.positionTemp) super.scale.set(this.scaleTemp) super._angle = this.angleTemp } /** * Sets the position to the given coordinates. * @param x the x coordinate * * * @param y the y coordinate */ protected abstract fun setPosition(x: Float, y: Float) /** * Sets the scale to the given scale. * @param xscale the scale in x direction * * * @param yscale the scale in y direction */ protected abstract fun setScale(xscale: Float, yscale: Float) /** * Sets the angle to the given one. * @param angle the angle in degrees */ protected abstract fun setAngle(angle: Float) } }
apache-2.0
b81dfb61676577ac41a5dd3281be3da3
28.114792
169
0.687624
3.636897
false
false
false
false
samtstern/quickstart-android
storage/app/src/main/java/com/google/firebase/quickstart/firebasestorage/kotlin/MyDownloadService.kt
1
5050
package com.google.firebase.quickstart.firebasestorage.kotlin import android.app.Service import android.content.Intent import android.content.IntentFilter import android.os.IBinder import android.util.Log import androidx.localbroadcastmanager.content.LocalBroadcastManager import com.google.firebase.ktx.Firebase import com.google.firebase.quickstart.firebasestorage.R import com.google.firebase.storage.StorageReference import com.google.firebase.storage.ktx.storage class MyDownloadService : MyBaseTaskService() { private lateinit var storageRef: StorageReference override fun onCreate() { super.onCreate() // Initialize Storage storageRef = Firebase.storage.reference } override fun onBind(intent: Intent): IBinder? { return null } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { Log.d(TAG, "onStartCommand:$intent:$startId") if (ACTION_DOWNLOAD == intent.action) { // Get the path to download from the intent val downloadPath = intent.getStringExtra(EXTRA_DOWNLOAD_PATH)!! downloadFromPath(downloadPath) } return Service.START_REDELIVER_INTENT } private fun downloadFromPath(downloadPath: String) { Log.d(TAG, "downloadFromPath:$downloadPath") // Mark task started taskStarted() showProgressNotification(getString(R.string.progress_downloading), 0, 0) // Download and get total bytes storageRef.child(downloadPath).getStream { taskSnapshot, inputStream -> val totalBytes = taskSnapshot.totalByteCount var bytesDownloaded: Long = 0 val buffer = ByteArray(1024) var size: Int = inputStream.read(buffer) while (size != -1) { bytesDownloaded += size.toLong() showProgressNotification(getString(R.string.progress_downloading), bytesDownloaded, totalBytes) size = inputStream.read(buffer) } // Close the stream at the end of the Task inputStream.close() }.addOnSuccessListener { taskSnapshot -> Log.d(TAG, "download:SUCCESS") // Send success broadcast with number of bytes downloaded broadcastDownloadFinished(downloadPath, taskSnapshot.totalByteCount) showDownloadFinishedNotification(downloadPath, taskSnapshot.totalByteCount.toInt()) // Mark task completed taskCompleted() }.addOnFailureListener { exception -> Log.w(TAG, "download:FAILURE", exception) // Send failure broadcast broadcastDownloadFinished(downloadPath, -1) showDownloadFinishedNotification(downloadPath, -1) // Mark task completed taskCompleted() } } /** * Broadcast finished download (success or failure). * @return true if a running receiver received the broadcast. */ private fun broadcastDownloadFinished(downloadPath: String, bytesDownloaded: Long): Boolean { val success = bytesDownloaded != -1L val action = if (success) DOWNLOAD_COMPLETED else DOWNLOAD_ERROR val broadcast = Intent(action) .putExtra(EXTRA_DOWNLOAD_PATH, downloadPath) .putExtra(EXTRA_BYTES_DOWNLOADED, bytesDownloaded) return LocalBroadcastManager.getInstance(applicationContext) .sendBroadcast(broadcast) } /** * Show a notification for a finished download. */ private fun showDownloadFinishedNotification(downloadPath: String, bytesDownloaded: Int) { // Hide the progress notification dismissProgressNotification() // Make Intent to MainActivity val intent = Intent(this, MainActivity::class.java) .putExtra(EXTRA_DOWNLOAD_PATH, downloadPath) .putExtra(EXTRA_BYTES_DOWNLOADED, bytesDownloaded) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) val success = bytesDownloaded != -1 val caption = if (success) { getString(R.string.download_success) } else { getString(R.string.download_failure) } showFinishedNotification(caption, intent, true) } companion object { private const val TAG = "Storage#DownloadService" /** Actions */ const val ACTION_DOWNLOAD = "action_download" const val DOWNLOAD_COMPLETED = "download_completed" const val DOWNLOAD_ERROR = "download_error" /** Extras */ const val EXTRA_DOWNLOAD_PATH = "extra_download_path" const val EXTRA_BYTES_DOWNLOADED = "extra_bytes_downloaded" val intentFilter: IntentFilter get() { val filter = IntentFilter() filter.addAction(DOWNLOAD_COMPLETED) filter.addAction(DOWNLOAD_ERROR) return filter } } }
apache-2.0
7277d11aa1cf4ead24882d4b2e9a7f57
33.353741
97
0.644554
5.233161
false
false
false
false
dna2github/NodeBase
android/app/src/main/kotlin/net/seven/nodebase/MainActivity.kt
1
10597
package net.seven.nodebase import androidx.annotation.NonNull import android.content.Context import android.content.ContextWrapper import android.content.Intent import android.content.IntentFilter import android.os.BatteryManager import android.os.Build.VERSION import android.os.Build.VERSION_CODES import android.os.Handler import java.io.File import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.EventChannel class MainActivity: FlutterActivity() { private val BATTERY_CHANNEL = "net.seven.nodebase/battery" private val APP_CHANNEL = "net.seven.nodebase/app" private val NODEBASE_CHANNEL = "net.seven.nodebase/nodebase" private val EVENT_CHANNEL = "net.seven.nodebase/event" private val eventHandler = NodeBaseEventHandler() private val NodeBaseServiceMap = mutableMapOf<String, NodeMonitor>() override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) // Note: MethodCallHandler is invoked on the main thread. MethodChannel(flutterEngine.dartExecutor.binaryMessenger, BATTERY_CHANNEL).setMethodCallHandler { call, result -> if (call.method == "getBatteryLevel") { val batteryLevel = getBatteryLevel() if (batteryLevel != -1) { result.success(batteryLevel) } else { result.error("UNAVAILABLE", "Battery level not available.", null) } } else { result.notImplemented() } } MethodChannel(flutterEngine.dartExecutor.binaryMessenger, APP_CHANNEL).setMethodCallHandler { call, result -> if (call.method == "RequestExternalStoragePermission") { result.success(requestExternalStoragePermission()) } else if (call.method == "KeepScreenOn") { var sw: Boolean? = call.argument("sw") if (sw == true) { keepScreenOn(true) } else { keepScreenOn(false) } result.success(0) } else if (call.method == "FetchExecutable") { var src: String? = call.argument("url") var dst: String? = call.argument("target") if (src == null || dst == null) { result.error("INVALID_PARAMS", "invalid parameter.", null) } else { val file = File(dst) val dir = file.getParentFile() if (!dir.exists()) { Storage.makeDirectory(dir.getAbsolutePath()) } result.success(fetchAndMarkExecutable(src, dst)) } } else if (call.method == "FetchApp") { var src: String? = call.argument("url") var dst: String? = call.argument("target") if (src == null || dst == null) { result.error("INVALID_PARAMS", "invalid parameter.", null) } else { val dir = File(dst) if (!dir.exists()) { Storage.makeDirectory(dir.getAbsolutePath()) } result.success(fetchApp(src, dst)) } } else if (call.method == "FetchWifiIpv4") { result.success(fetchWifiIpv4()) } else { result.notImplemented() } } MethodChannel(flutterEngine.dartExecutor.binaryMessenger, NODEBASE_CHANNEL).setMethodCallHandler { call, result -> if (call.method == "GetStatus") { var app: String? = call.argument("app") app?.let { result.success(getAppStatus(app)) } } else if (call.method == "Start") { var app: String? = call.argument("app") var cmd: String? = call.argument("cmd") app?.let { cmd?.let { result.success(startApp(app, cmd)) } } } else if (call.method == "Stop") { var app: String? = call.argument("app") app?.let { result.success(stopApp(app)) } } else if (call.method == "Unpack") { var app: String? = call.argument("app") var zipfile: String? = call.argument("zipfile") var path: String? = call.argument("path") app?.let { zipfile?.let { path?.let { val dir = File(path) if (!dir.exists()) { Storage.makeDirectory(dir.getAbsolutePath()) } result.success(fetchAndUnzip(zipfile, path)) } } } } else if (call.method == "Pack") { var app: String? = call.argument("app") var zipfile: String? = call.argument("zipfile") var path: String? = call.argument("path") app?.let { zipfile?.let { path?.let { result.success(fetchAndZip(path, zipfile)) } } } } else if (call.method == "Browser") { var url: String? = call.argument("url") url?.let { result.success(openInExternalBrowser(url)) } } else { result.notImplemented() } } EventChannel(flutterEngine.dartExecutor.binaryMessenger, EVENT_CHANNEL).setStreamHandler(eventHandler) } private fun openInExternalBrowser(url: String): Boolean { External.openBrowser(this, url) return true } private fun fetchAndZip(target_dir: String, zipfile: String): Boolean { // TODO: wrap a thread instead of running on main thread return Storage.zip(target_dir, zipfile) } private fun fetchAndUnzip(zipfile: String, target_dir: String): Boolean { // TODO: wrap a thread instead of running on main thread Storage.unzip(zipfile, target_dir) return true } private fun getAppStatus(app: String): String { val m = NodeBaseServiceMap.get(app) if (m == null) return "n/a" if (m.isRunning) return "started" if (m.isDead) return "stopped" return "unknown" } private fun startApp(app: String, cmd: String): Boolean { val m = NodeBaseServiceMap.get(app) if (m != null) { if (!m.isDead) return true } val cmdarr = StringUtils.parseArgv(cmd) val exec = NodeMonitor(app, cmdarr) val handler = Handler() val evt = object: NodeMonitorEvent { override fun before(cmd: Array<String>) {} override fun started(cmd: Array<String>, process: Process) { handler.post(object: Runnable { override fun run() { eventHandler.send(app + "\nstart") } }); } override fun error(cmd: Array<String>, process: Process) {} override fun after(cmd: Array<String>, process: Process) { handler.post(object: Runnable { override fun run() { eventHandler.send(app + "\nstop") } }); } } exec.setEvent(evt) NodeBaseServiceMap[app] = exec exec.start() return true } private fun stopApp(app: String): Boolean { val m = NodeBaseServiceMap.get(app) if (m == null) return true if (m.isDead) return true m.stopService() NodeBaseServiceMap.remove(app) return true } private fun fetchWifiIpv4(): String { return Network.getWifiIpv4(this) } private fun _markExecutable(dst: String): Boolean { val isZip = dst.endsWith(".zip") if (isZip) { val f = File(dst) val t = f.getParentFile().getAbsolutePath() android.util.Log.i("NodeBase", String.format("extracting %s -> %s ...", dst, t)) for (one in Storage.unzip(dst, t)) { android.util.Log.i("NodeBase", String.format(" %s", one.getAbsolutePath())) Storage.executablize(one.getAbsolutePath()) } return Storage.unlink(dst) } else { return Storage.executablize(dst) } } private fun fetchAndMarkExecutable(src: String, dst: String): Int { if (src == "") return -1 if (src.startsWith("file://")) { Permission.request(this) var final_src = src final_src = final_src.substring("file://".length) // Add Alarm to align with Download() // XXX: but how about we move Alarm out of Download() and use call back to do alarm? if (!Storage.copy(final_src, dst)) { Alarm.showToast(this, "Copy failed: cannot copy origin") return -2 } if (!_markExecutable(dst)) { Alarm.showToast(this, "Copy failed: cannot set binary executable") return -3 } Alarm.showToast(this, "Copy successful") return 0 } else { // download val postAction = object : Runnable { override fun run() { _markExecutable(dst) } } Download(this, postAction).act("fetch", src, dst) } return 0 } private fun _unpackApp(dst: String): Boolean { // dst is a zip file path val f = File(dst) val t = f.getParentFile().getAbsolutePath() android.util.Log.i("NodeBase", String.format("extracting %s -> %s ...", dst, t)) for (one in Storage.unzip(dst, t)) { android.util.Log.i("NodeBase", String.format(" %s", one.getAbsolutePath())) } return Storage.unlink(dst) } private fun fetchApp(src: String, dst: String): Int { if (src == "") return -1 if (!src.endsWith(".zip")) return -1 Storage.makeDirectory(dst) val src_name = File(src).getName() var dst_zip = dst + "/" + src_name if (src.startsWith("file://")) { Permission.request(this) var final_src = src final_src = final_src.substring("file://".length) // Add Alarm to align with Download() // XXX: but how about we move Alarm out of Download() and use call back to do alarm? if (!Storage.copy(final_src, dst_zip)) { Alarm.showToast(this, "Copy failed: cannot copy origin") return -2 } if (!_unpackApp(dst_zip)) { Alarm.showToast(this, "Copy failed: cannot set binary executable") return -3 } Alarm.showToast(this, "Copy successful") return 0 } else { // download val postAction = object : Runnable { override fun run() { _unpackApp(dst_zip) } } Download(this, postAction).act("fetch", src, dst_zip) } return 0 } private fun requestExternalStoragePermission(): Int { Permission.request(this) return 0 } private fun keepScreenOn(sw: Boolean) { Permission.keepScreen(this, sw) } private fun getBatteryLevel(): Int { val batteryLevel: Int if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) } else { val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) } return batteryLevel } }
apache-2.0
0441d28894c676116060321cdfef3367
33.630719
132
0.627442
4.091506
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/loading/TLoadingManager.kt
1
4082
package com.tamsiree.rxui.view.loading import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.annotation.SuppressLint import android.graphics.* import android.view.animation.LinearInterpolator internal class TLoadingManager(private val loaderView: TLoadingView) : ValueAnimator.AnimatorUpdateListener { private var rectPaint: Paint? = null private var linearGradient: LinearGradient? = null private var progress = 0f private var valueAnimator: ValueAnimator? = null private var widthWeight = TLoadingProfile.MAX_WEIGHT private var heightWeight = TLoadingProfile.MAX_WEIGHT private var useGradient = TLoadingProfile.USE_GRADIENT_DEFAULT private var corners = TLoadingProfile.CORNER_DEFAULT private fun init() { rectPaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG) loaderView.setRectColor(rectPaint!!) setValueAnimator(0.5f, 1f, ObjectAnimator.INFINITE) } @SuppressLint("DrawAllocation") @JvmOverloads fun onDraw(canvas: Canvas, left_pad: Float = 0f, top_pad: Float = 0f, right_pad: Float = 0f, bottom_pad: Float = 0f) { val margin_height = canvas.height * (1 - heightWeight) / 2 rectPaint!!.alpha = (progress * MAX_COLOR_CONSTANT_VALUE).toInt() if (useGradient) { prepareGradient(canvas.width * widthWeight) } canvas.drawRoundRect(RectF(0 + left_pad, margin_height + top_pad, canvas.width * widthWeight - right_pad, canvas.height - margin_height - bottom_pad), corners.toFloat(), corners.toFloat(), rectPaint!!) } fun onSizeChanged() { linearGradient = null startLoading() } private fun prepareGradient(width: Float) { if (linearGradient == null) { linearGradient = LinearGradient(0f, 0f, width, 0f, rectPaint!!.color, TLoadingProfile.COLOR_DEFAULT_GRADIENT, Shader.TileMode.MIRROR) } rectPaint!!.shader = linearGradient } fun startLoading() { if (valueAnimator != null && !loaderView.valueSet()) { valueAnimator!!.cancel() init() valueAnimator!!.start() } } fun setHeightWeight(heightWeight: Float) { this.heightWeight = validateWeight(heightWeight) } fun setWidthWeight(widthWeight: Float) { this.widthWeight = validateWeight(widthWeight) } fun setUseGradient(useGradient: Boolean) { this.useGradient = useGradient } fun setCorners(corners: Int) { this.corners = corners } private fun validateWeight(weight: Float): Float { if (weight > TLoadingProfile.MAX_WEIGHT) return TLoadingProfile.MAX_WEIGHT return if (weight < TLoadingProfile.MIN_WEIGHT) TLoadingProfile.MIN_WEIGHT else weight } fun stopLoading() { if (valueAnimator != null) { valueAnimator!!.cancel() setValueAnimator(progress, 0f, 0) valueAnimator!!.start() } } private fun setValueAnimator(begin: Float, end: Float, repeatCount: Int) { valueAnimator = ValueAnimator.ofFloat(begin, end) valueAnimator?.repeatCount = repeatCount valueAnimator?.duration = ANIMATION_CYCLE_DURATION.toLong() valueAnimator?.repeatMode = ValueAnimator.REVERSE valueAnimator?.interpolator = LinearInterpolator() valueAnimator?.addUpdateListener(this) } override fun onAnimationUpdate(valueAnimator: ValueAnimator) { progress = valueAnimator.animatedValue as Float loaderView.invalidate() } fun removeAnimatorUpdateListener() { if (valueAnimator != null) { valueAnimator!!.removeUpdateListener(this) valueAnimator!!.cancel() } progress = 0f } companion object { private const val MAX_COLOR_CONSTANT_VALUE = 255 private const val ANIMATION_CYCLE_DURATION = 750 //milis } init { init() } }
apache-2.0
b1817ccd9d3a571281b77bff6c1cb276
33.025
122
0.652376
4.836493
false
false
false
false
stripe/stripe-android
paymentsheet-example/src/main/java/com/stripe/android/paymentsheet/example/Settings.kt
1
1604
package com.stripe.android.paymentsheet.example import android.content.Context import android.content.pm.PackageManager /** * Class that provides global app settings. */ class Settings(context: Context) { private val appContext = context.applicationContext private val backendMetadata = getMetadata(METADATA_KEY_BACKEND_URL_KEY) private val googlePlacesMetadata = getMetadata(METADATA_KEY_GOOGLE_PLACES_API_KEY) val playgroundBackendUrl: String get() { return backendMetadata ?: BASE_URL } val googlePlacesApiKey: String? get() { return googlePlacesMetadata } private fun getMetadata(key: String): String? { return appContext.packageManager .getApplicationInfo(appContext.packageName, PackageManager.GET_META_DATA) .metaData .getString(key) .takeIf { it?.isNotBlank() == true } } internal companion object { /** * The base URL of the test backend, implementing a `/checkout` endpoint as defined by * [CheckoutBackendApi]. * * Note: only necessary if not configured via `gradle.properties`. */ private const val BASE_URL = "https://stripe-mobile-payment-sheet-test-playground-v6.glitch.me/" private const val METADATA_KEY_BACKEND_URL_KEY = "com.stripe.android.paymentsheet.example.metadata.backend_url" private const val METADATA_KEY_GOOGLE_PLACES_API_KEY = "com.stripe.android.paymentsheet.example.metadata.google_places_api_key" } }
mit
1a2f85c5bc9ce72b6cde13e8a268c2c7
33.12766
94
0.660224
4.595989
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/notifications/service/delegates/ExpoSchedulingDelegate.kt
2
4377
package abi43_0_0.expo.modules.notifications.service.delegates import android.app.AlarmManager import android.content.Context import android.util.Log import androidx.core.app.AlarmManagerCompat import expo.modules.notifications.notifications.interfaces.SchedulableNotificationTrigger import expo.modules.notifications.notifications.model.Notification import expo.modules.notifications.notifications.model.NotificationRequest import abi43_0_0.expo.modules.notifications.service.NotificationsService import abi43_0_0.expo.modules.notifications.service.interfaces.SchedulingDelegate import java.io.IOException import java.io.InvalidClassException class ExpoSchedulingDelegate(protected val context: Context) : SchedulingDelegate { protected val store = SharedPreferencesNotificationsStore(context) protected val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager override fun setupScheduledNotifications() { store.allNotificationRequests.forEach { try { scheduleNotification(it) } catch (e: Exception) { Log.w("expo-notifications", "Notification ${it.identifier} could not have been scheduled: ${e.message}") e.printStackTrace() } } } override fun getAllScheduledNotifications(): Collection<NotificationRequest> = store.allNotificationRequests override fun getScheduledNotification(identifier: String): NotificationRequest? = try { store.getNotificationRequest(identifier) } catch (e: IOException) { null } catch (e: ClassNotFoundException) { null } catch (e: NullPointerException) { null } override fun scheduleNotification(request: NotificationRequest) { // If the trigger is empty, handle receive immediately and return. if (request.trigger == null) { NotificationsService.receive(context, Notification(request)) return } if (request.trigger !is SchedulableNotificationTrigger) { throw IllegalArgumentException("Notification request \"${request.identifier}\" does not have a schedulable trigger (it's ${request.trigger}). Refusing to schedule.") } (request.trigger as SchedulableNotificationTrigger).nextTriggerDate().let { nextTriggerDate -> if (nextTriggerDate == null) { Log.d("expo-notifications", "Notification request \"${request.identifier}\" will not trigger in the future, removing.") NotificationsService.removeScheduledNotification(context, request.identifier) } else { store.saveNotificationRequest(request) AlarmManagerCompat.setExactAndAllowWhileIdle( alarmManager, AlarmManager.RTC_WAKEUP, nextTriggerDate.time, NotificationsService.createNotificationTrigger(context, request.identifier) ) } } } override fun triggerNotification(identifier: String) { try { val notificationRequest: NotificationRequest = store.getNotificationRequest(identifier)!! NotificationsService.receive(context, Notification(notificationRequest)) NotificationsService.schedule(context, notificationRequest) } catch (e: ClassNotFoundException) { Log.e("expo-notifications", "An exception occurred while triggering notification " + identifier + ", removing. " + e.message) e.printStackTrace() NotificationsService.removeScheduledNotification(context, identifier) } catch (e: InvalidClassException) { Log.e("expo-notifications", "An exception occurred while triggering notification " + identifier + ", removing. " + e.message) e.printStackTrace() NotificationsService.removeScheduledNotification(context, identifier) } catch (e: NullPointerException) { Log.e("expo-notifications", "An exception occurred while triggering notification " + identifier + ", removing. " + e.message) e.printStackTrace() NotificationsService.removeScheduledNotification(context, identifier) } } override fun removeScheduledNotifications(identifiers: Collection<String>) { identifiers.forEach { alarmManager.cancel(NotificationsService.createNotificationTrigger(context, it)) store.removeNotificationRequest(it) } } override fun removeAllScheduledNotifications() { store.removeAllNotificationRequests().forEach { alarmManager.cancel(NotificationsService.createNotificationTrigger(context, it)) } } }
bsd-3-clause
ca2d713494834447fb72243d21f31be3
41.911765
171
0.752799
5.363971
false
false
false
false
Madzi/owide
src/main/kotlin/owide/ui/FileSystem.kt
1
1980
package owide.ui import org.w3c.dom.HTMLAnchorElement import org.w3c.dom.HTMLElement import org.w3c.dom.HTMLInputElement import org.w3c.files.File import org.w3c.files.FileReader import org.w3c.files.get import kotlin.browser.document external class ArrayBuffer object FileSystem { private val body = document.querySelector("body") as HTMLElement private val inputer = initInputer() private val outputer = initOutputer() private var callback: ((fileName: String, content: ArrayBuffer) -> Unit)? = null private fun initInputer(): HTMLInputElement { val fin = document.createElement("input") as HTMLInputElement fin.apply { type = "file" style.display = "none" } body.appendChild(fin) fin.onchange = { event -> val file: File? = inputer.files!![0] as File if (file != null) { val reader = FileReader() reader.onload = { ev -> if (callback != null) { callback?.invoke(file.name, ev.target.asDynamic().result) } } reader.readAsArrayBuffer(file) } } return fin } private fun initOutputer(): HTMLAnchorElement { val fout = document.createElement("a") as HTMLAnchorElement fout.apply { style.display = "none" } body.appendChild(fout) return fout } fun load(callback: (fileName: String, context: ArrayBuffer) -> Unit) { FileSystem.callback = callback inputer.click() } fun save(fileName: String, context: ArrayBuffer) { outputer.href = "data:text/plain;base64,+++"; outputer.download = fileName outputer.click() } fun extension(fileName: String): String { val parts = fileName.split(".") return if (parts.size > 1) parts.last() else "" } }
apache-2.0
d800a16d7ac09c9a8b33e39b103200d6
28.132353
84
0.579798
4.351648
false
false
false
false
petropavel13/2photo-android
TwoPhoto/app/src/main/java/com/github/petropavel13/twophoto/PostEntriesActivity.kt
1
9156
package com.github.petropavel13.twophoto import android.app.WallpaperManager import android.graphics.Bitmap import android.os.Bundle import android.os.Handler import android.os.Looper import android.provider.MediaStore import android.support.v4.view.ViewPager import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import com.facebook.common.executors.CallerThreadExecutor import com.facebook.common.references.CloseableReference import com.facebook.datasource.DataSource import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber import com.facebook.imagepipeline.image.CloseableImage import com.facebook.imagepipeline.request.ImageRequest import com.github.petropavel13.twophoto.adapters.PostEntriesPagerAdapter import com.github.petropavel13.twophoto.model.Post import com.splunk.mint.Mint import java.util.HashSet public class PostEntriesActivity : AppCompatActivity() { companion object { val POST_ENTRIES_KEY ="post_entries" val SELECTED_ENTRY_INDEX = "selected_entry_index" private val FULLSCREEN_KEY = "fullscreen" } private var viewPager: ViewPager? = null private var toolbar: Toolbar? = null private val wallpapersInProgress = HashSet<Int>() private val downloadsInProgress = HashSet<Int>() private var postId = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_post_entries) val ctx = this val adapter = PostEntriesPagerAdapter(ctx, getIntent().getParcelableArrayListExtra<Post.Entry>(POST_ENTRIES_KEY)) val selectedItemIndex = getIntent().getIntExtra(SELECTED_ENTRY_INDEX, 0) postId = getIntent().getIntExtra(PostDetailActivity.POST_ID_KEY, 0) with(findViewById(R.id.post_entries_view_pager) as ViewPager) { viewPager = this adapter.onEntryTapListener = object: View.OnClickListener { override fun onClick(view: View) { with(getSupportActionBar()) { if(isShowing()) { hide() adapter.showEntriesDescription = false } else { show() adapter.showEntriesDescription = true } } } } if (savedInstanceState?.getBoolean(FULLSCREEN_KEY, false) ?: false) { getSupportActionBar().hide() adapter.showEntriesDescription = false } setAdapter(adapter) setCurrentItem(selectedItemIndex) setOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { // } override fun onPageSelected(position: Int) { toolbar?.setTitle("${position + 1} из ${getAdapter().getCount()}") } override fun onPageScrollStateChanged(state: Int) { // } }) } with(findViewById(R.id.post_entries_toolbar) as Toolbar) { toolbar = this // inflateMenu(R.menu.menu_post_entries) // for some reason "standalone" toolbar menu doesn't work setTitle("${selectedItemIndex + 1} из ${adapter.getCount()}") // so fallback to actionbar flavor setSupportActionBar(this) } getSupportActionBar().setDisplayHomeAsUpEnabled(true) } override fun onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) outState?.putBoolean(FULLSCREEN_KEY, getSupportActionBar().isShowing()) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { getMenuInflater().inflate(R.menu.menu_post_entries, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if(item?.getItemId() == android.R.id.home) { finish() return super.onOptionsItemSelected(item) } val ctx = this val pager = viewPager!! val adapter = pager.getAdapter() as PostEntriesPagerAdapter val currentItemIndex = pager.getCurrentItem() val entry = adapter.getViewForAtPosition(currentItemIndex)?.entry if(entry != null) { when(item?.getItemId()) { R.id.menu_post_entries_action_set_wallpaper -> { if(wallpapersInProgress.contains(currentItemIndex) == false) { wallpapersInProgress.add(currentItemIndex) Fresco.getImagePipeline() .fetchDecodedImage(ImageRequest.fromUri(entry.big_img_url), null) .subscribe(object: BaseBitmapDataSubscriber() { override fun onNewResultImpl(bitmap: Bitmap?) { var completed = false try { WallpaperManager.getInstance(ctx).setBitmap(bitmap) completed = true } catch(e: Exception) { Mint.logException(e) } Handler(Looper.getMainLooper()).post { if(completed) { Toast.makeText(ctx, R.string.post_entries_action_set_wallpaper_complete, Toast.LENGTH_LONG).show() } else { Toast.makeText(ctx, R.string.post_entries_action_set_wallpaper_failed, Toast.LENGTH_LONG).show() } } wallpapersInProgress.remove(currentItemIndex) } override fun onFailureImpl(dataSource: DataSource<CloseableReference<CloseableImage>>?) { Handler(Looper.getMainLooper()).post { Toast.makeText(ctx, R.string.post_entries_action_set_wallpaper_failed, Toast.LENGTH_LONG).show() } wallpapersInProgress.remove(currentItemIndex) } }, CallerThreadExecutor.getInstance()) } } R.id.menu_post_entries_action_download_picture -> { if(downloadsInProgress.contains(currentItemIndex) == false) { downloadsInProgress.add(currentItemIndex) Fresco.getImagePipeline() .fetchDecodedImage(ImageRequest.fromUri(entry.big_img_url), null) .subscribe(object: BaseBitmapDataSubscriber() { override fun onNewResultImpl(bitmap: Bitmap?) { val completed = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "2photo-$postId-${entry.id}", entry.description) != null Handler(Looper.getMainLooper()).post { if(completed) { Toast.makeText(ctx, R.string.post_entries_action_download_picture_complete, Toast.LENGTH_LONG).show() } else { Toast.makeText(ctx, R.string.post_entries_action_download_picture_failed, Toast.LENGTH_LONG).show() } } downloadsInProgress.remove(currentItemIndex) } override fun onFailureImpl(dataSource: DataSource<CloseableReference<CloseableImage>>?) { Handler(Looper.getMainLooper()).post { Toast.makeText(ctx, R.string.post_entries_action_download_picture_failed, Toast.LENGTH_LONG).show() } downloadsInProgress.remove(currentItemIndex) } }, CallerThreadExecutor.getInstance()) } } } } return super.onOptionsItemSelected(item) } }
mit
c3ab341b38fb8088f64de146198ac64e
40.6
178
0.533654
6.036939
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyBeyondBoundsModifier.kt
3
6979
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.lazy import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.lazy.LazyListBeyondBoundsInfo.Interval import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.layout.BeyondBoundsLayout import androidx.compose.ui.layout.BeyondBoundsLayout.BeyondBoundsScope import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Above import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.After import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Before import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Below import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Left import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Right import androidx.compose.ui.layout.ModifierLocalBeyondBoundsLayout import androidx.compose.ui.modifier.ModifierLocalProvider import androidx.compose.ui.modifier.ProvidableModifierLocal import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.LayoutDirection.Ltr import androidx.compose.ui.unit.LayoutDirection.Rtl /** * This modifier is used to measure and place additional items when the lazyList receives a * request to layout items beyond the visible bounds. */ @Suppress("ComposableModifierFactory") @Composable internal fun Modifier.lazyListBeyondBoundsModifier( state: LazyListState, beyondBoundsInfo: LazyListBeyondBoundsInfo, reverseLayout: Boolean, orientation: Orientation ): Modifier { val layoutDirection = LocalLayoutDirection.current return this then remember( state, beyondBoundsInfo, reverseLayout, layoutDirection, orientation ) { LazyListBeyondBoundsModifierLocal( state, beyondBoundsInfo, reverseLayout, layoutDirection, orientation ) } } private class LazyListBeyondBoundsModifierLocal( private val state: LazyListState, private val beyondBoundsInfo: LazyListBeyondBoundsInfo, private val reverseLayout: Boolean, private val layoutDirection: LayoutDirection, private val orientation: Orientation ) : ModifierLocalProvider<BeyondBoundsLayout?>, BeyondBoundsLayout { override val key: ProvidableModifierLocal<BeyondBoundsLayout?> get() = ModifierLocalBeyondBoundsLayout override val value: BeyondBoundsLayout get() = this override fun <T> layout( direction: BeyondBoundsLayout.LayoutDirection, block: BeyondBoundsScope.() -> T? ): T? { // We use a new interval each time because this function is re-entrant. var interval = beyondBoundsInfo.addInterval( state.firstVisibleItemIndex, state.layoutInfo.visibleItemsInfo.last().index ) var found: T? = null while (found == null && interval.hasMoreContent(direction)) { // Add one extra beyond bounds item. interval = addNextInterval(interval, direction).also { beyondBoundsInfo.removeInterval(interval) } state.remeasurement?.forceRemeasure() // When we invoke this block, the beyond bounds items are present. found = block.invoke( object : BeyondBoundsScope { override val hasMoreContent: Boolean get() = interval.hasMoreContent(direction) } ) } // Dispose the items that are beyond the visible bounds. beyondBoundsInfo.removeInterval(interval) state.remeasurement?.forceRemeasure() return found } private fun addNextInterval( currentInterval: Interval, direction: BeyondBoundsLayout.LayoutDirection ): Interval { var start = currentInterval.start var end = currentInterval.end when (direction) { Before -> start-- After -> end++ Above -> if (reverseLayout) end++ else start-- Below -> if (reverseLayout) start-- else end++ Left -> when (layoutDirection) { Ltr -> if (reverseLayout) end++ else start-- Rtl -> if (reverseLayout) start-- else end++ } Right -> when (layoutDirection) { Ltr -> if (reverseLayout) start-- else end++ Rtl -> if (reverseLayout) end++ else start-- } else -> unsupportedDirection() } return beyondBoundsInfo.addInterval(start, end) } private fun Interval.hasMoreContent(direction: BeyondBoundsLayout.LayoutDirection): Boolean { fun hasMoreItemsBefore() = start > 0 fun hasMoreItemsAfter() = end < state.layoutInfo.totalItemsCount - 1 if (direction.isOppositeToOrientation()) return false return when (direction) { Before -> hasMoreItemsBefore() After -> hasMoreItemsAfter() Above -> if (reverseLayout) hasMoreItemsAfter() else hasMoreItemsBefore() Below -> if (reverseLayout) hasMoreItemsBefore() else hasMoreItemsAfter() Left -> when (layoutDirection) { Ltr -> if (reverseLayout) hasMoreItemsAfter() else hasMoreItemsBefore() Rtl -> if (reverseLayout) hasMoreItemsBefore() else hasMoreItemsAfter() } Right -> when (layoutDirection) { Ltr -> if (reverseLayout) hasMoreItemsBefore() else hasMoreItemsAfter() Rtl -> if (reverseLayout) hasMoreItemsAfter() else hasMoreItemsBefore() } else -> unsupportedDirection() } } private fun BeyondBoundsLayout.LayoutDirection.isOppositeToOrientation(): Boolean { return when (this) { Above, Below -> orientation == Orientation.Horizontal Left, Right -> orientation == Orientation.Vertical Before, After -> false else -> unsupportedDirection() } } } private fun unsupportedDirection(): Nothing = error( "Lazy list does not support beyond bounds layout for the specified direction" )
apache-2.0
abb6e7fee2b2266a00f8f502a36ba0dd
39.34104
97
0.684912
5.456607
false
false
false
false
androidx/androidx
compose/animation/animation-core/samples/src/main/java/androidx/compose/animation/core/samples/AnimatedValueSamples.kt
3
5110
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.animation.core.samples import androidx.annotation.Sampled import androidx.compose.animation.core.AnimationVector2D import androidx.compose.animation.core.TwoWayConverter import androidx.compose.animation.core.animateValueAsState import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.animateIntOffsetAsState import androidx.compose.animation.core.animateOffsetAsState import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp @Sampled @Composable fun AlphaAnimationSample() { @Composable fun alphaAnimation(visible: Boolean) { // Animates to 1f or 0f based on [visible]. // This [animateState] returns a State<Float> object. The value of the State object is // being updated by animation. (This method is overloaded for different parameter types.) // Here we use the returned [State] object as a property delegate. val alpha: Float by animateFloatAsState(if (visible) 1f else 0f) // Updates the alpha of a graphics layer with the float animation value. It is more // performant to modify alpha in a graphics layer than using `Modifier.alpha`. The former // limits the invalidation scope of alpha change to graphicsLayer's draw stage (i.e. no // recomposition would be needed). The latter triggers recomposition on each animation // frame. Box(modifier = Modifier.graphicsLayer { this.alpha = alpha }.background(Color.Red)) } } data class MySize(val width: Dp, val height: Dp) @Sampled @Composable fun ArbitraryValueTypeTransitionSample() { @Composable fun ArbitraryValueTypeAnimation(enabled: Boolean) { // Sets up the different animation target values based on the [enabled] flag. val mySize = remember(enabled) { if (enabled) { MySize(500.dp, 500.dp) } else { MySize(100.dp, 100.dp) } } // Animates a custom type value to the given target value, using a [TwoWayConverter]. The // converter tells the animation system how to convert the custom type from and to // [AnimationVector], so that it can be animated. val animSize: MySize by animateValueAsState( mySize, TwoWayConverter<MySize, AnimationVector2D>( convertToVector = { AnimationVector2D(it.width.value, it.height.value) }, convertFromVector = { MySize(it.v1.dp, it.v2.dp) } ) ) Box(Modifier.size(animSize.width, animSize.height).background(color = Color.Red)) } } @Sampled @Composable fun DpAnimationSample() { @Composable fun HeightAnimation(collapsed: Boolean) { // Animates a height of [Dp] type to different target values based on the [collapsed] flag. val height: Dp by animateDpAsState(if (collapsed) 10.dp else 20.dp) Box(Modifier.fillMaxWidth().requiredHeight(height).background(color = Color.Red)) } } @Sampled @Composable @Suppress("UNUSED_VARIABLE") fun AnimateOffsetSample() { @Composable fun OffsetAnimation(selected: Boolean) { // Animates the offset depending on the selected flag. // [animateOffsetAsState] returns a State<Offset> object. The value of the State object is // updated by the animation. Here we use that State<Offset> as a property delegate. val offset: Offset by animateOffsetAsState( if (selected) Offset(0f, 0f) else Offset(20f, 20f) ) // In this example, animateIntOffsetAsState returns a State<IntOffset>. The value of the // returned // State object is updated by the animation. val intOffset: IntOffset by animateIntOffsetAsState( if (selected) IntOffset(0, 0) else IntOffset(50, 50) ) } }
apache-2.0
c2aab272b23c1e0a087ad2a16dee500a
40.209677
99
0.717221
4.367521
false
false
false
false
BenjaminEarley/DroidBot
app/src/main/java/com/benjaminearley/droidbot/AdafruitPCA9685.kt
1
3537
package com.benjaminearley.droidbot import android.os.SystemClock import android.util.Log import com.google.android.things.pio.I2cDevice import com.google.android.things.pio.PeripheralManagerService import java.io.IOException import kotlin.experimental.and import kotlin.experimental.or class AdafruitPCA9685(I2C_DEVICE_NAME: String) { private val device: I2cDevice init { device = PeripheralManagerService().openI2cDevice(I2C_DEVICE_NAME, PCA9685_ADDRESS) setAllPwm(0, 0) device.writeRegByte(MODE2, OUTDRV.toByte()) device.writeRegByte(MODE1, ALLCALL.toByte()) SystemClock.sleep(5) //wake up (reset sleep) var mode1 = device.readRegByte(MODE1) mode1 = mode1 and SLEEP.inv().toByte() device.writeRegByte(MODE1, mode1) SystemClock.sleep(5) } fun softwareReset() { writeBuffer(byteArrayOf(0x06)) // SWRST SystemClock.sleep(5) } fun close() { try { device.close() } catch (e: IOException) { Log.w(TAG, "Unable to close I2C device", e) } } fun setPwmFreq(freqHz: Float) { var preScaleVal = 25000000f //25HZ preScaleVal /= 4096f preScaleVal /= freqHz preScaleVal -= 1.0f Log.i(TAG, "Setting PWM frequency to $freqHz Hz") Log.i(TAG, "Estimated pre-scale: $preScaleVal") val preScale = Math.floor(preScaleVal + 0.5).toByte() Log.i(TAG, "Final pre-scale: $preScale") val oldMode = device.readRegByte(MODE1) val newMode = (oldMode and 0x7F) or 0x10 //sleep device.writeRegByte(MODE1, newMode) //go to sleep device.writeRegByte(PRESCALE, preScale) device.writeRegByte(MODE1, oldMode) SystemClock.sleep(5) device.writeRegByte(MODE1, oldMode or 0x80.toByte()) } fun setPwm(channel: Byte, on: Short, off: Short) { device.writeRegByte(LED0_ON_L + 4 * channel, (on and 0xFF).toByte()) device.writeRegByte(LED0_ON_H + 4 * channel, (on.toInt() ushr 8).toByte()) device.writeRegByte(LED0_OFF_L + 4 * channel, (off and 0xFF).toByte()) device.writeRegByte(LED0_OFF_H + 4 * channel, (off.toInt() ushr 8).toByte()) } private fun setAllPwm(on: Short, off: Short) { device.writeRegByte(ALL_LED_ON_L, (on and 0xFF).toByte()) device.writeRegByte(ALL_LED_ON_H, (on.toInt() ushr 8).toByte()) device.writeRegByte(ALL_LED_OFF_L, (off and 0xFF).toByte()) device.writeRegByte(ALL_LED_OFF_H, (off.toInt() ushr 8).toByte()) } @Throws(IOException::class) private fun writeBuffer(buffer: ByteArray) { val count = device.write(buffer, buffer.size) Log.d(TAG, "Wrote $count bytes over I2C.") } companion object { const private val TAG = "PCA9685" // Registers/etc: const private val PCA9685_ADDRESS = 0x40 const private val MODE1 = 0x00 const private val MODE2 = 0x01 const private val PRESCALE = 0xFE const private val LED0_ON_L = 0x06 const private val LED0_ON_H = 0x07 const private val LED0_OFF_L = 0x08 const private val LED0_OFF_H = 0x09 const private val ALL_LED_ON_L = 0xFA const private val ALL_LED_ON_H = 0xFB const private val ALL_LED_OFF_L = 0xFC const private val ALL_LED_OFF_H = 0xFD // Bits: const private val ALLCALL = 0x01 const private val SLEEP = 0x10 const private val OUTDRV = 0x04 } }
mit
c0ef500f55a882c79500358429b85bdc
34.37
91
0.631043
3.512413
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/plugin/PluginArrowDynamicFunctionCallPsiImpl.kt
1
3386
/* * Copyright (C) 2019-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xpath.psi.impl.plugin import com.intellij.lang.ASTNode import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import com.intellij.psi.util.elementType import uk.co.reecedunn.intellij.plugin.core.psi.ASTWrapperPsiElement import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.core.sequences.reverse import uk.co.reecedunn.intellij.plugin.core.sequences.siblings import uk.co.reecedunn.intellij.plugin.xpath.ast.filterNotWhitespace import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginArrowDynamicFunctionCall import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathArgumentList import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression import uk.co.reecedunn.intellij.plugin.xpm.optree.function.XpmArrowOperation import uk.co.reecedunn.intellij.plugin.xpm.optree.item.XpmMapEntry import xqt.platform.intellij.xpath.XPathTokenProvider class PluginArrowDynamicFunctionCallPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), PluginArrowDynamicFunctionCall, XpmSyntaxValidationElement { companion object { private val POSITIONAL_ARGUMENTS = Key.create<List<XpmExpression>>("POSITIONAL_ARGUMENTS") } // region PsiElement override fun subtreeChanged() { super.subtreeChanged() clearUserData(POSITIONAL_ARGUMENTS) } // endregion // region XpmExpression override val expressionElement: XPathArgumentList get() = children().filterIsInstance<XPathArgumentList>().first() // endregion // region XpmArrowFunctionCall override val functionCallExpression: XpmExpression? get() = children().filterIsInstance<XpmExpression>().firstOrNull() override val positionalArguments: List<XpmExpression> get() = computeUserDataIfAbsent(POSITIONAL_ARGUMENTS) { val argumentList = children().filterIsInstance<XPathArgumentList>().first() argumentList.children().filterIsInstance<XpmExpression>().toList() } override val keywordArguments: List<XpmMapEntry> = listOf() override val sourceExpression: XpmExpression get() = reverse(siblings()).filterIsInstance<XpmExpression>().first() override val operation: XpmArrowOperation get() = when (conformanceElement.elementType) { XPathTokenProvider.ThinArrow -> XpmArrowOperation.Mapping else -> XpmArrowOperation.Chaining } // endregion // region XpmSyntaxValidationElement override val conformanceElement: PsiElement get() = reverse(siblings()).filterNotWhitespace().firstOrNull() ?: firstChild // endregion }
apache-2.0
85069115f8f1277a8c8a9439d8a385a5
38.835294
98
0.759008
4.722455
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/map/QuestPinLayerManager.kt
1
7478
package de.westnordost.streetcomplete.map import android.content.res.Resources import android.os.Build import androidx.collection.LongSparseArray import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import com.mapzen.tangram.MapData import com.mapzen.tangram.geometry.Point import de.westnordost.streetcomplete.data.quest.* import de.westnordost.streetcomplete.data.visiblequests.OrderedVisibleQuestTypesProvider import de.westnordost.streetcomplete.ktx.values import de.westnordost.streetcomplete.map.tangram.toLngLat import de.westnordost.streetcomplete.quests.bikeway.AddCycleway import de.westnordost.streetcomplete.util.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import java.util.* import javax.inject.Inject /** Manages the layer of quest pins in the map view: * Gets told by the QuestsMapFragment when a new area is in view and independently pulls the quests * for the bbox surrounding the area from database and holds it in memory. */ class QuestPinLayerManager @Inject constructor( private val questTypesProvider: OrderedVisibleQuestTypesProvider, private val resources: Resources, private val visibleQuestsSource: VisibleQuestsSource ): LifecycleObserver, VisibleQuestListener, CoroutineScope by CoroutineScope(Dispatchers.Default) { // draw order in which the quest types should be rendered on the map private val questTypeOrders: MutableMap<QuestType<*>, Int> = mutableMapOf() // all the (zoom 14) tiles that have been retrieved from DB into memory already private val retrievedTiles: MutableSet<Tile> = mutableSetOf() // last displayed rect of (zoom 14) tiles private var lastDisplayedRect: TilesRect? = null // quest group -> ( quest Id -> [point, ...] ) private val quests: EnumMap<QuestGroup, LongSparseArray<List<Point>>> = EnumMap(QuestGroup::class.java) lateinit var mapFragment: MapFragment var questsLayer: MapData? = null set(value) { if (field === value) return field = value updateLayer() } /** Switch visibility of quest pins layer */ var isVisible: Boolean = true set(value) { if (field == value) return field = value updateLayer() } init { visibleQuestsSource.addListener(this) } @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onStart() { /* When reentering the fragment, the database may have changed (quest download in * background or change in settings), so the quests must be pulled from DB again */ initializeQuestTypeOrders() clear() onNewScreenPosition() } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onStop() { clear() } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy() { questsLayer = null visibleQuestsSource.removeListener(this) coroutineContext.cancel() } fun onNewScreenPosition() { val zoom = mapFragment.cameraPosition?.zoom ?: return if (zoom < TILES_ZOOM) return val displayedArea = mapFragment.getDisplayedArea() ?: return val tilesRect = displayedArea.enclosingTilesRect(TILES_ZOOM) if (lastDisplayedRect != tilesRect) { lastDisplayedRect = tilesRect updateQuestsInRect(tilesRect) } } override fun onUpdatedVisibleQuests(added: Collection<Quest>, removed: Collection<Long>, group: QuestGroup) { added.forEach { add(it, group) } removed.forEach { remove(it, group) } updateLayer() } override fun onVisibleQuestsInvalidated() { clear() onNewScreenPosition() } private fun updateQuestsInRect(tilesRect: TilesRect) { // area too big -> skip (performance) if (tilesRect.size > 4) { return } var tiles: List<Tile> synchronized(retrievedTiles) { tiles = tilesRect.asTileSequence().filter { !retrievedTiles.contains(it) }.toList() } val minRect = tiles.minTileRect() ?: return val bbox = minRect.asBoundingBox(TILES_ZOOM) val questTypeNames = questTypesProvider.get().map { it.javaClass.simpleName } launch(Dispatchers.IO) { visibleQuestsSource.getAllVisible(bbox, questTypeNames).forEach { add(it.quest, it.group) } updateLayer() } synchronized(retrievedTiles) { retrievedTiles.addAll(tiles) } } private fun add(quest: Quest, group: QuestGroup) { // hack away cycleway quests for old Android SDK versions (#713) if (quest.type is AddCycleway && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return } val questIconName = resources.getResourceEntryName(quest.type.icon) val positions = quest.markerLocations val points = positions.map { position -> val properties = mapOf( "type" to "point", "kind" to questIconName, "importance" to getQuestImportance(quest).toString(), MARKER_QUEST_GROUP to group.name, MARKER_QUEST_ID to quest.id!!.toString() ) Point(position.toLngLat(), properties) } synchronized(quests) { quests.getOrPut(group, { LongSparseArray(256) }).put(quest.id!!, points) } } private fun remove(questId: Long, group: QuestGroup) { synchronized(quests) { quests[group]?.remove(questId) } } private fun clear() { synchronized(quests) { for (value in quests.values) { value.clear() } } synchronized(retrievedTiles) { retrievedTiles.clear() } questsLayer?.clear() lastDisplayedRect = null } private fun updateLayer() { if (isVisible) { questsLayer?.setFeatures(getPoints()) } else { questsLayer?.clear() } } private fun getPoints(): List<Point> { synchronized(quests) { return quests.values.flatMap { questsById -> questsById.values.flatten() } } } private fun initializeQuestTypeOrders() { // this needs to be reinitialized when the quest order changes var order = 0 for (questType in questTypesProvider.get()) { questTypeOrders[questType] = order++ } } /** returns values from 0 to 100000, the higher the number, the more important */ private fun getQuestImportance(quest: Quest): Int { val questTypeOrder = questTypeOrders[quest.type] ?: 0 val freeValuesForEachQuest = 100000 / questTypeOrders.size /* quest ID is used to add values unique to each quest to make ordering consistent freeValuesForEachQuest is an int, so % freeValuesForEachQuest will fit into int */ val hopefullyUniqueValueForQuest = ((quest.id?: 0) % freeValuesForEachQuest).toInt() return 100000 - questTypeOrder * freeValuesForEachQuest + hopefullyUniqueValueForQuest } companion object { const val MARKER_QUEST_ID = "quest_id" const val MARKER_QUEST_GROUP = "quest_group" private const val TILES_ZOOM = 14 } }
gpl-3.0
e7b8f3832de72f186a8d5ce82fbfaf4b
35.478049
113
0.654453
4.878017
false
false
false
false
JayNewstrom/ViewMode
view-mode-sample/src/main/java/com/jaynewstrom/viewmodesample/MainActivity.kt
1
1413
package com.jaynewstrom.viewmodesample import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import butterknife.BindView import butterknife.ButterKnife import com.jaynewstrom.viewmode.ViewModeView class MainActivity : AppCompatActivity() { @BindView(R.id.view_mode_view) lateinit var viewModeView: ViewModeView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) ButterKnife.bind(this) if (savedInstanceState == null) { viewModeView.showViewMode(ViewModes.CONTENT) } else { viewModeView.showViewMode(savedInstanceState.getSerializable(SAVED_STATE_VIEW_MODE) as ViewModes) } if (viewModeView.currentViewMode() === ViewModes.CONTENT) { val contentView = viewModeView.viewForViewMode(ViewModes.CONTENT) as ContentView // Usually I would use dependency injection to get a reference, but to keep things simple, this works. contentView.setViewModeView(viewModeView) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putSerializable(SAVED_STATE_VIEW_MODE, viewModeView.currentViewMode() as ViewModes?) } companion object { private const val SAVED_STATE_VIEW_MODE = "savedState.viewMode" } }
apache-2.0
962a6eaa716b0d197ddaddda1be6c23b
36.184211
114
0.720453
4.839041
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/persistence/di/PersistenceModule.kt
2
5764
package org.stepic.droid.persistence.di import android.app.DownloadManager import android.content.Context import dagger.Binds import dagger.Module import dagger.Provides import io.reactivex.Observable import io.reactivex.Observer import io.reactivex.subjects.PublishSubject import org.stepic.droid.di.qualifiers.PersistenceProgressStatusMapper import org.stepic.droid.persistence.downloads.DownloadTaskManager import org.stepic.droid.persistence.downloads.DownloadTaskManagerImpl import org.stepic.droid.persistence.downloads.helpers.AddDownloadTaskHelper import org.stepic.droid.persistence.downloads.helpers.AddDownloadTaskHelperImpl import org.stepic.droid.persistence.downloads.helpers.RemoveDownloadTaskHelper import org.stepic.droid.persistence.downloads.helpers.RemoveDownloadTaskHelperImpl import org.stepic.droid.persistence.downloads.progress.mapper.DownloadProgressStatusMapper import org.stepic.droid.persistence.downloads.progress.mapper.DownloadProgressStatusMapperImpl import org.stepic.droid.persistence.downloads.resolvers.DownloadTitleResolver import org.stepic.droid.persistence.downloads.resolvers.DownloadTitleResolverImpl import org.stepic.droid.persistence.files.ExternalStorageManager import org.stepic.droid.persistence.files.ExternalStorageManagerImpl import org.stepic.droid.persistence.model.Structure import org.stepic.droid.persistence.service.FileTransferService import org.stepic.droid.persistence.storage.PersistentItemObserver import org.stepic.droid.persistence.storage.PersistentItemObserverImpl import org.stepic.droid.persistence.storage.PersistentStateManager import org.stepic.droid.persistence.storage.PersistentStateManagerImpl import org.stepic.droid.persistence.storage.dao.SystemDownloadsDao import org.stepic.droid.persistence.storage.dao.SystemDownloadsDaoImpl import org.stepik.android.view.injection.assignment.AssignmentDataModule import org.stepik.android.view.injection.attempt.AttemptDataModule import org.stepik.android.view.injection.course.CourseDataModule import org.stepik.android.view.injection.lesson.LessonDataModule import org.stepik.android.view.injection.progress.ProgressDataModule import org.stepik.android.view.injection.section.SectionDataModule import org.stepik.android.view.injection.step.StepDataModule import org.stepik.android.view.injection.submission.SubmissionDataModule import org.stepik.android.view.injection.unit.UnitDataModule import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock @Module(includes = [ ContentModule::class, DownloadInteractorsModule::class, StructureResolversModule::class, ProgressProvidersModule::class, AssignmentDataModule::class, AttemptDataModule::class, CourseDataModule::class, LessonDataModule::class, UnitDataModule::class, SectionDataModule::class, ProgressDataModule::class, StepDataModule::class, SubmissionDataModule::class ]) abstract class PersistenceModule { @Binds @PersistenceScope abstract fun bindUpdatesObservable(subject: PublishSubject<Structure>): Observable<Structure> @Binds @PersistenceScope abstract fun bindUpdatesObserver(subject: PublishSubject<Structure>): Observer<Structure> @Binds @PersistenceScope abstract fun bindSystemDonwloadsDao(systemDownloadsDaoImpl: SystemDownloadsDaoImpl): SystemDownloadsDao @Binds @PersistenceScope abstract fun bindExternalStorageManager(externalStorageManagerImpl: ExternalStorageManagerImpl): ExternalStorageManager @Binds @PersistenceScope abstract fun bindDownloadTaskManager(downloadTaskManagerImpl: DownloadTaskManagerImpl): DownloadTaskManager @Binds @PersistenceScope abstract fun bindPersistentStateManager(persistentStateManagerImpl: PersistentStateManagerImpl): PersistentStateManager @Binds @PersistenceScope abstract fun bindPersistentItemObserver(persistentItemObserverImpl: PersistentItemObserverImpl): PersistentItemObserver @Binds @PersistenceScope abstract fun bindDownloadTitleResolver(downloadTitleResolverImpl: DownloadTitleResolverImpl): DownloadTitleResolver @Binds @PersistenceScope abstract fun bindAddDownloadTasksHelper(addDownloadTasksHelperImpl: AddDownloadTaskHelperImpl): AddDownloadTaskHelper @Binds @PersistenceScope abstract fun bindRemoveDownloadTasksHelper(removeDownloadTasksHelperImpl: RemoveDownloadTaskHelperImpl): RemoveDownloadTaskHelper @Binds @PersistenceScope @PersistenceProgressStatusMapper abstract fun bindDownloadProgressStatusMapper(downloadProgressStatusMapperImpl: DownloadProgressStatusMapperImpl): DownloadProgressStatusMapper @Module companion object { private const val UPDATE_INTERVAL_MS = 1000L @Provides @JvmStatic @PersistenceScope fun provideFileTransferEventSubject(): PublishSubject<FileTransferService.Event> = PublishSubject.create() @Provides @JvmStatic @PersistenceScope fun provideUpdatesPublishSubject(): PublishSubject<Structure> = PublishSubject.create() @Provides @JvmStatic @PersistenceScope fun provideIntervalUpdatesObservable(): Observable<kotlin.Unit> = Observable.interval(UPDATE_INTERVAL_MS, TimeUnit.MILLISECONDS).map { kotlin.Unit } @Provides @JvmStatic @PersistenceScope fun provideDownloadManager(context: Context): DownloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager @Provides @JvmStatic @FSLock @PersistenceScope fun provideFSLock(): ReentrantLock = ReentrantLock() } }
apache-2.0
761a862a44128816480f3edbe397b37a
39.314685
147
0.807599
5.259124
false
false
false
false
CarlosEsco/tachiyomi
core/src/main/java/eu/kanade/tachiyomi/network/ProgressResponseBody.kt
1
1387
package eu.kanade.tachiyomi.network import okhttp3.MediaType import okhttp3.ResponseBody import okio.Buffer import okio.BufferedSource import okio.ForwardingSource import okio.Source import okio.buffer import java.io.IOException class ProgressResponseBody(private val responseBody: ResponseBody, private val progressListener: ProgressListener) : ResponseBody() { private val bufferedSource: BufferedSource by lazy { source(responseBody.source()).buffer() } override fun contentType(): MediaType? { return responseBody.contentType() } override fun contentLength(): Long { return responseBody.contentLength() } override fun source(): BufferedSource { return bufferedSource } private fun source(source: Source): Source { return object : ForwardingSource(source) { var totalBytesRead = 0L @Throws(IOException::class) override fun read(sink: Buffer, byteCount: Long): Long { val bytesRead = super.read(sink, byteCount) // read() returns the number of bytes read, or -1 if this source is exhausted. totalBytesRead += if (bytesRead != -1L) bytesRead else 0 progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1L) return bytesRead } } } }
apache-2.0
38ec4bfe060252823ed642c7addeeedd
30.522727
133
0.667628
5.293893
false
false
false
false
exponentjs/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/permissions/requesters/ForegroundLocationRequester.kt
2
1246
package abi43_0_0.expo.modules.permissions.requesters import android.Manifest import android.os.Bundle import abi43_0_0.expo.modules.interfaces.permissions.PermissionsResponse import abi43_0_0.expo.modules.interfaces.permissions.PermissionsStatus class ForegroundLocationRequester : PermissionRequester { override fun getAndroidPermissions() = listOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ) override fun parseAndroidPermissions(permissionsResponse: Map<String, PermissionsResponse>): Bundle { return parseBasicLocationPermissions(permissionsResponse).apply { val accessFineLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_FINE_LOCATION) val accessCoarseLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_COARSE_LOCATION) val accuracy = when { accessFineLocation.status == PermissionsStatus.GRANTED -> { "fine" } accessCoarseLocation.status == PermissionsStatus.GRANTED -> { "coarse" } else -> { "none" } } putBundle( "android", Bundle().apply { putString("accuracy", accuracy) } ) } } }
bsd-3-clause
b3c58ad26b050c3e1fef09fe0c4f1118
30.948718
105
0.704655
5.085714
false
false
false
false
sirixdb/sirix
bundles/sirix-kotlin-cli/src/main/kotlin/org/sirix/cli/Main.kt
1
1406
@file:OptIn(ExperimentalCli::class) package org.sirix.cli import kotlinx.cli.* import org.sirix.cli.commands.CliCommand import org.sirix.cli.parser.* fun main(args: Array<String>) { val cliCommand: CliCommand? = parseArgs(args) if (cliCommand != null) { cliCommand.execute() } else { println("No Command provided!") } } fun parseArgs(args: Array<String>): CliCommand? { val argParser = ArgParser("Sirix CLI") val location by argParser.option(ArgType.String, "location", "l", "The Sirix DB File location").required() // Can not use default values when using subcommands at the moment. // See https://github.com/Kotlin/kotlinx.cli/issues/26 val verbose by argParser.option(ArgType.Boolean, "verbose", "v", "Run verbosely") val subCommandList: Array<Subcommand> = arrayOf( CreateSubcommand(), DropSubCommand(), CreateResourceSubCommand(), DropResourceSubCommand(), DumpResourceHistorySubCommand(), QuerySubCommand(), UpdateSubCommand() ) argParser.subcommands(*subCommandList) argParser.parse(args) val options = CliOptions(location, verbose ?: false) subCommandList.forEach { val asc: AbstractArgSubCommand = it as AbstractArgSubCommand if (asc.wasExecuted()) { return asc.createCliCommand(options) } } return null }
bsd-3-clause
0c625a464390b809bd63ed16aa06f161
25.037037
110
0.667852
4.273556
false
false
false
false
realm/realm-java
examples/coroutinesExample/src/main/java/io/realm/examples/coroutinesexample/data/newsreader/network/model/NYTimes.kt
1
2264
/* * Copyright 2020 Realm 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 io.realm.examples.coroutinesexample.data.newsreader.network.model import com.squareup.moshi.Json data class NYTimesResponse( val status: String, val copyright: String, val section: String, @field:Json(name = "last_updated") val lastUpdated: String, @field:Json(name = "num_results") val numResults: Int, val results: List<NYTimesArticle> ) data class NYTimesArticle( val section: String, val subsection: String, val title: String, @field:Json(name = "abstract") val abstractText: String?, val url: String, val uri: String, val byline: String, @field:Json(name = "item_type") val itemType: String?, @field:Json(name = "updated_date") val updatedDate: String?, @field:Json(name = "created_date") val createDate: String?, @field:Json(name = "published_date") val publishedDate: String?, @field:Json(name = "material_type_facet") val materialTypeFacet: String?, val kicker: String, @field:Json(name = "des_facet") val desFacet: List<String>?, @field:Json(name = "org_facet") val orgFacet: List<String>?, @field:Json(name = "per_facet") val perFacet: List<String>?, @field:Json(name = "geo_facet") val geoFacet: List<String>?, val multimedia: List<NYTMultimedium>, @field:Json(name = "short_url") val shortUrl: String? ) data class NYTMultimedium( val url: String, val format: String, val height: Int, val width: Int, val type: String, val subtype: String, val caption: String, val copyright: String )
apache-2.0
546d67d0f758e8f699e4a74f9a34e600
36.114754
81
0.654594
3.883362
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LALR1/semantic/SemanticMachine.kt
1
3846
package com.bajdcc.LALR1.semantic import com.bajdcc.LALR1.grammar.semantic.ISemanticAction import com.bajdcc.LALR1.grammar.semantic.ISemanticAnalyzer import com.bajdcc.LALR1.grammar.semantic.ISemanticRecorder import com.bajdcc.LALR1.grammar.symbol.IManageSymbol import com.bajdcc.LALR1.grammar.symbol.IQuerySymbol import com.bajdcc.LALR1.semantic.token.IRandomAccessOfTokens import com.bajdcc.LALR1.semantic.token.ParsingStack import com.bajdcc.LALR1.semantic.tracker.Instruction import com.bajdcc.LALR1.syntax.automata.npa.NPAInstruction import com.bajdcc.LALR1.syntax.rule.RuleItem import com.bajdcc.util.lexer.token.Token /** * 【语义分析】语义指令运行时机器 * [items] 规则集合 * [actions] 语义动作集合 * [tokens] 单词流 * [query] 符号表查询接口 * [manage] 符号表管理接口 * [recorder] 语义错误处理接口 * @author bajdcc */ class SemanticMachine(private val items: List<RuleItem>, private val actions: List<ISemanticAction>, private val tokens: List<Token>, private val query: IQuerySymbol, private val manage: IManageSymbol, private val recorder: ISemanticRecorder, val debug: Boolean = false) : IRandomAccessOfTokens { /** * 单词索引 */ private var index = 0 /** * 语义动作接口 */ private var action: ISemanticAction? = null /** * 语义处理接口 */ private var handler: ISemanticAnalyzer? = null /** * 数据处理堆栈 */ private val ps = ParsingStack() /** * 结果 */ var obj: Any = Object() private set /** * 运行一个指令 * * @param inst 指令 */ fun run(inst: Instruction) { /* 重置处理机制 */ handler = null action = null /* 处理前 */ if (inst.handler != -1) { when (inst.inst) { NPAInstruction.PASS, NPAInstruction.READ, NPAInstruction.SHIFT -> action = actions[inst.handler] else -> handler = items[inst.handler].handler } } action?.handle(ps, manage, this, recorder) when (inst.inst) { NPAInstruction.PASS -> index++ NPAInstruction.READ -> { ps[inst.index] = tokens[index] index++ } NPAInstruction.SHIFT -> ps.push() else -> { } } /* 处理时 */ if (handler != null) { obj = handler!!.handle(ps, query, recorder) } /* 处理后 */ when (inst.inst) { NPAInstruction.LEFT_RECURSION -> { ps.pop()// 先pop再push为了让栈层成为current的引用 ps.push() ps[inst.index] = obj } NPAInstruction.LEFT_RECURSION_DISCARD -> { ps.pop() ps.push() } NPAInstruction.PASS -> { } NPAInstruction.READ -> { } NPAInstruction.SHIFT -> { } NPAInstruction.TRANSLATE -> { ps.pop() ps[inst.index] = obj } NPAInstruction.TRANSLATE_DISCARD -> ps.pop() NPAInstruction.TRANSLATE_FINISH -> ps.pop() } /* 打印调试信息 */ if (debug) { System.err.println("#### $inst ####") System.err.println(ps.toString()) System.err.println() } } override fun relativeGet(index: Int): Token { return tokens[this.index + index] } override fun positiveGet(index: Int): Token { return tokens[index] } }
mit
0e0cba996e02ed3bf3e20ad80da1fad5
26.603053
81
0.533186
4.254118
false
false
false
false
PolymerLabs/arcs
java/arcs/core/storage/util/HoldQueue.kt
1
4225
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.storage.util import arcs.core.common.Referencable import arcs.core.common.ReferenceId import arcs.core.crdt.VersionMap import arcs.core.storage.util.HoldQueue.Entity import arcs.core.storage.util.HoldQueue.Record import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock /** * Maintainer of a collection of references for data awaiting processing. * * During [processReferenceId]: when all of the reference's entities' [Entity.version] values are * dominated-by the incoming [VersionMap], it is considered ready for processing. (by calling its * [Record]'s [Record.onRelease] method) */ class HoldQueue( /** An [OperationQueue] that will run the blocks for released [Record]s. */ private val operationQueue: OperationQueue ) { private val mutex = Mutex() /* internal */ val queue = mutableMapOf<ReferenceId, MutableList<Record>>() /** * Enqueues a collection of [Entities] into the [HoldQueue]. When they are ready, [onRelease] * will be called. * * @return an identifier for the hold record which can be used to remove a hold using * [removeFromQueue]. */ suspend fun enqueue(entities: Collection<Entity>, onRelease: suspend () -> Unit): Int { val holdRecord = Record( entities.associateByTo(mutableMapOf(), Entity::id, Entity::version), onRelease ) mutex.withLock { // Update the queue by adding the holdRecord to the records for each entity's id. entities.forEach { val list = queue[it.id] ?: mutableListOf() list += holdRecord queue[it.id] = list } } return holdRecord.hashCode() } /** * Removes a pending item from the [HoldQueue] by the [enqueueId] returned from [enqueue]. */ suspend fun removeFromQueue(enqueueId: Int) = mutex.withLock { queue.values.forEach { records -> records.removeAll { it.hashCode() == enqueueId } } } /** * Removes a pending item from the [HoldQueue] by collection of reference ids. */ suspend fun removePendingIds(ids: Collection<ReferenceId>) { mutex.withLock { ids.forEach { queue.remove(it) } } } /** * Processes a given [ReferenceId] corresponding to the current [version]. * * See [HoldQueue]'s documentation for more details. */ suspend fun processReferenceId(id: ReferenceId, version: VersionMap) { val recordsToRelease = mutableListOf<Record>() mutex.withLock { // For each record belonging to the id, find all versionMaps which are dominated by the // given version and remove them from the record. If that makes the record empty, call // the onRelease method. queue[id]?.forEach { record -> record.ids[id] ?.takeIf { version dominates it } ?.let { record.ids.remove(id) } if (record.ids.isEmpty()) { recordsToRelease += record } } queue.remove(id) } operationQueue.enqueue { recordsToRelease.forEach { it.onRelease() } } } /** Simple alias for an entity being referenced. */ data class Entity(val id: ReferenceId, val version: VersionMap?) // Internal for testing. /* internal */ data class Record( val ids: MutableMap<ReferenceId, VersionMap?>, val onRelease: suspend () -> Unit ) } /** * Enqueues all [Referencable]s in the collection into the [HoldQueue] at the specified [version] * with a given [onRelease] callback. */ suspend fun <T : Referencable> Collection<T>.enqueueAll( holdQueue: HoldQueue, version: VersionMap, onRelease: suspend () -> Unit ) = holdQueue.enqueue(map { it.toHoldQueueEntity(version) }, onRelease) /** * Converts an object implementing [Referencable] to a [HoldQueue.Entity] with the specified * [version]. */ fun <T : Referencable> T.toHoldQueueEntity(version: VersionMap): Entity = Entity(this.id, version.copy()) // TODO: maybe we shouldn't copy the version map?
bsd-3-clause
e0696b95120fe042579139e9949f5d6a
31.007576
97
0.68568
4.150295
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/ndarray/SparseBinaryNDArraySpec.kt
1
3029
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * 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 http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package ndarray import com.kotlinnlp.simplednn.simplemath.ndarray.Indices import com.kotlinnlp.simplednn.simplemath.ndarray.Shape import com.kotlinnlp.simplednn.simplemath.ndarray.sparsebinary.SparseBinaryNDArrayFactory import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertEquals import kotlin.test.assertFalse /** * */ class SparseBinaryNDArraySpec : Spek({ describe("a SparseBinaryNDArray") { context("iteration") { context("row vector") { val array = SparseBinaryNDArrayFactory.arrayOf(activeIndices = listOf(1, 3, 19), shape = Shape(1, 20)) val iterator = array.iterator() it("should return the expected first indices Pair") { assertEquals(Pair(0, 1), iterator.next()) } it("should return the expected second indices Pair") { assertEquals(Pair(0, 3), iterator.next()) } it("should return the expected third indices Pair") { assertEquals(Pair(0, 19), iterator.next()) } it("should return false calling hasNext() at the fourth iteration") { assertFalse { iterator.hasNext() } } } context("column vector") { val array = SparseBinaryNDArrayFactory.arrayOf(activeIndices = listOf(1, 3, 19), shape = Shape(20)) val iterator = array.iterator() it("should return the expected first indices Pair") { assertEquals(Pair(1, 0), iterator.next()) } it("should return the expected second indices Pair") { assertEquals(Pair(3, 0), iterator.next()) } it("should return the expected third indices Pair") { assertEquals(Pair(19, 0), iterator.next()) } it("should return false calling hasNext() at the fourth iteration") { assertFalse { iterator.hasNext() } } } context("a 2-dim array") { val array = SparseBinaryNDArrayFactory.arrayOf( activeIndices = arrayOf(Indices(1, 0), Indices(5, 19), Indices(12, 6)), shape = Shape(15, 20)) val iterator = array.iterator() it("should return the expected first indices Pair") { assertEquals(Pair(1, 0), iterator.next()) } it("should return the expected second indices Pair") { assertEquals(Pair(12, 6), iterator.next()) } it("should return the expected third indices Pair") { assertEquals(Pair(5, 19), iterator.next()) } it("should return false calling hasNext() at the fourth iteration") { assertFalse { iterator.hasNext() } } } } } })
mpl-2.0
477fd23a81f28805edbb760d8fd7aa2f
30.552083
110
0.619346
4.554887
false
false
false
false
andgate/Ikou
core/src/com/andgate/ikou/animate/LinearTween.kt
1
2339
/* This file is part of Ikou. Ikou is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License. Ikou 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 Ikou. If not, see <http://www.gnu.org/licenses/>. */ package com.andgate.ikou.animate; import com.badlogic.gdx.math.Matrix4 import com.badlogic.gdx.math.Vector3; class LinearTween(start: Vector3, end: Vector3, val speed: Float) : Tween(start, end) { private val TAG: String = "LinearTween" private val ACCUMULATOR_MAX: Float = 1f private var accumulator: Float = 0f init { duration = calculateTweenTime(start, end, speed) } /** * Update the tween. New value can be retrieved with LinearTween.get() * @param delta Time to elapse. * @return False if unfinished, true when done. */ override fun update(target: Matrix4, delta: Float) { val percentTween: Float = delta / duration if(accumulator == 0f) start_hook() accumulator += percentTween if(accumulator >= ACCUMULATOR_MAX) { curr.set(end) isCompleted = true finish_hook() } else { curr.set(start) curr.lerp(end, accumulator) } target.setTranslation(curr) update_hook(curr.cpy()) } private fun calculateTweenTime(start: Vector3, end: Vector3, speed: Float): Float { val distance = Vector3(end).sub(start) val time: Float = distance.len() / speed return time } // Get delta time unused by the tween, for chaining consecutive tweens. override fun remainingDelta(): Float { val deltaAccum: Float = accumulator - ACCUMULATOR_MAX if(deltaAccum > 0.0f) { val delta_time: Float = deltaAccum * duration return delta_time } return 0f } }
gpl-2.0
97c9ad1b38a60e3c34c948c1c936831e
27.180723
85
0.619068
4.283883
false
false
false
false
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinULambdaExpression.kt
4
2996
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.PsiType import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter @ApiStatus.Internal class KotlinULambdaExpression( override val sourcePsi: KtLambdaExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), ULambdaExpression, KotlinUElementWithType { override val functionalInterfaceType: PsiType? by lz { baseResolveProviderService.getFunctionalInterfaceType(this) } override val body by lz { sourcePsi.bodyExpression?.let { Body(it, this) } ?: UastEmptyExpression(this) } @ApiStatus.Internal class Body( bodyExpression: KtBlockExpression, parent: KotlinULambdaExpression ) : KotlinUBlockExpression(bodyExpression, parent) { override val expressions: List<UExpression> by lz { val statements = sourcePsi.statements if (statements.isEmpty()) return@lz emptyList<UExpression>() ArrayList<UExpression>(statements.size).also { result -> statements.subList(0, statements.size - 1).mapTo(result) { baseResolveProviderService.baseKotlinConverter.convertOrEmpty(it, this) } result.add(implicitReturn ?: baseResolveProviderService.baseKotlinConverter.convertOrEmpty(statements.last(), this)) } } val implicitReturn: KotlinUImplicitReturnExpression? by lz { baseResolveProviderService.getImplicitReturn(parent.sourcePsi, this) } } override val valueParameters by lz { getParameters(includeExplicitParameters = false) } override val parameters: List<UParameter> by lz { getParameters(includeExplicitParameters = true) } private fun getParameters(includeExplicitParameters: Boolean): List<UParameter> { val explicitParameters = sourcePsi.valueParameters.mapIndexed { i, p -> KotlinUParameter(UastKotlinPsiParameter.create(p, sourcePsi, this, i), p, this) } if (explicitParameters.isNotEmpty()) return explicitParameters return baseResolveProviderService.getImplicitParameters(sourcePsi, this, includeExplicitParameters) } override fun asRenderString(): String { val renderedValueParameters = if (valueParameters.isEmpty()) "" else valueParameters.joinToString { it.asRenderString() } + " ->\n" val expressions = (body as? UBlockExpression)?.expressions?.joinToString("\n") { it.asRenderString().withMargin } ?: body.asRenderString() return "{ $renderedValueParameters\n$expressions\n}" } }
apache-2.0
9f73c9a6f28e0e2f7a77f0c6f632893c
39.486486
158
0.706275
5.398198
false
false
false
false
MiJack/ImageDrive
app/src/main/java/cn/mijack/imagedrive/ui/ProfileActivity.kt
1
6397
package cn.mijack.imagedrive.ui import android.app.Activity import android.content.Intent import android.os.Bundle import android.provider.MediaStore import android.support.design.widget.CoordinatorLayout import android.support.design.widget.Snackbar import android.support.design.widget.TextInputLayout import android.support.v4.view.ViewCompat import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Button import android.widget.TextView import android.widget.Toast import cn.mijack.imagedrive.R import cn.mijack.imagedrive.base.BaseActivity import cn.mijack.imagedrive.util.TextHelper import cn.mijack.imagedrive.util.Utils import com.afollestad.materialdialogs.MaterialDialog import com.bumptech.glide.Glide import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.UserProfileChangeRequest import com.google.firebase.storage.FirebaseStorage import de.hdodenhof.circleimageview.CircleImageView class ProfileActivity : BaseActivity(), View.OnClickListener { private var firebaseAuth: FirebaseAuth? = null private var toolbar: Toolbar? = null private var titleInfo: TextView? = null private var circleImageView: CircleImageView? = null private var selectAvatar: Button? = null private var editNickName: TextInputLayout? = null private var editEmail: TextInputLayout? = null private var coordinatorLayout: CoordinatorLayout? = null private var dialog: MaterialDialog? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_profile) toolbar = findViewById<Toolbar>(R.id.toolbar) titleInfo = findViewById<TextView>(R.id.titleInfo) coordinatorLayout = findViewById<CoordinatorLayout>(R.id.coordinatorLayout) circleImageView = findViewById<CircleImageView>(R.id.circleImageView) selectAvatar = findViewById<Button>(R.id.selectAvatar) editNickName = findViewById<TextInputLayout>(R.id.editNickName) editEmail = findViewById<TextInputLayout>(R.id.editEmail) setSupportActionBar(toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) supportActionBar!!.setDisplayShowHomeEnabled(true) ViewCompat.setTransitionName(circleImageView, "profile") firebaseAuth = FirebaseAuth.getInstance() val user = firebaseAuth!!.currentUser editNickName!!.editText!!.setText(user!!.displayName) editEmail!!.editText!!.setText(user.email) println("photo uri:" + user.photoUrl!!) if (!Utils.isEmpty(user.photoUrl!!)) { Glide.with(this).load(user.photoUrl).into(circleImageView!!) } else { circleImageView!!.setImageResource(R.drawable.ic_empty_profile) } selectAvatar!!.setOnClickListener(this) circleImageView!!.setOnClickListener(this) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_profile, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.actionSave -> { editNickName!!.isEnabled = false val request = UserProfileChangeRequest.Builder() .setDisplayName(TextHelper.getText(editNickName!!)) .build() firebaseAuth!!.currentUser!!.updateProfile(request) .addOnFailureListener(this) { result -> Snackbar.make(coordinatorLayout!!, R.string.settings_failure, Snackbar.LENGTH_SHORT).show() } .addOnSuccessListener(this) { result -> Snackbar.make(coordinatorLayout!!, R.string.settings_success, Snackbar.LENGTH_SHORT).show() } .addOnCompleteListener(this) { result -> editNickName!!.isEnabled = true } } android.R.id.home -> { finish() return true } } return super.onOptionsItemSelected(item) } override fun onClick(v: View) { if (v.id == R.id.selectAvatar || v.id == R.id.circleImageView) { gotoPickImage() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_PICK_IMAGE && resultCode == Activity.RESULT_OK) { //todo val imageUri = data.data dialog = MaterialDialog.Builder(this).title(R.string.setting_avatar) .progress(true, 100).build() dialog!!.show() val firebaseAuth = FirebaseAuth.getInstance() val user = firebaseAuth.currentUser val uid = user!!.uid val firebaseStorage = FirebaseStorage.getInstance() val reference = firebaseStorage.reference.child("avatars").child(uid) reference.putFile(imageUri).addOnSuccessListener { taskSnapshot -> val downloadUrl = taskSnapshot.downloadUrl val firebaseAuth1 = FirebaseAuth.getInstance() val request = UserProfileChangeRequest.Builder().setPhotoUri(downloadUrl) .build() firebaseAuth1.currentUser!!.updateProfile(request).addOnSuccessListener { aVoid -> Snackbar.make(coordinatorLayout!!, R.string.setting_avatar_success, Toast.LENGTH_SHORT).show() dialog!!.cancel() val firebaseUser = FirebaseAuth.getInstance().currentUser Glide.with(this@ProfileActivity).load(firebaseUser!!.photoUrl).into(circleImageView!!) }.addOnFailureListener { e -> Snackbar.make(coordinatorLayout!!, R.string.setting_avatar_failure, Toast.LENGTH_SHORT).show() } }.addOnFailureListener { e -> Snackbar.make(coordinatorLayout!!, R.string.upload_avatar_failure, Toast.LENGTH_SHORT).show() } } } private fun gotoPickImage() { val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(intent, REQUEST_PICK_IMAGE) } companion object { private val TAG = "ProfileActivity" private val REQUEST_PICK_IMAGE = 1 } }
apache-2.0
ca26e07f19aff3fe4e2a4264bd53b13f
45.021583
157
0.679225
5.009397
false
false
false
false
GunoH/intellij-community
plugins/changeReminder/src/com/jetbrains/changeReminder/changes/ChangeReminderCheckAction.kt
5
1587
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.changeReminder.changes import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAware import com.jetbrains.changeReminder.ChangeReminderBundle import com.jetbrains.changeReminder.anyGitRootsForIndexing import com.jetbrains.changeReminder.getGitRoots import com.jetbrains.changeReminder.plugin.UserSettings class ChangeReminderCheckAction : ToggleAction(), DumbAware { private val userSettings = service<UserSettings>() override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { super.update(e) val project = e.project ?: let { e.presentation.isEnabledAndVisible = false return } if (!project.anyGitRootsForIndexing()) { e.presentation.isEnabled = false if (project.getGitRoots().isEmpty()) { e.presentation.isVisible = false } else { e.presentation.setDescription(ChangeReminderBundle.messagePointer( "action.ChangesView.ViewOptions.ShowRelatedFiles.disabled.index.description" )) } } } override fun isSelected(e: AnActionEvent) = userSettings.isPluginEnabled override fun setSelected(e: AnActionEvent, state: Boolean) { userSettings.isPluginEnabled = state } }
apache-2.0
fa98d8430a529d0861bd40b415dbeae6
35.090909
140
0.767486
4.868098
false
false
false
false
NiciDieNase/chaosflix
touch/src/main/java/de/nicidienase/chaosflix/touch/browse/BrowseFragment.kt
1
1740
package de.nicidienase.chaosflix.touch.browse import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProviders import de.nicidienase.chaosflix.common.viewmodel.BrowseViewModel import de.nicidienase.chaosflix.common.viewmodel.ViewModelFactory open class BrowseFragment : androidx.fragment.app.Fragment() { lateinit var viewModel: BrowseViewModel var overlay: View? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProviders.of(activity!!, ViewModelFactory.getInstance(requireContext())).get(BrowseViewModel::class.java) } @JvmOverloads protected fun setupToolbar(toolbar: Toolbar, title: Int, isRoot: Boolean = true) { setupToolbar(toolbar, resources.getString(title), isRoot) } @JvmOverloads protected fun setupToolbar(toolbar: Toolbar, title: String, isRoot: Boolean = true) { val activity = activity as AppCompatActivity if (activity is BrowseActivity) { activity.setupDrawerToggle(toolbar) } activity.setSupportActionBar(toolbar) activity.supportActionBar?.setTitle(title) if (isRoot) { activity.supportActionBar?.setDisplayShowHomeEnabled(true) } else { activity.supportActionBar?.setDisplayHomeAsUpEnabled(true) } } protected fun setLoadingOverlayVisibility(visible: Boolean) { if (visible) { overlay?.setVisibility(View.VISIBLE) } else { overlay?.setVisibility(View.INVISIBLE) } } }
mit
ff75e58f4159c043c533965590091448
34.510204
134
0.718391
5.102639
false
false
false
false
ktorio/ktor
ktor-utils/common/src/io/ktor/util/pipeline/Pipeline.kt
1
16655
/* * 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.util.pipeline import io.ktor.util.* import io.ktor.util.collections.* import io.ktor.util.debug.* import io.ktor.util.debug.plugins.* import io.ktor.utils.io.concurrent.* import kotlinx.atomicfu.* import kotlin.coroutines.* internal typealias PipelineInterceptorFunction<TSubject, TContext> = (PipelineContext<TSubject, TContext>, TSubject, Continuation<Unit>) -> Any? /** * Represents an execution pipeline for asynchronous extensible computations */ @Suppress("DEPRECATION") public open class Pipeline<TSubject : Any, TContext : Any>( vararg phases: PipelinePhase ) { /** * Provides common place to store pipeline attributes */ public val attributes: Attributes = Attributes(concurrent = true) /** * Indicated if debug mode is enabled. In debug mode users will get more details in the stacktrace. */ public open val developmentMode: Boolean = false private val phasesRaw: MutableList<Any> = mutableListOf(*phases) private var interceptorsQuantity = 0 /** * Phases of this pipeline */ public val items: List<PipelinePhase> get() = phasesRaw.map { it as? PipelinePhase ?: (it as? PhaseContent<*, *>)?.phase!! } /** * @return `true` if there are no interceptors installed regardless number of phases */ public val isEmpty: Boolean get() = interceptorsQuantity == 0 private val _interceptors: AtomicRef<List<PipelineInterceptorFunction<TSubject, TContext>>?> = atomic(null) private var interceptors: List<PipelineInterceptorFunction<TSubject, TContext>>? get() = _interceptors.value set(value) { _interceptors.value = value } private var interceptorsListShared: Boolean = false private var interceptorsListSharedPhase: PipelinePhase? = null public constructor( phase: PipelinePhase, interceptors: List<PipelineInterceptor<TSubject, TContext>> ) : this(phase) { interceptors.forEach { intercept(phase, it) } } /** * Executes this pipeline in the given [context] and with the given [subject] */ public suspend fun execute(context: TContext, subject: TSubject): TSubject = createContext(context, subject, coroutineContext).execute(subject) /** * Adds [phase] to the end of this pipeline */ public fun addPhase(phase: PipelinePhase) { if (hasPhase(phase)) { return } phasesRaw.add(phase) } /** * Inserts [phase] after the [reference] phase. If there are other phases inserted after [reference], then [phase] * will be inserted after them. * Example: * ``` * val pipeline = Pipeline<String, String>(a) * pipeline.insertPhaseAfter(a, b) * pipeline.insertPhaseAfter(a, c) * assertEquals(listOf(a, b, c), pipeline.items) * ``` */ public fun insertPhaseAfter(reference: PipelinePhase, phase: PipelinePhase) { if (hasPhase(phase)) return val index = findPhaseIndex(reference) if (index == -1) { throw InvalidPhaseException("Phase $reference was not registered for this pipeline") } // insert after the last phase that has Relation.After on [reference] var lastRelatedPhaseIndex = index for (i in index + 1..phasesRaw.lastIndex) { val relation = (phasesRaw[i] as? PhaseContent<*, *>)?.relation ?: break val relatedTo = (relation as? PipelinePhaseRelation.After)?.relativeTo ?: continue lastRelatedPhaseIndex = if (relatedTo == reference) i else lastRelatedPhaseIndex } phasesRaw.add( lastRelatedPhaseIndex + 1, PhaseContent<TSubject, TContext>(phase, PipelinePhaseRelation.After(reference)) ) } /** * Inserts [phase] before the [reference] phase. * Example: * ``` * val pipeline = Pipeline<String, String>(c) * pipeline.insertPhaseBefore(c, a) * pipeline.insertPhaseBefore(c, b) * assertEquals(listOf(a, b, c), pipeline.items) * ``` */ public fun insertPhaseBefore(reference: PipelinePhase, phase: PipelinePhase) { if (hasPhase(phase)) return val index = findPhaseIndex(reference) if (index == -1) { throw InvalidPhaseException("Phase $reference was not registered for this pipeline") } phasesRaw.add(index, PhaseContent<TSubject, TContext>(phase, PipelinePhaseRelation.Before(reference))) } /** * Adds [block] to the [phase] of this pipeline */ public fun intercept(phase: PipelinePhase, block: PipelineInterceptor<TSubject, TContext>) { val phaseContent = findPhase(phase) ?: throw InvalidPhaseException("Phase $phase was not registered for this pipeline") @Suppress("UNCHECKED_CAST") block as PipelineInterceptorFunction<TSubject, TContext> if (tryAddToPhaseFastPath(phase, block)) { interceptorsQuantity++ return } phaseContent.addInterceptor(block) interceptorsQuantity++ resetInterceptorsList() afterIntercepted() } /** * Invoked after an interceptor has been installed */ public open fun afterIntercepted() { } public fun interceptorsForPhase(phase: PipelinePhase): List<PipelineInterceptor<TSubject, TContext>> { @Suppress("UNCHECKED_CAST") return phasesRaw.filterIsInstance<PhaseContent<*, *>>() .firstOrNull { phaseOrContent -> phaseOrContent.phase == phase } ?.sharedInterceptors() as List<PipelineInterceptor<TSubject, TContext>>? ?: emptyList() } public fun mergePhases(from: Pipeline<TSubject, TContext>) { val fromPhases = from.phasesRaw val toInsert = fromPhases.toMutableList() // the worst case is O(n^2), but it will happen only // when all phases were inserted before each other into the second pipeline // (see test testDependantPhasesLastCommon). // in practice, it will be linear time for most cases while (toInsert.isNotEmpty()) { val iterator = toInsert.iterator() while (iterator.hasNext()) { val fromPhaseOrContent = iterator.next() val fromPhase = (fromPhaseOrContent as? PipelinePhase) ?: (fromPhaseOrContent as PhaseContent<*, *>).phase if (hasPhase(fromPhase)) { iterator.remove() } else { val inserted = insertRelativePhase(fromPhaseOrContent, fromPhase) if (inserted) { iterator.remove() } } } } } private fun mergeInterceptors(from: Pipeline<TSubject, TContext>) { if (interceptorsQuantity == 0) { setInterceptorsListFromAnotherPipeline(from) } else { resetInterceptorsList() } val fromPhases = from.phasesRaw fromPhases.forEach { fromPhaseOrContent -> val fromPhase = (fromPhaseOrContent as? PipelinePhase) ?: (fromPhaseOrContent as PhaseContent<*, *>).phase if (fromPhaseOrContent is PhaseContent<*, *> && !fromPhaseOrContent.isEmpty) { @Suppress("UNCHECKED_CAST") fromPhaseOrContent as PhaseContent<TSubject, TContext> fromPhaseOrContent.addTo(findPhase(fromPhase)!!) interceptorsQuantity += fromPhaseOrContent.size } } } /** * Merges another pipeline into this pipeline, maintaining relative phases order */ public fun merge(from: Pipeline<TSubject, TContext>) { if (fastPathMerge(from)) { return } mergePhases(from) mergeInterceptors(from) } /** * Reset current pipeline from other. */ public fun resetFrom(from: Pipeline<TSubject, TContext>) { phasesRaw.clear() check(interceptorsQuantity == 0) fastPathMerge(from) } internal fun phaseInterceptors(phase: PipelinePhase): List<PipelineInterceptorFunction<TSubject, TContext>> = findPhase(phase)?.sharedInterceptors() ?: emptyList() /** * For tests only */ internal fun interceptorsForTests(): List<PipelineInterceptorFunction<TSubject, TContext>> { return interceptors ?: cacheInterceptors() } @Suppress("DEPRECATION") private fun createContext( context: TContext, subject: TSubject, coroutineContext: CoroutineContext ): PipelineContext<TSubject, TContext> = pipelineContextFor(context, sharedInterceptorsList(), subject, coroutineContext, developmentMode) private fun findPhase(phase: PipelinePhase): PhaseContent<TSubject, TContext>? { val phasesList = phasesRaw for (index in 0 until phasesList.size) { val current = phasesList[index] if (current === phase) { val content = PhaseContent<TSubject, TContext>(phase, PipelinePhaseRelation.Last) phasesList[index] = content return content } if (current is PhaseContent<*, *> && current.phase === phase) { @Suppress("UNCHECKED_CAST") return current as PhaseContent<TSubject, TContext> } } return null } private fun findPhaseIndex(phase: PipelinePhase): Int { val phasesList = phasesRaw for (index in 0 until phasesList.size) { val current = phasesList[index] if (current === phase || (current is PhaseContent<*, *> && current.phase === phase)) { return index } } return -1 } private fun hasPhase(phase: PipelinePhase): Boolean { val phasesList = phasesRaw for (index in 0 until phasesList.size) { val current = phasesList[index] if (current === phase || (current is PhaseContent<*, *> && current.phase === phase)) { return true } } return false } private fun cacheInterceptors(): List<PipelineInterceptorFunction<TSubject, TContext>> { val interceptorsQuantity = interceptorsQuantity if (interceptorsQuantity == 0) { notSharedInterceptorsList(emptyList()) return emptyList() } val phases = phasesRaw if (interceptorsQuantity == 1) { for (phaseIndex in 0..phases.lastIndex) { @Suppress("UNCHECKED_CAST") val phaseContent = phases[phaseIndex] as? PhaseContent<TSubject, TContext> ?: continue if (phaseContent.isEmpty) continue val interceptors = phaseContent.sharedInterceptors() setInterceptorsListFromPhase(phaseContent) return interceptors } } val destination: MutableList<PipelineInterceptorFunction<TSubject, TContext>> = mutableListOf() for (phaseIndex in 0..phases.lastIndex) { @Suppress("UNCHECKED_CAST") val phase = phases[phaseIndex] as? PhaseContent<TSubject, TContext> ?: continue phase.addTo(destination) } notSharedInterceptorsList(destination) return destination } private fun fastPathMerge(from: Pipeline<TSubject, TContext>): Boolean { if (from.phasesRaw.isEmpty()) { return true } if (phasesRaw.isNotEmpty()) { return false } val fromPhases = from.phasesRaw for (index in 0..fromPhases.lastIndex) { val fromPhaseOrContent = fromPhases[index] if (fromPhaseOrContent is PipelinePhase) { phasesRaw.add(fromPhaseOrContent) continue } if (fromPhaseOrContent !is PhaseContent<*, *>) { continue } @Suppress("UNCHECKED_CAST") fromPhaseOrContent as PhaseContent<TSubject, TContext> phasesRaw.add( PhaseContent( fromPhaseOrContent.phase, fromPhaseOrContent.relation, fromPhaseOrContent.sharedInterceptors() ) ) continue } interceptorsQuantity += from.interceptorsQuantity setInterceptorsListFromAnotherPipeline(from) return true } private fun sharedInterceptorsList(): List<PipelineInterceptorFunction<TSubject, TContext>> { if (interceptors == null) { cacheInterceptors() } interceptorsListShared = true return interceptors!! } private fun resetInterceptorsList() { interceptors = null interceptorsListShared = false interceptorsListSharedPhase = null } private fun notSharedInterceptorsList(list: List<PipelineInterceptorFunction<TSubject, TContext>>) { interceptors = list interceptorsListShared = false interceptorsListSharedPhase = null } private fun setInterceptorsListFromPhase(phaseContent: PhaseContent<TSubject, TContext>) { interceptors = phaseContent.sharedInterceptors() interceptorsListShared = false interceptorsListSharedPhase = phaseContent.phase } private fun setInterceptorsListFromAnotherPipeline(pipeline: Pipeline<TSubject, TContext>) { interceptors = pipeline.sharedInterceptorsList() interceptorsListShared = true interceptorsListSharedPhase = null } private fun tryAddToPhaseFastPath( phase: PipelinePhase, block: PipelineInterceptorFunction<TSubject, TContext> ): Boolean { val currentInterceptors = interceptors if (phasesRaw.isEmpty() || currentInterceptors == null) { return false } if (interceptorsListShared || currentInterceptors !is MutableList) { return false } if (interceptorsListSharedPhase == phase) { currentInterceptors.add(block) return true } if (phase == phasesRaw.last() || findPhaseIndex(phase) == phasesRaw.lastIndex) { findPhase(phase)!!.addInterceptor(block) currentInterceptors.add(block) return true } return false } private fun insertRelativePhase(fromPhaseOrContent: Any, fromPhase: PipelinePhase): Boolean { val fromPhaseRelation = when { fromPhaseOrContent === fromPhase -> PipelinePhaseRelation.Last else -> (fromPhaseOrContent as PhaseContent<*, *>).relation } when { fromPhaseRelation is PipelinePhaseRelation.Last -> addPhase(fromPhase) fromPhaseRelation is PipelinePhaseRelation.Before && hasPhase(fromPhaseRelation.relativeTo) -> insertPhaseBefore(fromPhaseRelation.relativeTo, fromPhase) fromPhaseRelation is PipelinePhaseRelation.After -> insertPhaseAfter(fromPhaseRelation.relativeTo, fromPhase) else -> return false } return true } } /** * Executes this pipeline */ @Suppress("NOTHING_TO_INLINE") public suspend inline fun <TContext : Any> Pipeline<Unit, TContext>.execute( context: TContext ) { // A list of executed plugins with their handlers must be attached to the call's coroutine context // in order to be available from the IntelliJ debugger any time inside the call. initContextInDebugMode { execute(context, Unit) } } /** * Intercepts an untyped pipeline when the subject is of the given type */ public inline fun <reified TSubject : Any, TContext : Any> Pipeline<*, TContext>.intercept( phase: PipelinePhase, noinline block: suspend PipelineContext<TSubject, TContext>.(TSubject) -> Unit ) { intercept(phase) interceptor@{ subject -> if (subject !is TSubject) return@interceptor @Suppress("UNCHECKED_CAST") val reinterpret = this as? PipelineContext<TSubject, TContext> reinterpret?.block(subject) } } /** * Represents an interceptor type which is a suspend extension function for a context */ public typealias PipelineInterceptor<TSubject, TContext> = suspend PipelineContext<TSubject, TContext>.(TSubject) -> Unit
apache-2.0
661cd1c4b75f811bd5bf443c96b989cb
32.177291
118
0.625758
5.402206
false
false
false
false
marius-m/wt4
remote/src/main/java/lt/markmerkk/worklogs/JiraWorklogInteractor.kt
1
7070
package lt.markmerkk.worklogs import lt.markmerkk.* import lt.markmerkk.entities.Log import lt.markmerkk.entities.RemoteData import lt.markmerkk.entities.Ticket import lt.markmerkk.tickets.JiraTicketSearch import lt.markmerkk.utils.TimedCommentStamper import net.rcarz.jiraclient.WorkLog import org.jetbrains.annotations.TestOnly import org.joda.time.DateTime import org.joda.time.LocalDate import org.slf4j.LoggerFactory import rx.Emitter import rx.Observable import rx.Single class JiraWorklogInteractor( private val jiraClientProvider: JiraClientProvider, private val timeProvider: TimeProvider, private val userSettings: UserSettings ) { /** * Fetches worklogs for time gap. The worklogs returned will exceed [startDate] and [endDate] * as it'll bind 1:1 worklogs with their related issues */ fun searchWorklogs( fetchTime: DateTime, jql: String, startDate: LocalDate, endDate: LocalDate ): Observable<Pair<Ticket, List<Log>>> { return Observable.create( JiraWorklogEmitter( jiraClientProvider = jiraClientProvider, jql = jql, searchFields = JiraTicketSearch.TICKET_SEARCH_FIELDS .joinToString(separator = ","), start = startDate, end = endDate ), Emitter.BackpressureMode.BUFFER ).map { issueWorklogPair -> val issue = issueWorklogPair.issue val assigneeAsUser = issue.assignee?.toJiraUser() ?: JiraUser.asEmpty() val reporterAsuser = issue.reporter?.toJiraUser() ?: JiraUser.asEmpty() val ticket = Ticket.fromRemoteData( code = issue.key, description = issue.summary, status = issue.status?.name ?: "", assigneeName = assigneeAsUser.identifierAsString(), reporterName = reporterAsuser.identifierAsString(), isWatching = issue.watches?.isWatching ?: false, parentCode = issue.parent?.key ?: "", remoteData = RemoteData.fromRemote( fetchTime = fetchTime.millis, url = issue.url ) ) val activeUserIdentifier = userSettings.jiraUser().identifierAsString() val worklogs = issueWorklogPair.worklogs .filter { isCurrentUserLog( activeIdentifier = activeUserIdentifier, worklog = it ) } .map { workLog -> mapRemoteToLocalWorklog( timeProvider = timeProvider, fetchTime = fetchTime, ticket = ticket, remoteWorkLog = workLog, ) } logger.debug("Remapping ${ticket.code.code} JIRA worklogs to Log (${worklogs.size} / ${issueWorklogPair.worklogs.size})") ticket to worklogs } } /** * Uploads a worklog. Returns [Log] with uploaded remote data * Will throw an exception in the stream if worklog not eligible for upload * @throws JiraException whenever upload fails * @throws IllegalArgumentException whenever worklog is not valid */ // todo: Each worklog upload will create do multiple requests to jira. This can be optimized fun uploadWorklog( fetchTime: DateTime, log: Log ): Single<Log> { return Single.defer { val jiraClient = jiraClientProvider.client() val issue = jiraClient.getIssue(log.code.code) val commentWithTimeStamp = TimedCommentStamper .addStamp(log.time.start, log.time.end, log.comment) val remoteWorklog = issue.addWorkLog( commentWithTimeStamp, log.time.start, log.time.duration.standardSeconds ) val noStampRemoteComment = TimedCommentStamper .removeStamp(remoteWorklog.comment) val logAsRemote = log.appendRemoteData( timeProvider, code = issue.key, started = remoteWorklog.started, comment = noStampRemoteComment, timeSpentSeconds = remoteWorklog.timeSpentSeconds, fetchTime = fetchTime, url = remoteWorklog.url ) Single.just(logAsRemote) } } /** * Deletes worklog * Will throw an exception in the stream if worklog not eligable for upload * @throws JiraException whenever worklog deletion fails * @throws IllegalArgumentException whenever worklog is not valid */ fun delete( log: Log ): Single<Long> { return Single.defer { val remoteId = log.remoteData?.remoteId ?: throw IllegalArgumentException("Cannot find worklog id") val jiraClient = jiraClientProvider.client() val issue = jiraClient.getIssue(log.code.code) issue.removeWorklog(remoteId.toString()) Single.just(remoteId) } } companion object { private val logger = LoggerFactory.getLogger(Tags.JIRA) fun isCurrentUserLog( activeIdentifier: String, worklog: WorkLog ): Boolean { val jiraUser = worklog.author.toJiraUser() if (jiraUser.isEmpty() || activeIdentifier.isEmpty()) { return false } return activeIdentifier.equals(jiraUser.name, ignoreCase = true) || activeIdentifier.equals(jiraUser.displayName, ignoreCase = true) || activeIdentifier.equals(jiraUser.email, ignoreCase = true) || activeIdentifier.equals(jiraUser.accountId, ignoreCase = true) } @TestOnly internal fun mapRemoteToLocalWorklog( timeProvider: TimeProvider, fetchTime: DateTime, ticket: Ticket, remoteWorkLog: WorkLog, ): Log { val comment: String = remoteWorkLog.comment ?: "" val noStampComment = TimedCommentStamper.removeStamp(comment) val jiraUser = remoteWorkLog.author.toJiraUser() return Log.createFromRemoteData( timeProvider = timeProvider, code = ticket.code.code, comment = noStampComment, started = remoteWorkLog.started, timeSpentSeconds = remoteWorkLog.timeSpentSeconds, fetchTime = fetchTime, url = remoteWorkLog.url, author = jiraUser.identifierAsString() ) } } }
apache-2.0
9ae930887d295fc29a1a82c6a25a78f2
39.176136
133
0.566337
5.58011
false
false
false
false
emanuelpalm/palm-compute
core/src/main/java/se/ltu/emapal/compute/Computer.kt
1
5017
package se.ltu.emapal.compute import rx.Observable import rx.lang.kotlin.PublishSubject import se.ltu.emapal.compute.io.ComputeClient import java.io.Closeable import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger /** * A client computer. * * Receives compute instructions via some [ComputeClient], executes them using internally managed * threads, and reports any results of relevance to its connected compute service. * * @param client Client used to communication with some compute service, providing tasks. * @param contextFactory Function used to instantiate new [ComputeContext]s. * @param contextThreads The amount of [ComputeContext]s to create, each given its own thread. */ class Computer( val client: ComputeClient, contextFactory: () -> ComputeContext, private val contextThreads: Int = 1 ) : Closeable { private val threadPool = Executors.newFixedThreadPool(contextThreads) private val threadQueues = Array(contextThreads, { ConcurrentLinkedQueue<(ComputeContext) -> Unit>() }) private val sharedQueue = ConcurrentLinkedQueue<(ComputeContext) -> Unit>() private val isClosed = AtomicBoolean(false) private val whenExceptionSubject = PublishSubject<Pair<Int, Throwable>>() private val whenLambdaCountSubject = PublishSubject<Int>() private val whenBatchPendingCountSubject = PublishSubject<Int>() private val whenBatchProcessedCountSubject = PublishSubject<Int>() private val lambdaCount = AtomicInteger(0) private val batchPendingCount = AtomicInteger(0) private val batchProcessedCount = AtomicInteger(0) init { // Creates one thread and work queue for each created context. (0..(contextThreads - 1)).forEach { index -> val context = contextFactory() val contextQueue = threadQueues[index] threadPool.execute({ while (!isClosed.get()) { try { val contextTask = contextQueue.poll() if (contextTask != null) { contextTask.invoke(context) continue } val stolenTask = sharedQueue.poll() if (stolenTask != null) { stolenTask.invoke(context) continue } Thread.sleep(250) } catch (e: Throwable) { whenExceptionSubject.onNext(Pair(index, e)) } } context.close() }) } // Provides received lambdas via personal queues to each context thread. client.whenLambda.subscribe { lambda -> threadQueues.forEach { queue -> queue.add { context -> context.register(lambda).let { it.ifValue { whenLambdaCountSubject.onNext(lambdaCount.incrementAndGet()) } it.ifError { client.submit(it) } } } } } // Provides received batches via shared queue to first available context thread. client.whenBatch.subscribe { batch -> whenBatchPendingCountSubject.onNext(batchPendingCount.incrementAndGet()) sharedQueue.add { context -> context.process(batch).let { it.ifValue { client.submit(it) whenBatchProcessedCountSubject.onNext(batchProcessedCount.incrementAndGet()) } it.ifError { client.submit(it) } whenBatchPendingCountSubject.onNext(batchPendingCount.decrementAndGet()) } } } } /** Publishes context thread exceptions, with the first pair member being context ID. */ val whenException: Observable<Pair<Int, Throwable>> get() = whenExceptionSubject /** Publishes the amount of registered lambda functions. */ val whenLambdaCount: Observable<Int> get() = whenLambdaCountSubject.map { it / contextThreads } /** Publishes the amount of received batches pending for processing. */ val whenBatchPendingCount: Observable<Int> get() = whenBatchPendingCountSubject /** Publishes the amount of received batches that have been processed and returned. */ val whenBatchProcessedCount: Observable<Int> get() = whenBatchProcessedCountSubject override fun close() { if (isClosed.compareAndSet(false, true)) { threadPool.shutdown() whenExceptionSubject.onCompleted() whenLambdaCountSubject.onCompleted() whenBatchPendingCountSubject.onCompleted() whenBatchProcessedCountSubject.onCompleted() } } }
mit
b28bdeef4e4f3bfa389738bb1a19257e
39.144
107
0.617899
5.611857
false
false
false
false
pureal-code/pureal-os
android.backend/src/net/pureal/android/backend/GlShader.kt
1
1051
package net.pureal.android.backend import android.opengl.GLES20 class GlShader(val vertexShaderCode: String, val fragmentShaderCode: String) { private var createdProgram : Int? = null fun useProgram() : Int { val program = createdProgram ?: createProgram() GLES20.glUseProgram(program) return program } private fun createProgram(): Int { val vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode) val fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode) val program = GLES20.glCreateProgram() GLES20.glAttachShader(program, vertexShader) GLES20.glAttachShader(program, fragmentShader) GLES20.glLinkProgram(program) createdProgram = program return program } private fun loadShader(shaderType: Int, shaderCode: String): Int { val shader = GLES20.glCreateShader(shaderType) GLES20.glShaderSource(shader, shaderCode) GLES20.glCompileShader(shader) return shader; } }
bsd-3-clause
52a16699d0a2c4e9ef950b93b00f7c3a
32.935484
86
0.697431
4.821101
false
false
false
false
iSoron/uhabits
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/models/ModelFactory.kt
1
1778
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.core.models import org.isoron.uhabits.core.database.Repository import org.isoron.uhabits.core.models.sqlite.records.EntryRecord import org.isoron.uhabits.core.models.sqlite.records.HabitRecord /** * Interface implemented by factories that provide concrete implementations of * the core model classes. */ interface ModelFactory { fun buildHabit(): Habit { val scores = buildScoreList() val streaks = buildStreakList() return Habit( scores = scores, streaks = streaks, originalEntries = buildOriginalEntries(), computedEntries = buildComputedEntries(), ) } fun buildComputedEntries(): EntryList fun buildOriginalEntries(): EntryList fun buildHabitList(): HabitList fun buildScoreList(): ScoreList fun buildStreakList(): StreakList fun buildHabitListRepository(): Repository<HabitRecord> fun buildRepetitionListRepository(): Repository<EntryRecord> }
gpl-3.0
7987b7d4eb19db298ec20122dd28721c
36.020833
78
0.727068
4.476071
false
false
false
false
nlgcoin/guldencoin-official
src/frontend/android/unity_wallet/app/src/main/java/com/gulden/unity_wallet/BackgroundSync.kt
2
6186
// Copyright (c) 2018 The Gulden developers // Authored by: Willem de Jonge ([email protected]) // Distributed under the GULDEN software license, see the accompanying // file COPYING package com.gulden.unity_wallet import android.app.* import android.content.Context import android.content.Intent import android.os.Build import android.os.IBinder import androidx.core.app.NotificationCompat import android.util.Log import android.content.BroadcastReceiver import android.os.SystemClock.sleep import androidx.preference.PreferenceManager import androidx.core.content.ContextCompat import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import androidx.work.Worker import androidx.work.WorkerParameters import kotlinx.coroutines.* import org.jetbrains.anko.runOnUiThread import java.util.concurrent.TimeUnit import kotlin.coroutines.CoroutineContext private const val TAG = "background_sync" const val GULDEN_PERIODIC_SYNC = "GULDEN_PERIODIC_SYNC" fun setupBackgroundSync(context: Context) { // get syncType from preferences val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) val syncType = sharedPreferences.getString("preference_background_sync", context.getString(R.string.background_sync_default))!! Log.i(TAG, "Starting background sync: $syncType") val serviceIntent = Intent(context, SyncService::class.java) when (syncType) { "BACKGROUND_SYNC_OFF" -> { context.stopService(serviceIntent) WorkManager.getInstance().cancelAllWorkByTag(GULDEN_PERIODIC_SYNC) } "BACKGROUND_SYNC_DAILY" -> { context.stopService(serviceIntent) WorkManager.getInstance().cancelAllWorkByTag(GULDEN_PERIODIC_SYNC) val work = PeriodicWorkRequestBuilder<SyncWorker>(24, TimeUnit.HOURS) .addTag(GULDEN_PERIODIC_SYNC) .build() WorkManager.getInstance().enqueue(work) } "BACKGROUND_SYNC_CONTINUOUS" -> { ContextCompat.startForegroundService(context, serviceIntent) } } } private var NOTIFICATION_ID_FOREGROUND_SERVICE = 2 class SyncService : Service(), UnityCore.Observer { override fun onBind(intent: Intent?): IBinder? { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun syncProgressChanged(percent: Float) { Log.i(TAG, "sync progress = $percent") if (builder != null) { val b: NotificationCompat.Builder = builder!! builder!!.setContentText("progress $percent") val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(NOTIFICATION_ID_FOREGROUND_SERVICE, b.build()) } } private var builder: NotificationCompat.Builder? = null private val channelID = "com.gulden.unity_wallet.service.channel" private fun startInForeground() { val notificationIntent = Intent(this, WalletActivity::class.java) val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationChannel = NotificationChannel(channelID, getString(R.string.notification_service_channel_name), NotificationManager.IMPORTANCE_LOW) (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(notificationChannel) notificationChannel.description = getString(R.string.notification_service_channel_description) notificationChannel.enableLights(false) notificationChannel.setShowBadge(false) } builder = NotificationCompat.Builder(this, channelID) .setContentTitle("Gulden") .setTicker("Gulden") .setContentText("Gulden") .setSmallIcon(R.drawable.ic_g_logo) .setContentIntent(pendingIntent) .setOngoing(true) val notification = builder?.build() startForeground(NOTIFICATION_ID_FOREGROUND_SERVICE, notification) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { startInForeground() return super.onStartCommand(intent, flags, startId) } override fun onCreate() { super.onCreate() UnityCore.instance.addObserver(this, fun (callback:() -> Unit) { runOnUiThread { callback() }}) UnityCore.instance.startCore() } override fun onDestroy() { super.onDestroy() UnityCore.instance.removeObserver(this) } } class BootReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (Intent.ACTION_BOOT_COMPLETED == intent.action) { setupBackgroundSync(context) } } } class SyncWorker(context : Context, params : WorkerParameters) : UnityCore.Observer, Worker(context, params), CoroutineScope { override val coroutineContext: CoroutineContext = Dispatchers.Main + SupervisorJob() override fun syncProgressChanged(percent: Float) { Log.i(TAG, "periodic sync progress = $percent") } override fun doWork(): Result { Log.i(TAG, "Periodic sync started") UnityCore.instance.addObserver(this) UnityCore.instance.startCore() // wait for wallet ready (or get killed by the OS which ever comes first) try { runBlocking { UnityCore.instance.walletReady.await() } } catch (e: CancellationException) { return Result.retry() } // wait until sync is complete (or get killed by the OS which ever comes first) while (UnityCore.instance.progressPercent < 100.0) { sleep(5000) } Log.i(TAG, "Periodic sync finished") // Indicate success or failure with your return value: return Result.success() // (Returning RETRY tells WorkManager to try this task again // later; FAILURE says not to try again.) } }
mit
346cdeb582de8904b43af7ffc34ee73d
33.176796
159
0.682994
4.929084
false
false
false
false
nlgcoin/guldencoin-official
src/frontend/android/unity_wallet/app/src/main/java/com/gulden/unity_wallet/main_activity_fragments/MutationFragment.kt
2
3536
// Copyright (c) 2018 The Gulden developers // Authored by: Malcolm MacLeod ([email protected]) // Distributed under the GULDEN software license, see the accompanying // file COPYING package com.gulden.unity_wallet.main_activity_fragments import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.gulden.jniunifiedbackend.ILibraryController import com.gulden.jniunifiedbackend.MutationRecord import com.gulden.jniunifiedbackend.TransactionRecord import com.gulden.unity_wallet.* import com.gulden.unity_wallet.ui.MutationAdapter import com.gulden.unity_wallet.util.AppBaseFragment import com.gulden.unity_wallet.util.invokeNowOrOnSuccessfulCompletion import kotlinx.android.synthetic.main.fragment_mutation.* import kotlinx.coroutines.* import org.jetbrains.anko.support.v4.runOnUiThread class MutationFragment : AppBaseFragment(), UnityCore.Observer, CoroutineScope { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_mutation, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // if wallet ready setup list immediately so list does not briefly flash empty content and // scroll position is kept on switching from and to this fragment UnityCore.instance.walletReady.invokeNowOrOnSuccessfulCompletion(this) { mutationList?.emptyView = emptyMutationListView val mutations = ILibraryController.getMutationHistory() val adapter = MutationAdapter([email protected]!!, mutations) mutationList.adapter = adapter mutationList.setOnItemClickListener { parent, _, position, _ -> val mutation = parent.adapter.getItem(position) as MutationRecord val intent = Intent([email protected], TransactionInfoActivity::class.java) intent.putExtra(TransactionInfoActivity.EXTRA_TRANSACTION, mutation.txHash) startActivity(intent) } launch { try { (mutationList.adapter as MutationAdapter).updateRate(fetchCurrencyRate(localCurrency.code)) } catch (e: Throwable) { // silently ignore failure of getting rate here } } } } override fun onAttach(context: Context) { UnityCore.instance.addObserver(this) super.onAttach(context) } override fun onDetach() { UnityCore.instance.removeObserver(this) super.onDetach() } override fun onNewMutation(mutation: MutationRecord, selfCommitted: Boolean) { //TODO: Update only the single mutation we have received val mutations = ILibraryController.getMutationHistory() runOnUiThread { val adapter = mutationList.adapter as MutationAdapter adapter.updateDataSource(mutations) } } override fun updatedTransaction(transaction: TransactionRecord) { //TODO: Update only the single mutation we have received val mutations = ILibraryController.getMutationHistory() runOnUiThread { val adapter = mutationList.adapter as MutationAdapter adapter.updateDataSource(mutations) } } }
mit
673068bfcac0d83c75d734d721362940
36.617021
114
0.707296
5.058655
false
false
false
false
google/ground-android
ground/src/main/java/com/google/android/ground/ui/editsubmission/PhotoTaskViewModel.kt
1
3936
/* * 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.android.ground.ui.editsubmission import android.content.res.Resources import android.net.Uri import androidx.lifecycle.LiveData import androidx.lifecycle.LiveDataReactiveStreams import androidx.lifecycle.MutableLiveData import com.google.android.ground.model.submission.TextTaskData.Companion.fromString import com.google.android.ground.model.task.Task import com.google.android.ground.persistence.remote.firestore.FirestoreStorageManager.Companion.getRemoteMediaPath import com.google.android.ground.repository.UserMediaRepository import com.google.android.ground.rx.annotations.Hot import com.google.android.ground.ui.editsubmission.EditSubmissionViewModel.PhotoResult import java.io.File import java.io.IOException import javax.inject.Inject import timber.log.Timber class PhotoTaskViewModel @Inject constructor(private val userMediaRepository: UserMediaRepository, resources: Resources) : AbstractTaskViewModel(resources) { val uri: LiveData<Uri> = LiveDataReactiveStreams.fromPublisher( detailsTextFlowable.switchMapSingle { userMediaRepository.getDownloadUrl(it) } ) val isPhotoPresent: LiveData<Boolean> = LiveDataReactiveStreams.fromPublisher(detailsTextFlowable.map { it.isNotEmpty() }) private var surveyId: String? = null private var submissionId: String? = null private val showDialogClicks: @Hot(replays = true) MutableLiveData<Task> = MutableLiveData() private val editable: @Hot(replays = true) MutableLiveData<Boolean> = MutableLiveData(false) fun onShowPhotoSelectorDialog() { showDialogClicks.value = task } fun getShowDialogClicks(): LiveData<Task> = showDialogClicks fun setEditable(enabled: Boolean) { editable.postValue(enabled) } fun isEditable(): LiveData<Boolean> = editable fun updateResponse(value: String) { setResponse(fromString(value)) } fun setSurveyId(surveyId: String?) { this.surveyId = surveyId } fun setSubmissionId(submissionId: String?) { this.submissionId = submissionId } fun onPhotoResult(photoResult: PhotoResult) { if (photoResult.isHandled()) { return } if (surveyId == null || submissionId == null) { Timber.e("surveyId or submissionId not set") return } if (!photoResult.hasTaskId(task.id)) { // Update belongs to another task. return } photoResult.setHandled(true) if (photoResult.isEmpty) { clearResponse() Timber.v("Photo cleared") return } try { val imageFile = getFileFromResult(photoResult) val filename = imageFile.name val path = imageFile.absolutePath // Add image to gallery. userMediaRepository.addImageToGallery(path, filename) // Update taskData. val remoteDestinationPath = getRemoteMediaPath(surveyId!!, submissionId!!, filename) updateResponse(remoteDestinationPath) } catch (e: IOException) { // TODO: Report error. Timber.e(e, "Failed to save photo") } } @Throws(IOException::class) private fun getFileFromResult(result: PhotoResult): File { if (result.bitmap.isPresent) { return userMediaRepository.savePhoto(result.bitmap.get(), result.taskId) } if (result.path.isPresent) { return File(result.path.get()) } throw IllegalStateException("PhotoResult is empty") } }
apache-2.0
a666671c81449669fcaeee11f6cb0765
31.262295
114
0.740346
4.368479
false
false
false
false
JetBrains/spek
spek-ide-plugin-interop-jvm/src/main/kotlin/org/spekframework/ide/ServiceMessageAdapter.kt
1
3853
package org.spekframework.ide import org.spekframework.spek2.runtime.execution.ExecutionListener import org.spekframework.spek2.runtime.execution.ExecutionResult import org.spekframework.spek2.runtime.scope.GroupScopeImpl import org.spekframework.spek2.runtime.scope.Path import org.spekframework.spek2.runtime.scope.TestScopeImpl import java.io.CharArrayWriter import java.io.PrintWriter class ServiceMessageAdapter: ExecutionListener { private val durations = mutableMapOf<Path, Long>() override fun executionStart() { } override fun executionFinish() { durations.clear() } override fun testExecutionStart(test: TestScopeImpl) { durations[test.path] = System.currentTimeMillis() out("testStarted name='${test.path.name.toServiceMessageSafeString()}' locationHint='spek://${test.path.serialize()}'") } override fun testExecutionFinish(test: TestScopeImpl, result: ExecutionResult) { val name = test.path.name.toServiceMessageSafeString() val duration = System.currentTimeMillis() - durations[test.path]!! if (result is ExecutionResult.Failure) { val exceptionDetails = getExceptionDetails(result) out("testFailed name='$name' duration='$duration' message='${exceptionDetails.first}' details='${exceptionDetails.second}'") } out("testFinished name='$name' duration='$duration'") } override fun testIgnored(test: TestScopeImpl, reason: String?) { val name = test.path.name.toServiceMessageSafeString() out("testIgnored name='$name' ignoreComment='${reason ?: "no reason provided"}'") out("testFinished name='$name'") } override fun groupExecutionStart(group: GroupScopeImpl) { out("testSuiteStarted name='${group.path.name.toServiceMessageSafeString()}' locationHint='spek://${group.path.serialize()}'") } override fun groupExecutionFinish(group: GroupScopeImpl, result: ExecutionResult) { val name = group.path.name.toServiceMessageSafeString() if (result is ExecutionResult.Failure) { val exceptionDetails = getExceptionDetails(result) // fake a child test out("testStarted name='$name'") out("testFailed name='$name' message='${exceptionDetails.first}' details='${exceptionDetails.second}'") out("testFinished name='$name'") } out("testSuiteFinished name='$name'") } override fun groupIgnored(group: GroupScopeImpl, reason: String?) { val name = group.path.name.toServiceMessageSafeString() out("testIgnored name='$name' ignoreComment='${reason ?: "no reason provided"}'") out("testFinished name='$name'") } private fun getExceptionDetails(result: ExecutionResult.Failure): Pair<String?, String> { val throwable = result.cause val writer = CharArrayWriter() throwable.printStackTrace(PrintWriter(writer)) val details = CharArrayWriter().let { throwable.printStackTrace(PrintWriter(it)) it.toString().toServiceMessageSafeString() } val message = throwable.message?.toServiceMessageSafeString() return message to details } private fun String.toServiceMessageSafeString(): String { return this.replace("|", "||") .replace("\n", "|n") .replace("\r", "|r") .replace("'", "|'") .replace("[", "|[") .replace("]", "|]") .replace(Regex("""\\u(\d\d\d\d)""")) { "|0x${it.groupValues[1]}" } } private fun out(event: String) { /* ensure service message has it's own line*/ println() println("##teamcity[$event]") } }
bsd-3-clause
70c89be32019338aa251970e045ac529
38.557895
136
0.636647
5.036601
false
true
false
false
mdanielwork/intellij-community
platform/lang-impl/src/com/intellij/ide/actions/GotoClassPresentationUpdater.kt
4
2178
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions import com.intellij.ide.IdeBundle import com.intellij.lang.IdeLanguageCustomization import com.intellij.navigation.ChooseByNameRegistry import com.intellij.navigation.GotoClassContributor import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.application.PreloadingActivity import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.text.StringUtil class GotoClassPresentationUpdater : PreloadingActivity() { override fun preload(indicator: ProgressIndicator) { //we need to change the template presentation to show the proper text for the action in Settings | Keymap val presentation = ActionManager.getInstance().getAction("GotoClass").templatePresentation presentation.text = getActionTitle() + "..." presentation.description = IdeBundle.message("go.to.class.action.description", getElementKinds().joinToString("/")) } companion object { @JvmStatic fun getActionTitle(): String { val primaryIdeLanguages = IdeLanguageCustomization.getInstance().primaryIdeLanguages val mainContributor = ChooseByNameRegistry.getInstance().classModelContributors .filterIsInstance(GotoClassContributor::class.java) .firstOrNull { it.elementLanguage in primaryIdeLanguages } val text = mainContributor?.elementKind ?: IdeBundle.message("go.to.class.kind.text") return StringUtil.capitalizeWords(text, " /", true, true) } @JvmStatic fun getElementKinds(): Set<String> { val primaryIdeLanguages = IdeLanguageCustomization.getInstance().primaryIdeLanguages return ChooseByNameRegistry.getInstance().classModelContributors .filterIsInstance(GotoClassContributor::class.java) .sortedBy { val index = primaryIdeLanguages.indexOf(it.elementLanguage) if (index == -1) primaryIdeLanguages.size else index } .flatMapTo(LinkedHashSet()) { it.elementKind.split("/") } } } }
apache-2.0
9b173cf627803571b3b1cde753e5e8c7
48.5
140
0.747016
5.088785
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinFunctionCallUsage.kt
3
26640
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.util.PsiTreeUtil import com.intellij.usageView.UsageInfo import com.intellij.util.containers.ContainerUtil import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeInsight.shorten.addDelayedImportRequest import org.jetbrains.kotlin.idea.core.moveFunctionLiteralOutsideParentheses import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.intentions.RemoveEmptyParenthesesFromLambdaCallIntention import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinParameterInfo import org.jetbrains.kotlin.idea.refactoring.changeSignature.isInsideOfCallerBody import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.createNameCounterpartMap import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinIntroduceVariableHandler import org.jetbrains.kotlin.idea.refactoring.replaceListPsiAndKeepDelimiters import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.* import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.* import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.util.kind import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.kotlin.utils.sure class KotlinFunctionCallUsage( element: KtCallElement, private val callee: KotlinCallableDefinitionUsage<*>, forcedResolvedCall: ResolvedCall<*>? = null ) : KotlinUsageInfo<KtCallElement>(element) { private val context = element.analyze(BodyResolveMode.FULL) private val resolvedCall = forcedResolvedCall ?: element.getResolvedCall(context) private val skipUnmatchedArgumentsCheck = forcedResolvedCall != null override fun processUsage(changeInfo: KotlinChangeInfo, element: KtCallElement, allUsages: Array<out UsageInfo>): Boolean { processUsageAndGetResult(changeInfo, element, allUsages) return true } fun processUsageAndGetResult( changeInfo: KotlinChangeInfo, element: KtCallElement, allUsages: Array<out UsageInfo>, skipRedundantArgumentList: Boolean = false, ): KtElement { if (shouldSkipUsage(element)) return element var result: KtElement = element changeNameIfNeeded(changeInfo, element) if (element.valueArgumentList == null && changeInfo.isParameterSetOrOrderChanged && element.lambdaArguments.isNotEmpty()) { val anchor = element.typeArgumentList ?: element.calleeExpression if (anchor != null) { element.addAfter(KtPsiFactory(element).createCallArguments("()"), anchor) } } if (element.valueArgumentList != null) { if (changeInfo.isParameterSetOrOrderChanged) { result = updateArgumentsAndReceiver(changeInfo, element, allUsages, skipRedundantArgumentList) } else { changeArgumentNames(changeInfo, element) } } if (changeInfo.getNewParametersCount() == 0 && element is KtSuperTypeCallEntry) { val enumEntry = element.getStrictParentOfType<KtEnumEntry>() if (enumEntry != null && enumEntry.initializerList == element.parent) { val initializerList = enumEntry.initializerList enumEntry.deleteChildRange(enumEntry.getColon() ?: initializerList, initializerList) } } return result } private fun shouldSkipUsage(element: KtCallElement): Boolean { // TODO: We probable need more clever processing of invalid calls, but for now default to Java-like behaviour if (resolvedCall == null && element !is KtSuperTypeCallEntry) return true if (resolvedCall == null || resolvedCall.isReallySuccess()) return false // TODO: investigate why arguments are not recorded for enum constructor call if (element is KtSuperTypeCallEntry && element.parent.parent is KtEnumEntry && element.valueArguments.isEmpty()) return false if (skipUnmatchedArgumentsCheck) return false if (!resolvedCall.call.valueArguments.all { resolvedCall.getArgumentMapping(it) is ArgumentMatch }) return true val arguments = resolvedCall.valueArguments return !resolvedCall.resultingDescriptor.valueParameters.all { arguments.containsKey(it) } } private val isPropertyJavaUsage: Boolean get() { val calleeElement = this.callee.element if (calleeElement !is KtProperty && calleeElement !is KtParameter) return false return resolvedCall?.resultingDescriptor is JavaMethodDescriptor } private fun changeNameIfNeeded(changeInfo: KotlinChangeInfo, element: KtCallElement) { if (!changeInfo.isNameChanged) return val callee = element.calleeExpression as? KtSimpleNameExpression ?: return var newName = changeInfo.newName if (isPropertyJavaUsage) { val currentName = callee.getReferencedName() if (JvmAbi.isGetterName(currentName)) newName = JvmAbi.getterName(newName) else if (JvmAbi.isSetterName(currentName)) newName = JvmAbi.setterName(newName) } callee.replace(KtPsiFactory(project).createSimpleName(newName)) } private fun getReceiverExpressionIfMatched( receiverValue: ReceiverValue?, originalDescriptor: DeclarationDescriptor, psiFactory: KtPsiFactory ): KtExpression? { if (receiverValue == null) return null // Replace descriptor of extension function/property with descriptor of its receiver // to simplify checking against receiver value in the corresponding resolved call val adjustedDescriptor = if (originalDescriptor is CallableDescriptor && originalDescriptor !is ReceiverParameterDescriptor) { originalDescriptor.extensionReceiverParameter ?: return null } else originalDescriptor val currentIsExtension = resolvedCall!!.extensionReceiver == receiverValue val originalIsExtension = adjustedDescriptor is ReceiverParameterDescriptor && adjustedDescriptor.value is ExtensionReceiver if (currentIsExtension != originalIsExtension) return null val originalType = when (adjustedDescriptor) { is ReceiverParameterDescriptor -> adjustedDescriptor.type is ClassDescriptor -> adjustedDescriptor.defaultType else -> null } if (originalType == null || !KotlinTypeChecker.DEFAULT.isSubtypeOf(receiverValue.type, originalType)) return null return getReceiverExpression(receiverValue, psiFactory) } private fun needSeparateVariable(element: PsiElement): Boolean { return when { element is KtConstantExpression || element is KtThisExpression || element is KtSimpleNameExpression -> false element is KtBinaryExpression && OperatorConventions.ASSIGNMENT_OPERATIONS.contains(element.operationToken) -> true element is KtUnaryExpression && OperatorConventions.INCREMENT_OPERATIONS.contains(element.operationToken) -> true element is KtCallExpression -> element.getResolvedCall(context)?.resultingDescriptor is ConstructorDescriptor else -> element.children.any { needSeparateVariable(it) } } } private fun substituteReferences( expression: KtExpression, referenceMap: Map<PsiReference, DeclarationDescriptor>, psiFactory: KtPsiFactory ): KtExpression { if (referenceMap.isEmpty() || resolvedCall == null) return expression var newExpression = expression.copy() as KtExpression val nameCounterpartMap = createNameCounterpartMap(expression, newExpression) val valueArguments = resolvedCall.valueArguments val replacements = ArrayList<Pair<KtExpression, KtExpression>>() loop@ for ((ref, descriptor) in referenceMap.entries) { var argumentExpression: KtExpression? val addReceiver: Boolean if (descriptor is ValueParameterDescriptor) { // Ordinary parameter // Find corresponding parameter in the current function (may differ from 'descriptor' if original function is part of override hierarchy) val parameterDescriptor = resolvedCall.resultingDescriptor.valueParameters[descriptor.index] val resolvedValueArgument = valueArguments[parameterDescriptor] as? ExpressionValueArgument ?: continue val argument = resolvedValueArgument.valueArgument ?: continue addReceiver = false argumentExpression = argument.getArgumentExpression() } else { addReceiver = descriptor !is ReceiverParameterDescriptor argumentExpression = getReceiverExpressionIfMatched(resolvedCall.extensionReceiver, descriptor, psiFactory) ?: getReceiverExpressionIfMatched(resolvedCall.dispatchReceiver, descriptor, psiFactory) } if (argumentExpression == null) continue if (needSeparateVariable(argumentExpression) && PsiTreeUtil.getNonStrictParentOfType( element, KtConstructorDelegationCall::class.java, KtSuperTypeListEntry::class.java, KtParameter::class.java ) == null ) { KotlinIntroduceVariableHandler.doRefactoring( project, null, argumentExpression, isVar = false, occurrencesToReplace = listOf(argumentExpression), onNonInteractiveFinish = { argumentExpression = psiFactory.createExpression(it.name!!) }) } var expressionToReplace: KtExpression = nameCounterpartMap[ref.element] ?: continue val parent = expressionToReplace.parent if (parent is KtThisExpression) { expressionToReplace = parent } if (addReceiver) { val callExpression = expressionToReplace.getParentOfTypeAndBranch<KtCallExpression>(true) { calleeExpression } when { callExpression != null -> expressionToReplace = callExpression parent is KtOperationExpression && parent.operationReference == expressionToReplace -> continue@loop } val replacement = psiFactory.createExpression("${argumentExpression!!.text}.${expressionToReplace.text}") replacements.add(expressionToReplace to replacement) } else { replacements.add(expressionToReplace to argumentExpression!!) } } // Sort by descending offset so that call arguments are replaced before call itself ContainerUtil.sort(replacements, REVERSED_TEXT_OFFSET_COMPARATOR) for ((expressionToReplace, replacingExpression) in replacements) { val replaced = expressionToReplace.replaced(replacingExpression) if (expressionToReplace == newExpression) { newExpression = replaced } } return newExpression } class ArgumentInfo( val parameter: KotlinParameterInfo, val parameterIndex: Int, val resolvedArgument: ResolvedValueArgument?, val receiverValue: ReceiverValue? ) { private val mainValueArgument: ValueArgument? get() = resolvedArgument?.arguments?.firstOrNull() val wasNamed: Boolean get() = mainValueArgument?.isNamed() ?: false var name: String? = null private set fun makeNamed(callee: KotlinCallableDefinitionUsage<*>) { name = parameter.getInheritedName(callee) } fun shouldSkip() = parameter.defaultValue != null && mainValueArgument == null } private fun getResolvedValueArgument(oldIndex: Int): ResolvedValueArgument? { if (oldIndex < 0) return null val parameterDescriptor = resolvedCall!!.resultingDescriptor.valueParameters[oldIndex] return resolvedCall.valueArguments[parameterDescriptor] } private fun ArgumentInfo.getArgumentByDefaultValue( element: KtCallElement, allUsages: Array<out UsageInfo>, psiFactory: KtPsiFactory ): KtValueArgument { val isInsideOfCallerBody = element.isInsideOfCallerBody(allUsages) val defaultValueForCall = parameter.defaultValueForCall val argValue = when { isInsideOfCallerBody -> psiFactory.createExpression(parameter.name) defaultValueForCall != null -> substituteReferences( defaultValueForCall, parameter.defaultValueParameterReferences, psiFactory, ).asMarkedForShortening() else -> null } val argName = (if (isInsideOfCallerBody) null else name)?.let { Name.identifier(it) } return psiFactory.createArgument(argValue ?: psiFactory.createExpression("0"), argName).apply { if (argValue == null) { getArgumentExpression()?.delete() } } } private fun ExpressionReceiver.wrapInvalidated(element: KtCallElement): ExpressionReceiver = object : ExpressionReceiver by this { override val expression = element.getQualifiedExpressionForSelector()!!.receiverExpression } private fun updateArgumentsAndReceiver( changeInfo: KotlinChangeInfo, element: KtCallElement, allUsages: Array<out UsageInfo>, skipRedundantArgumentList: Boolean, ): KtElement { if (isPropertyJavaUsage) return updateJavaPropertyCall(changeInfo, element) val fullCallElement = element.getQualifiedExpressionForSelector() ?: element val oldArguments = element.valueArguments val newParameters = changeInfo.getNonReceiverParameters() val purelyNamedCall = element is KtCallExpression && oldArguments.isNotEmpty() && oldArguments.all { it.isNamed() } val newReceiverInfo = changeInfo.receiverParameterInfo val originalReceiverInfo = changeInfo.methodDescriptor.receiver val extensionReceiver = resolvedCall?.extensionReceiver val dispatchReceiver = resolvedCall?.dispatchReceiver // Do not add extension receiver to calls with explicit dispatch receiver except for objects if (newReceiverInfo != null && fullCallElement is KtQualifiedExpression && dispatchReceiver is ExpressionReceiver ) { if (isObjectReceiver(dispatchReceiver)) { //It's safe to replace object reference with a new receiver, but we shall import the function addDelayedImportRequest(changeInfo.method, element.containingKtFile) } else { return element } } val newArgumentInfos = newParameters.asSequence().withIndex().map { val (index, param) = it val oldIndex = param.oldIndex val resolvedArgument = if (oldIndex >= 0) getResolvedValueArgument(oldIndex) else null var receiverValue = if (param == originalReceiverInfo) extensionReceiver else null // Workaround for recursive calls where implicit extension receiver is transformed into ordinary value argument // Receiver expression retained in the original resolved call is no longer valid at this point if (receiverValue is ExpressionReceiver && !receiverValue.expression.isValid) { receiverValue = receiverValue.wrapInvalidated(element) } ArgumentInfo(param, index, resolvedArgument, receiverValue) }.toList() val lastParameterIndex = newParameters.lastIndex val canMixArguments = element.languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition) var firstNamedIndex = newArgumentInfos.firstOrNull { !canMixArguments && it.wasNamed || it.parameter.isNewParameter && it.parameter.defaultValue != null || it.resolvedArgument is VarargValueArgument && it.parameterIndex < lastParameterIndex }?.parameterIndex if (firstNamedIndex == null) { val lastNonDefaultArgIndex = (lastParameterIndex downTo 0).firstOrNull { !newArgumentInfos[it].shouldSkip() } ?: -1 firstNamedIndex = (0..lastNonDefaultArgIndex).firstOrNull { newArgumentInfos[it].shouldSkip() } } val lastPositionalIndex = if (firstNamedIndex != null) firstNamedIndex - 1 else lastParameterIndex val namedRange = lastPositionalIndex + 1..lastParameterIndex for ((index, argument) in newArgumentInfos.withIndex()) { if (purelyNamedCall || argument.wasNamed || index in namedRange) { argument.makeNamed(callee) } } val psiFactory = KtPsiFactory(element.project) val newArgumentList = psiFactory.createCallArguments("()").apply { for (argInfo in newArgumentInfos) { if (argInfo.shouldSkip()) continue val name = argInfo.name?.let { Name.identifier(it) } if (argInfo.receiverValue != null) { val receiverExpression = getReceiverExpression(argInfo.receiverValue, psiFactory) ?: continue addArgument(psiFactory.createArgument(receiverExpression, name)) continue } when (val resolvedArgument = argInfo.resolvedArgument) { null, is DefaultValueArgument -> addArgument(argInfo.getArgumentByDefaultValue(element, allUsages, psiFactory)) is ExpressionValueArgument -> { val valueArgument = resolvedArgument.valueArgument val newValueArgument: KtValueArgument = when { valueArgument == null -> argInfo.getArgumentByDefaultValue(element, allUsages, psiFactory) valueArgument is KtLambdaArgument -> psiFactory.createArgument(valueArgument.getArgumentExpression(), name) valueArgument is KtValueArgument && valueArgument.getArgumentName()?.asName == name -> valueArgument else -> psiFactory.createArgument(valueArgument.getArgumentExpression(), name) } addArgument(newValueArgument) } // TODO: Support Kotlin varargs is VarargValueArgument -> resolvedArgument.arguments.forEach { if (it is KtValueArgument) addArgument(it) } else -> return element } } } newArgumentList.arguments.singleOrNull()?.let { if (it.getArgumentExpression() == null) { newArgumentList.removeArgument(it) } } val lastOldArgument = oldArguments.lastOrNull() val lastNewParameter = newParameters.lastOrNull() val lastNewArgument = newArgumentList.arguments.lastOrNull() val oldLastResolvedArgument = getResolvedValueArgument(lastNewParameter?.oldIndex ?: -1) as? ExpressionValueArgument val lambdaArgumentNotTouched = lastOldArgument is KtLambdaArgument && oldLastResolvedArgument?.valueArgument == lastOldArgument val newLambdaArgumentAddedLast = lastNewParameter != null && lastNewParameter.isNewParameter && lastNewParameter.defaultValueForCall is KtLambdaExpression && lastNewArgument?.getArgumentExpression() is KtLambdaExpression && !lastNewArgument.isNamed() if (lambdaArgumentNotTouched) { newArgumentList.removeArgument(newArgumentList.arguments.last()) } else { val lambdaArguments = element.lambdaArguments if (lambdaArguments.isNotEmpty()) { element.deleteChildRange(lambdaArguments.first(), lambdaArguments.last()) } } val oldArgumentList = element.valueArgumentList.sure { "Argument list is expected: " + element.text } for (argument in replaceListPsiAndKeepDelimiters(changeInfo, oldArgumentList, newArgumentList) { arguments }.arguments) { if (argument.getArgumentExpression() == null) argument.delete() } var newElement: KtElement = element if (newReceiverInfo != originalReceiverInfo) { val replacingElement: PsiElement = if (newReceiverInfo != null) { val receiverArgument = getResolvedValueArgument(newReceiverInfo.oldIndex)?.arguments?.singleOrNull() val extensionReceiverExpression = receiverArgument?.getArgumentExpression() val defaultValueForCall = newReceiverInfo.defaultValueForCall val receiver = extensionReceiverExpression?.let { psiFactory.createExpression(it.text) } ?: defaultValueForCall?.asMarkedForShortening() ?: psiFactory.createExpression("_") psiFactory.createExpressionByPattern("$0.$1", receiver, element) } else { element.copy() } newElement = fullCallElement.replace(replacingElement) as KtElement } val newCallExpression = newElement.safeAs<KtExpression>()?.getPossiblyQualifiedCallExpression() if (!lambdaArgumentNotTouched && newLambdaArgumentAddedLast) { newCallExpression?.moveFunctionLiteralOutsideParentheses() } if (!skipRedundantArgumentList) { newCallExpression?.valueArgumentList?.let(RemoveEmptyParenthesesFromLambdaCallIntention::applyToIfApplicable) } newElement.flushElementsForShorteningToWaitList() return newElement } private fun isObjectReceiver(dispatchReceiver: ReceiverValue) = dispatchReceiver.safeAs<ClassValueReceiver>()?.classQualifier?.descriptor?.kind == ClassKind.OBJECT private fun changeArgumentNames(changeInfo: KotlinChangeInfo, element: KtCallElement) { for (argument in element.valueArguments) { val argumentName = argument.getArgumentName() val argumentNameExpression = argumentName?.referenceExpression ?: continue val oldParameterIndex = changeInfo.getOldParameterIndex(argumentNameExpression.getReferencedName()) ?: continue val newParameterIndex = if (changeInfo.receiverParameterInfo != null) oldParameterIndex + 1 else oldParameterIndex val parameterInfo = changeInfo.newParameters[newParameterIndex] changeArgumentName(argumentNameExpression, parameterInfo) } } private fun changeArgumentName(argumentNameExpression: KtSimpleNameExpression?, parameterInfo: KotlinParameterInfo) { val identifier = argumentNameExpression?.getIdentifier() ?: return val newName = parameterInfo.getInheritedName(callee) identifier.replace(KtPsiFactory(project).createIdentifier(newName)) } companion object { private val REVERSED_TEXT_OFFSET_COMPARATOR = Comparator<Pair<KtElement, KtElement>> { p1, p2 -> val offset1 = p1.first.startOffset val offset2 = p2.first.startOffset when { offset1 < offset2 -> 1 offset1 > offset2 -> -1 else -> 0 } } private fun updateJavaPropertyCall(changeInfo: KotlinChangeInfo, element: KtCallElement): KtElement { val newReceiverInfo = changeInfo.receiverParameterInfo val originalReceiverInfo = changeInfo.methodDescriptor.receiver if (newReceiverInfo == originalReceiverInfo) return element val arguments = element.valueArgumentList.sure { "Argument list is expected: " + element.text } val oldArguments = element.valueArguments val psiFactory = KtPsiFactory(element.project) val firstArgument = oldArguments.firstOrNull() as KtValueArgument? when { newReceiverInfo != null -> { val defaultValueForCall = newReceiverInfo.defaultValueForCall ?: psiFactory.createExpression("_") val newReceiverArgument = psiFactory.createArgument(defaultValueForCall, null, false) if (originalReceiverInfo != null) { firstArgument?.replace(newReceiverArgument) } else { arguments.addArgumentAfter(newReceiverArgument, null) } } firstArgument != null -> arguments.removeArgument(firstArgument) } return element } private fun getReceiverExpression(receiver: ReceiverValue, psiFactory: KtPsiFactory): KtExpression? { return when (receiver) { is ExpressionReceiver -> receiver.expression is ImplicitReceiver -> { val descriptor = receiver.declarationDescriptor val thisText = if (descriptor is ClassDescriptor && !DescriptorUtils.isAnonymousObject(descriptor)) { "this@" + descriptor.name.asString() } else { "this" } psiFactory.createExpression(thisText) } else -> null } } } }
apache-2.0
aa5f82b51e799252e15a3eb5b31635b0
47
167
0.673273
6.626866
false
false
false
false
TheMrMilchmann/lwjgl3
modules/lwjgl/spvc/src/templates/kotlin/spvc/templates/Spv.kt
1
78356
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package spvc.templates import org.lwjgl.generator.* val Spv = "Spv".nativeClass(Module.SPVC, prefix = "Spv", prefixConstant = "Spv", prefixMethod = "Spv") { documentation = "Enumeration tokens for SPIR-V." IntConstant("", "SPV_VERSION".."0x10600").noPrefix() IntConstant("", "SPV_REVISION".."1").noPrefix() IntConstant("", "MagicNumber".."0x07230203") IntConstant("", "Version".."0x00010600") IntConstant("", "Revision".."1") IntConstant("", "OpCodeMask".."0xffff") IntConstant("", "WordCountShift".."16") EnumConstant( "{@code SpvSourceLanguage}", "SourceLanguageUnknown".."0", "SourceLanguageESSL".."1", "SourceLanguageGLSL".."2", "SourceLanguageOpenCL_C".."3", "SourceLanguageOpenCL_CPP".."4", "SourceLanguageHLSL".."5", "SourceLanguageCPP_for_OpenCL".."6", "SourceLanguageSYCL".."7", "SourceLanguageMax".."0x7fffffff", ) EnumConstant( "{@code SpvExecutionModel}", "ExecutionModelVertex".."0", "ExecutionModelTessellationControl".."1", "ExecutionModelTessellationEvaluation".."2", "ExecutionModelGeometry".."3", "ExecutionModelFragment".."4", "ExecutionModelGLCompute".."5", "ExecutionModelKernel".."6", "ExecutionModelTaskNV".."5267", "ExecutionModelMeshNV".."5268", "ExecutionModelRayGenerationKHR".."5313", "ExecutionModelRayGenerationNV".."5313", "ExecutionModelIntersectionKHR".."5314", "ExecutionModelIntersectionNV".."5314", "ExecutionModelAnyHitKHR".."5315", "ExecutionModelAnyHitNV".."5315", "ExecutionModelClosestHitKHR".."5316", "ExecutionModelClosestHitNV".."5316", "ExecutionModelMissKHR".."5317", "ExecutionModelMissNV".."5317", "ExecutionModelCallableKHR".."5318", "ExecutionModelCallableNV".."5318", "ExecutionModelMax".."0x7fffffff", ) EnumConstant( "{@code SpvAddressingModel}", "AddressingModelLogical".."0", "AddressingModelPhysical32".."1", "AddressingModelPhysical64".."2", "AddressingModelPhysicalStorageBuffer64".."5348", "AddressingModelPhysicalStorageBuffer64EXT".."5348", "AddressingModelMax".."0x7fffffff", ) EnumConstant( "{@code SpvMemoryModel}", "MemoryModelSimple".."0", "MemoryModelGLSL450".."1", "MemoryModelOpenCL".."2", "MemoryModelVulkan".."3", "MemoryModelVulkanKHR".."3", "MemoryModelMax".."0x7fffffff", ) EnumConstant( "{@code SpvExecutionMode}", "ExecutionModeInvocations".."0", "ExecutionModeSpacingEqual".."1", "ExecutionModeSpacingFractionalEven".."2", "ExecutionModeSpacingFractionalOdd".."3", "ExecutionModeVertexOrderCw".."4", "ExecutionModeVertexOrderCcw".."5", "ExecutionModePixelCenterInteger".."6", "ExecutionModeOriginUpperLeft".."7", "ExecutionModeOriginLowerLeft".."8", "ExecutionModeEarlyFragmentTests".."9", "ExecutionModePointMode".."10", "ExecutionModeXfb".."11", "ExecutionModeDepthReplacing".."12", "ExecutionModeDepthGreater".."14", "ExecutionModeDepthLess".."15", "ExecutionModeDepthUnchanged".."16", "ExecutionModeLocalSize".."17", "ExecutionModeLocalSizeHint".."18", "ExecutionModeInputPoints".."19", "ExecutionModeInputLines".."20", "ExecutionModeInputLinesAdjacency".."21", "ExecutionModeTriangles".."22", "ExecutionModeInputTrianglesAdjacency".."23", "ExecutionModeQuads".."24", "ExecutionModeIsolines".."25", "ExecutionModeOutputVertices".."26", "ExecutionModeOutputPoints".."27", "ExecutionModeOutputLineStrip".."28", "ExecutionModeOutputTriangleStrip".."29", "ExecutionModeVecTypeHint".."30", "ExecutionModeContractionOff".."31", "ExecutionModeInitializer".."33", "ExecutionModeFinalizer".."34", "ExecutionModeSubgroupSize".."35", "ExecutionModeSubgroupsPerWorkgroup".."36", "ExecutionModeSubgroupsPerWorkgroupId".."37", "ExecutionModeLocalSizeId".."38", "ExecutionModeLocalSizeHintId".."39", "ExecutionModeSubgroupUniformControlFlowKHR".."4421", "ExecutionModePostDepthCoverage".."4446", "ExecutionModeDenormPreserve".."4459", "ExecutionModeDenormFlushToZero".."4460", "ExecutionModeSignedZeroInfNanPreserve".."4461", "ExecutionModeRoundingModeRTE".."4462", "ExecutionModeRoundingModeRTZ".."4463", "ExecutionModeStencilRefReplacingEXT".."5027", "ExecutionModeOutputLinesNV".."5269", "ExecutionModeOutputPrimitivesNV".."5270", "ExecutionModeDerivativeGroupQuadsNV".."5289", "ExecutionModeDerivativeGroupLinearNV".."5290", "ExecutionModeOutputTrianglesNV".."5298", "ExecutionModePixelInterlockOrderedEXT".."5366", "ExecutionModePixelInterlockUnorderedEXT".."5367", "ExecutionModeSampleInterlockOrderedEXT".."5368", "ExecutionModeSampleInterlockUnorderedEXT".."5369", "ExecutionModeShadingRateInterlockOrderedEXT".."5370", "ExecutionModeShadingRateInterlockUnorderedEXT".."5371", "ExecutionModeSharedLocalMemorySizeINTEL".."5618", "ExecutionModeRoundingModeRTPINTEL".."5620", "ExecutionModeRoundingModeRTNINTEL".."5621", "ExecutionModeFloatingPointModeALTINTEL".."5622", "ExecutionModeFloatingPointModeIEEEINTEL".."5623", "ExecutionModeMaxWorkgroupSizeINTEL".."5893", "ExecutionModeMaxWorkDimINTEL".."5894", "ExecutionModeNoGlobalOffsetINTEL".."5895", "ExecutionModeNumSIMDWorkitemsINTEL".."5896", "ExecutionModeSchedulerTargetFmaxMhzINTEL".."5903", "ExecutionModeNamedBarrierCountINTEL".."6417", "ExecutionModeMax".."0x7fffffff", ) EnumConstant( "{@code SpvStorageClass}", "StorageClassUniformConstant".."0", "StorageClassInput".."1", "StorageClassUniform".."2", "StorageClassOutput".."3", "StorageClassWorkgroup".."4", "StorageClassCrossWorkgroup".."5", "StorageClassPrivate".."6", "StorageClassFunction".."7", "StorageClassGeneric".."8", "StorageClassPushConstant".."9", "StorageClassAtomicCounter".."10", "StorageClassImage".."11", "StorageClassStorageBuffer".."12", "StorageClassCallableDataKHR".."5328", "StorageClassCallableDataNV".."5328", "StorageClassIncomingCallableDataKHR".."5329", "StorageClassIncomingCallableDataNV".."5329", "StorageClassRayPayloadKHR".."5338", "StorageClassRayPayloadNV".."5338", "StorageClassHitAttributeKHR".."5339", "StorageClassHitAttributeNV".."5339", "StorageClassIncomingRayPayloadKHR".."5342", "StorageClassIncomingRayPayloadNV".."5342", "StorageClassShaderRecordBufferKHR".."5343", "StorageClassShaderRecordBufferNV".."5343", "StorageClassPhysicalStorageBuffer".."5349", "StorageClassPhysicalStorageBufferEXT".."5349", "StorageClassCodeSectionINTEL".."5605", "StorageClassDeviceOnlyINTEL".."5936", "StorageClassHostOnlyINTEL".."5937", "StorageClassMax".."0x7fffffff", ) EnumConstant( "{@code SpvDim}", "Dim1D".."0", "Dim2D".."1", "Dim3D".."2", "DimCube".."3", "DimRect".."4", "DimBuffer".."5", "DimSubpassData".."6", "DimMax".."0x7fffffff", ) EnumConstant( "{@code SpvSamplerAddressingMode}", "SamplerAddressingModeNone".."0", "SamplerAddressingModeClampToEdge".."1", "SamplerAddressingModeClamp".."2", "SamplerAddressingModeRepeat".."3", "SamplerAddressingModeRepeatMirrored".."4", "SamplerAddressingModeMax".."0x7fffffff", ) EnumConstant( "{@code SpvSamplerFilterMode}", "SamplerFilterModeNearest".."0", "SamplerFilterModeLinear".."1", "SamplerFilterModeMax".."0x7fffffff", ) EnumConstant( "{@code SpvImageFormat}", "ImageFormatUnknown".."0", "ImageFormatRgba32f".."1", "ImageFormatRgba16f".."2", "ImageFormatR32f".."3", "ImageFormatRgba8".."4", "ImageFormatRgba8Snorm".."5", "ImageFormatRg32f".."6", "ImageFormatRg16f".."7", "ImageFormatR11fG11fB10f".."8", "ImageFormatR16f".."9", "ImageFormatRgba16".."10", "ImageFormatRgb10A2".."11", "ImageFormatRg16".."12", "ImageFormatRg8".."13", "ImageFormatR16".."14", "ImageFormatR8".."15", "ImageFormatRgba16Snorm".."16", "ImageFormatRg16Snorm".."17", "ImageFormatRg8Snorm".."18", "ImageFormatR16Snorm".."19", "ImageFormatR8Snorm".."20", "ImageFormatRgba32i".."21", "ImageFormatRgba16i".."22", "ImageFormatRgba8i".."23", "ImageFormatR32i".."24", "ImageFormatRg32i".."25", "ImageFormatRg16i".."26", "ImageFormatRg8i".."27", "ImageFormatR16i".."28", "ImageFormatR8i".."29", "ImageFormatRgba32ui".."30", "ImageFormatRgba16ui".."31", "ImageFormatRgba8ui".."32", "ImageFormatR32ui".."33", "ImageFormatRgb10a2ui".."34", "ImageFormatRg32ui".."35", "ImageFormatRg16ui".."36", "ImageFormatRg8ui".."37", "ImageFormatR16ui".."38", "ImageFormatR8ui".."39", "ImageFormatR64ui".."40", "ImageFormatR64i".."41", "ImageFormatMax".."0x7fffffff", ) EnumConstant( "{@code SpvImageChannelOrder}", "ImageChannelOrderR".."0", "ImageChannelOrderA".."1", "ImageChannelOrderRG".."2", "ImageChannelOrderRA".."3", "ImageChannelOrderRGB".."4", "ImageChannelOrderRGBA".."5", "ImageChannelOrderBGRA".."6", "ImageChannelOrderARGB".."7", "ImageChannelOrderIntensity".."8", "ImageChannelOrderLuminance".."9", "ImageChannelOrderRx".."10", "ImageChannelOrderRGx".."11", "ImageChannelOrderRGBx".."12", "ImageChannelOrderDepth".."13", "ImageChannelOrderDepthStencil".."14", "ImageChannelOrdersRGB".."15", "ImageChannelOrdersRGBx".."16", "ImageChannelOrdersRGBA".."17", "ImageChannelOrdersBGRA".."18", "ImageChannelOrderABGR".."19", "ImageChannelOrderMax".."0x7fffffff", ) EnumConstant( "{@code SpvImageChannelDataType}", "ImageChannelDataTypeSnormInt8".."0", "ImageChannelDataTypeSnormInt16".."1", "ImageChannelDataTypeUnormInt8".."2", "ImageChannelDataTypeUnormInt16".."3", "ImageChannelDataTypeUnormShort565".."4", "ImageChannelDataTypeUnormShort555".."5", "ImageChannelDataTypeUnormInt101010".."6", "ImageChannelDataTypeSignedInt8".."7", "ImageChannelDataTypeSignedInt16".."8", "ImageChannelDataTypeSignedInt32".."9", "ImageChannelDataTypeUnsignedInt8".."10", "ImageChannelDataTypeUnsignedInt16".."11", "ImageChannelDataTypeUnsignedInt32".."12", "ImageChannelDataTypeHalfFloat".."13", "ImageChannelDataTypeFloat".."14", "ImageChannelDataTypeUnormInt24".."15", "ImageChannelDataTypeUnormInt101010_2".."16", "ImageChannelDataTypeMax".."0x7fffffff", ) EnumConstant( "{@code SpvImageOperandsShift}", "ImageOperandsBiasShift".."0", "ImageOperandsLodShift".."1", "ImageOperandsGradShift".."2", "ImageOperandsConstOffsetShift".."3", "ImageOperandsOffsetShift".."4", "ImageOperandsConstOffsetsShift".."5", "ImageOperandsSampleShift".."6", "ImageOperandsMinLodShift".."7", "ImageOperandsMakeTexelAvailableShift".."8", "ImageOperandsMakeTexelAvailableKHRShift".."8", "ImageOperandsMakeTexelVisibleShift".."9", "ImageOperandsMakeTexelVisibleKHRShift".."9", "ImageOperandsNonPrivateTexelShift".."10", "ImageOperandsNonPrivateTexelKHRShift".."10", "ImageOperandsVolatileTexelShift".."11", "ImageOperandsVolatileTexelKHRShift".."11", "ImageOperandsSignExtendShift".."12", "ImageOperandsZeroExtendShift".."13", "ImageOperandsNontemporalShift".."14", "ImageOperandsOffsetsShift".."16", "ImageOperandsMax".."0x7fffffff", ) EnumConstant( "{@code SpvImageOperandsMask}", "ImageOperandsMaskNone".."0", "ImageOperandsBiasMask".."0x00000001", "ImageOperandsLodMask".."0x00000002", "ImageOperandsGradMask".."0x00000004", "ImageOperandsConstOffsetMask".."0x00000008", "ImageOperandsOffsetMask".."0x00000010", "ImageOperandsConstOffsetsMask".."0x00000020", "ImageOperandsSampleMask".."0x00000040", "ImageOperandsMinLodMask".."0x00000080", "ImageOperandsMakeTexelAvailableMask".."0x00000100", "ImageOperandsMakeTexelAvailableKHRMask".."0x00000100", "ImageOperandsMakeTexelVisibleMask".."0x00000200", "ImageOperandsMakeTexelVisibleKHRMask".."0x00000200", "ImageOperandsNonPrivateTexelMask".."0x00000400", "ImageOperandsNonPrivateTexelKHRMask".."0x00000400", "ImageOperandsVolatileTexelMask".."0x00000800", "ImageOperandsVolatileTexelKHRMask".."0x00000800", "ImageOperandsSignExtendMask".."0x00001000", "ImageOperandsZeroExtendMask".."0x00002000", "ImageOperandsNontemporalMask".."0x00004000", "ImageOperandsOffsetsMask".."0x00010000" ) EnumConstant( "{@code SpvFPFastMathModeShift}", "FPFastMathModeNotNaNShift".."0", "FPFastMathModeNotInfShift".."1", "FPFastMathModeNSZShift".."2", "FPFastMathModeAllowRecipShift".."3", "FPFastMathModeFastShift".."4", "FPFastMathModeAllowContractFastINTELShift".."16", "FPFastMathModeAllowReassocINTELShift".."17", "FPFastMathModeMax".."0x7fffffff", ) EnumConstant( "{@code SpvFPFastMathModeMask}", "FPFastMathModeMaskNone".."0", "FPFastMathModeNotNaNMask".."0x00000001", "FPFastMathModeNotInfMask".."0x00000002", "FPFastMathModeNSZMask".."0x00000004", "FPFastMathModeAllowRecipMask".."0x00000008", "FPFastMathModeFastMask".."0x00000010", "FPFastMathModeAllowContractFastINTELMask".."0x00010000", "FPFastMathModeAllowReassocINTELMask".."0x00020000" ) EnumConstant( "{@code SpvFPRoundingMode}", "FPRoundingModeRTE".."0", "FPRoundingModeRTZ".."1", "FPRoundingModeRTP".."2", "FPRoundingModeRTN".."3", "FPRoundingModeMax".."0x7fffffff", ) EnumConstant( "{@code SpvLinkageType}", "LinkageTypeExport".."0", "LinkageTypeImport".."1", "LinkageTypeLinkOnceODR".."2", "LinkageTypeMax".."0x7fffffff", ) EnumConstant( "{@code SpvAccessQualifier}", "AccessQualifierReadOnly".."0", "AccessQualifierWriteOnly".."1", "AccessQualifierReadWrite".."2", "AccessQualifierMax".."0x7fffffff", ) EnumConstant( "{@code SpvFunctionParameterAttribute}", "FunctionParameterAttributeZext".."0", "FunctionParameterAttributeSext".."1", "FunctionParameterAttributeByVal".."2", "FunctionParameterAttributeSret".."3", "FunctionParameterAttributeNoAlias".."4", "FunctionParameterAttributeNoCapture".."5", "FunctionParameterAttributeNoWrite".."6", "FunctionParameterAttributeNoReadWrite".."7", "FunctionParameterAttributeMax".."0x7fffffff", ) EnumConstant( "{@code SpvDecoration}", "DecorationRelaxedPrecision".."0", "DecorationSpecId".."1", "DecorationBlock".."2", "DecorationBufferBlock".."3", "DecorationRowMajor".."4", "DecorationColMajor".."5", "DecorationArrayStride".."6", "DecorationMatrixStride".."7", "DecorationGLSLShared".."8", "DecorationGLSLPacked".."9", "DecorationCPacked".."10", "DecorationBuiltIn".."11", "DecorationNoPerspective".."13", "DecorationFlat".."14", "DecorationPatch".."15", "DecorationCentroid".."16", "DecorationSample".."17", "DecorationInvariant".."18", "DecorationRestrict".."19", "DecorationAliased".."20", "DecorationVolatile".."21", "DecorationConstant".."22", "DecorationCoherent".."23", "DecorationNonWritable".."24", "DecorationNonReadable".."25", "DecorationUniform".."26", "DecorationUniformId".."27", "DecorationSaturatedConversion".."28", "DecorationStream".."29", "DecorationLocation".."30", "DecorationComponent".."31", "DecorationIndex".."32", "DecorationBinding".."33", "DecorationDescriptorSet".."34", "DecorationOffset".."35", "DecorationXfbBuffer".."36", "DecorationXfbStride".."37", "DecorationFuncParamAttr".."38", "DecorationFPRoundingMode".."39", "DecorationFPFastMathMode".."40", "DecorationLinkageAttributes".."41", "DecorationNoContraction".."42", "DecorationInputAttachmentIndex".."43", "DecorationAlignment".."44", "DecorationMaxByteOffset".."45", "DecorationAlignmentId".."46", "DecorationMaxByteOffsetId".."47", "DecorationNoSignedWrap".."4469", "DecorationNoUnsignedWrap".."4470", "DecorationExplicitInterpAMD".."4999", "DecorationOverrideCoverageNV".."5248", "DecorationPassthroughNV".."5250", "DecorationViewportRelativeNV".."5252", "DecorationSecondaryViewportRelativeNV".."5256", "DecorationPerPrimitiveNV".."5271", "DecorationPerViewNV".."5272", "DecorationPerTaskNV".."5273", "DecorationPerVertexKHR".."5285", "DecorationPerVertexNV".."5285", "DecorationNonUniform".."5300", "DecorationNonUniformEXT".."5300", "DecorationRestrictPointer".."5355", "DecorationRestrictPointerEXT".."5355", "DecorationAliasedPointer".."5356", "DecorationAliasedPointerEXT".."5356", "DecorationBindlessSamplerNV".."5398", "DecorationBindlessImageNV".."5399", "DecorationBoundSamplerNV".."5400", "DecorationBoundImageNV".."5401", "DecorationSIMTCallINTEL".."5599", "DecorationReferencedIndirectlyINTEL".."5602", "DecorationClobberINTEL".."5607", "DecorationSideEffectsINTEL".."5608", "DecorationVectorComputeVariableINTEL".."5624", "DecorationFuncParamIOKindINTEL".."5625", "DecorationVectorComputeFunctionINTEL".."5626", "DecorationStackCallINTEL".."5627", "DecorationGlobalVariableOffsetINTEL".."5628", "DecorationCounterBuffer".."5634", "DecorationHlslCounterBufferGOOGLE".."5634", "DecorationHlslSemanticGOOGLE".."5635", "DecorationUserSemantic".."5635", "DecorationUserTypeGOOGLE".."5636", "DecorationFunctionRoundingModeINTEL".."5822", "DecorationFunctionDenormModeINTEL".."5823", "DecorationRegisterINTEL".."5825", "DecorationMemoryINTEL".."5826", "DecorationNumbanksINTEL".."5827", "DecorationBankwidthINTEL".."5828", "DecorationMaxPrivateCopiesINTEL".."5829", "DecorationSinglepumpINTEL".."5830", "DecorationDoublepumpINTEL".."5831", "DecorationMaxReplicatesINTEL".."5832", "DecorationSimpleDualPortINTEL".."5833", "DecorationMergeINTEL".."5834", "DecorationBankBitsINTEL".."5835", "DecorationForcePow2DepthINTEL".."5836", "DecorationBurstCoalesceINTEL".."5899", "DecorationCacheSizeINTEL".."5900", "DecorationDontStaticallyCoalesceINTEL".."5901", "DecorationPrefetchINTEL".."5902", "DecorationStallEnableINTEL".."5905", "DecorationFuseLoopsInFunctionINTEL".."5907", "DecorationAliasScopeINTEL".."5914", "DecorationNoAliasINTEL".."5915", "DecorationBufferLocationINTEL".."5921", "DecorationIOPipeStorageINTEL".."5944", "DecorationFunctionFloatingPointModeINTEL".."6080", "DecorationSingleElementVectorINTEL".."6085", "DecorationVectorComputeCallableFunctionINTEL".."6087", "DecorationMediaBlockIOINTEL".."6140", "DecorationMax".."0x7fffffff", ) EnumConstant( "{@code SpvBuiltIn}", "BuiltInPosition".."0", "BuiltInPointSize".."1", "BuiltInClipDistance".."3", "BuiltInCullDistance".."4", "BuiltInVertexId".."5", "BuiltInInstanceId".."6", "BuiltInPrimitiveId".."7", "BuiltInInvocationId".."8", "BuiltInLayer".."9", "BuiltInViewportIndex".."10", "BuiltInTessLevelOuter".."11", "BuiltInTessLevelInner".."12", "BuiltInTessCoord".."13", "BuiltInPatchVertices".."14", "BuiltInFragCoord".."15", "BuiltInPointCoord".."16", "BuiltInFrontFacing".."17", "BuiltInSampleId".."18", "BuiltInSamplePosition".."19", "BuiltInSampleMask".."20", "BuiltInFragDepth".."22", "BuiltInHelperInvocation".."23", "BuiltInNumWorkgroups".."24", "BuiltInWorkgroupSize".."25", "BuiltInWorkgroupId".."26", "BuiltInLocalInvocationId".."27", "BuiltInGlobalInvocationId".."28", "BuiltInLocalInvocationIndex".."29", "BuiltInWorkDim".."30", "BuiltInGlobalSize".."31", "BuiltInEnqueuedWorkgroupSize".."32", "BuiltInGlobalOffset".."33", "BuiltInGlobalLinearId".."34", "BuiltInSubgroupSize".."36", "BuiltInSubgroupMaxSize".."37", "BuiltInNumSubgroups".."38", "BuiltInNumEnqueuedSubgroups".."39", "BuiltInSubgroupId".."40", "BuiltInSubgroupLocalInvocationId".."41", "BuiltInVertexIndex".."42", "BuiltInInstanceIndex".."43", "BuiltInSubgroupEqMask".."4416", "BuiltInSubgroupEqMaskKHR".."4416", "BuiltInSubgroupGeMask".."4417", "BuiltInSubgroupGeMaskKHR".."4417", "BuiltInSubgroupGtMask".."4418", "BuiltInSubgroupGtMaskKHR".."4418", "BuiltInSubgroupLeMask".."4419", "BuiltInSubgroupLeMaskKHR".."4419", "BuiltInSubgroupLtMask".."4420", "BuiltInSubgroupLtMaskKHR".."4420", "BuiltInBaseVertex".."4424", "BuiltInBaseInstance".."4425", "BuiltInDrawIndex".."4426", "BuiltInPrimitiveShadingRateKHR".."4432", "BuiltInDeviceIndex".."4438", "BuiltInViewIndex".."4440", "BuiltInShadingRateKHR".."4444", "BuiltInBaryCoordNoPerspAMD".."4992", "BuiltInBaryCoordNoPerspCentroidAMD".."4993", "BuiltInBaryCoordNoPerspSampleAMD".."4994", "BuiltInBaryCoordSmoothAMD".."4995", "BuiltInBaryCoordSmoothCentroidAMD".."4996", "BuiltInBaryCoordSmoothSampleAMD".."4997", "BuiltInBaryCoordPullModelAMD".."4998", "BuiltInFragStencilRefEXT".."5014", "BuiltInViewportMaskNV".."5253", "BuiltInSecondaryPositionNV".."5257", "BuiltInSecondaryViewportMaskNV".."5258", "BuiltInPositionPerViewNV".."5261", "BuiltInViewportMaskPerViewNV".."5262", "BuiltInFullyCoveredEXT".."5264", "BuiltInTaskCountNV".."5274", "BuiltInPrimitiveCountNV".."5275", "BuiltInPrimitiveIndicesNV".."5276", "BuiltInClipDistancePerViewNV".."5277", "BuiltInCullDistancePerViewNV".."5278", "BuiltInLayerPerViewNV".."5279", "BuiltInMeshViewCountNV".."5280", "BuiltInMeshViewIndicesNV".."5281", "BuiltInBaryCoordKHR".."5286", "BuiltInBaryCoordNV".."5286", "BuiltInBaryCoordNoPerspKHR".."5287", "BuiltInBaryCoordNoPerspNV".."5287", "BuiltInFragSizeEXT".."5292", "BuiltInFragmentSizeNV".."5292", "BuiltInFragInvocationCountEXT".."5293", "BuiltInInvocationsPerPixelNV".."5293", "BuiltInLaunchIdKHR".."5319", "BuiltInLaunchIdNV".."5319", "BuiltInLaunchSizeKHR".."5320", "BuiltInLaunchSizeNV".."5320", "BuiltInWorldRayOriginKHR".."5321", "BuiltInWorldRayOriginNV".."5321", "BuiltInWorldRayDirectionKHR".."5322", "BuiltInWorldRayDirectionNV".."5322", "BuiltInObjectRayOriginKHR".."5323", "BuiltInObjectRayOriginNV".."5323", "BuiltInObjectRayDirectionKHR".."5324", "BuiltInObjectRayDirectionNV".."5324", "BuiltInRayTminKHR".."5325", "BuiltInRayTminNV".."5325", "BuiltInRayTmaxKHR".."5326", "BuiltInRayTmaxNV".."5326", "BuiltInInstanceCustomIndexKHR".."5327", "BuiltInInstanceCustomIndexNV".."5327", "BuiltInObjectToWorldKHR".."5330", "BuiltInObjectToWorldNV".."5330", "BuiltInWorldToObjectKHR".."5331", "BuiltInWorldToObjectNV".."5331", "BuiltInHitTNV".."5332", "BuiltInHitKindKHR".."5333", "BuiltInHitKindNV".."5333", "BuiltInCurrentRayTimeNV".."5334", "BuiltInIncomingRayFlagsKHR".."5351", "BuiltInIncomingRayFlagsNV".."5351", "BuiltInRayGeometryIndexKHR".."5352", "BuiltInWarpsPerSMNV".."5374", "BuiltInSMCountNV".."5375", "BuiltInWarpIDNV".."5376", "BuiltInSMIDNV".."5377", "BuiltInCullMaskKHR".."6021", "BuiltInMax".."0x7fffffff", ) EnumConstant( "{@code SpvSelectionControlShift}", "SelectionControlFlattenShift".."0", "SelectionControlDontFlattenShift".."1", "SelectionControlMax".."0x7fffffff", ) EnumConstant( "{@code SpvSelectionControlMask}", "SelectionControlMaskNone".."0", "SelectionControlFlattenMask".."0x00000001", "SelectionControlDontFlattenMask".."0x00000002" ) EnumConstant( "{@code SpvLoopControlShift}", "LoopControlUnrollShift".."0", "LoopControlDontUnrollShift".."1", "LoopControlDependencyInfiniteShift".."2", "LoopControlDependencyLengthShift".."3", "LoopControlMinIterationsShift".."4", "LoopControlMaxIterationsShift".."5", "LoopControlIterationMultipleShift".."6", "LoopControlPeelCountShift".."7", "LoopControlPartialCountShift".."8", "LoopControlInitiationIntervalINTELShift".."16", "LoopControlMaxConcurrencyINTELShift".."17", "LoopControlDependencyArrayINTELShift".."18", "LoopControlPipelineEnableINTELShift".."19", "LoopControlLoopCoalesceINTELShift".."20", "LoopControlMaxInterleavingINTELShift".."21", "LoopControlSpeculatedIterationsINTELShift".."22", "LoopControlNoFusionINTELShift".."23", "LoopControlMax".."0x7fffffff", ) EnumConstant( "{@code SpvLoopControlMask}", "LoopControlMaskNone".."0", "LoopControlUnrollMask".."0x00000001", "LoopControlDontUnrollMask".."0x00000002", "LoopControlDependencyInfiniteMask".."0x00000004", "LoopControlDependencyLengthMask".."0x00000008", "LoopControlMinIterationsMask".."0x00000010", "LoopControlMaxIterationsMask".."0x00000020", "LoopControlIterationMultipleMask".."0x00000040", "LoopControlPeelCountMask".."0x00000080", "LoopControlPartialCountMask".."0x00000100", "LoopControlInitiationIntervalINTELMask".."0x00010000", "LoopControlMaxConcurrencyINTELMask".."0x00020000", "LoopControlDependencyArrayINTELMask".."0x00040000", "LoopControlPipelineEnableINTELMask".."0x00080000", "LoopControlLoopCoalesceINTELMask".."0x00100000", "LoopControlMaxInterleavingINTELMask".."0x00200000", "LoopControlSpeculatedIterationsINTELMask".."0x00400000", "LoopControlNoFusionINTELMask".."0x00800000" ) EnumConstant( "{@code SpvFunctionControlShift}", "FunctionControlInlineShift".."0", "FunctionControlDontInlineShift".."1", "FunctionControlPureShift".."2", "FunctionControlConstShift".."3", "FunctionControlOptNoneINTELShift".."16", "FunctionControlMax".."0x7fffffff", ) EnumConstant( "{@code SpvFunctionControlMask}", "FunctionControlMaskNone".."0", "FunctionControlInlineMask".."0x00000001", "FunctionControlDontInlineMask".."0x00000002", "FunctionControlPureMask".."0x00000004", "FunctionControlConstMask".."0x00000008", "FunctionControlOptNoneINTELMask".."0x00010000" ) EnumConstant( "{@code SpvMemorySemanticsShift}", "MemorySemanticsAcquireShift".."1", "MemorySemanticsReleaseShift".."2", "MemorySemanticsAcquireReleaseShift".."3", "MemorySemanticsSequentiallyConsistentShift".."4", "MemorySemanticsUniformMemoryShift".."6", "MemorySemanticsSubgroupMemoryShift".."7", "MemorySemanticsWorkgroupMemoryShift".."8", "MemorySemanticsCrossWorkgroupMemoryShift".."9", "MemorySemanticsAtomicCounterMemoryShift".."10", "MemorySemanticsImageMemoryShift".."11", "MemorySemanticsOutputMemoryShift".."12", "MemorySemanticsOutputMemoryKHRShift".."12", "MemorySemanticsMakeAvailableShift".."13", "MemorySemanticsMakeAvailableKHRShift".."13", "MemorySemanticsMakeVisibleShift".."14", "MemorySemanticsMakeVisibleKHRShift".."14", "MemorySemanticsVolatileShift".."15", "MemorySemanticsMax".."0x7fffffff", ) EnumConstant( "{@code SpvMemorySemanticsMask}", "MemorySemanticsMaskNone".."0", "MemorySemanticsAcquireMask".."0x00000002", "MemorySemanticsReleaseMask".."0x00000004", "MemorySemanticsAcquireReleaseMask".."0x00000008", "MemorySemanticsSequentiallyConsistentMask".."0x00000010", "MemorySemanticsUniformMemoryMask".."0x00000040", "MemorySemanticsSubgroupMemoryMask".."0x00000080", "MemorySemanticsWorkgroupMemoryMask".."0x00000100", "MemorySemanticsCrossWorkgroupMemoryMask".."0x00000200", "MemorySemanticsAtomicCounterMemoryMask".."0x00000400", "MemorySemanticsImageMemoryMask".."0x00000800", "MemorySemanticsOutputMemoryMask".."0x00001000", "MemorySemanticsOutputMemoryKHRMask".."0x00001000", "MemorySemanticsMakeAvailableMask".."0x00002000", "MemorySemanticsMakeAvailableKHRMask".."0x00002000", "MemorySemanticsMakeVisibleMask".."0x00004000", "MemorySemanticsMakeVisibleKHRMask".."0x00004000", "MemorySemanticsVolatileMask".."0x00008000" ) EnumConstant( "{@code SpvMemoryAccessShift}", "MemoryAccessVolatileShift".."0", "MemoryAccessAlignedShift".."1", "MemoryAccessNontemporalShift".."2", "MemoryAccessMakePointerAvailableShift".."3", "MemoryAccessMakePointerAvailableKHRShift".."3", "MemoryAccessMakePointerVisibleShift".."4", "MemoryAccessMakePointerVisibleKHRShift".."4", "MemoryAccessNonPrivatePointerShift".."5", "MemoryAccessNonPrivatePointerKHRShift".."5", "MemoryAccessAliasScopeINTELMaskShift".."16", "MemoryAccessNoAliasINTELMaskShift".."17", "MemoryAccessMax".."0x7fffffff", ) EnumConstant( "{@code SpvMemoryAccessMask}", "MemoryAccessMaskNone".."0", "MemoryAccessVolatileMask".."0x00000001", "MemoryAccessAlignedMask".."0x00000002", "MemoryAccessNontemporalMask".."0x00000004", "MemoryAccessMakePointerAvailableMask".."0x00000008", "MemoryAccessMakePointerAvailableKHRMask".."0x00000008", "MemoryAccessMakePointerVisibleMask".."0x00000010", "MemoryAccessMakePointerVisibleKHRMask".."0x00000010", "MemoryAccessNonPrivatePointerMask".."0x00000020", "MemoryAccessNonPrivatePointerKHRMask".."0x00000020", "MemoryAccessAliasScopeINTELMaskMask".."0x00010000", "MemoryAccessNoAliasINTELMaskMask".."0x00020000" ) EnumConstant( "{@code SpvScope}", "ScopeCrossDevice".."0", "ScopeDevice".."1", "ScopeWorkgroup".."2", "ScopeSubgroup".."3", "ScopeInvocation".."4", "ScopeQueueFamily".."5", "ScopeQueueFamilyKHR".."5", "ScopeShaderCallKHR".."6", "ScopeMax".."0x7fffffff", ) EnumConstant( "{@code SpvGroupOperation}", "GroupOperationReduce".."0", "GroupOperationInclusiveScan".."1", "GroupOperationExclusiveScan".."2", "GroupOperationClusteredReduce".."3", "GroupOperationPartitionedReduceNV".."6", "GroupOperationPartitionedInclusiveScanNV".."7", "GroupOperationPartitionedExclusiveScanNV".."8", "GroupOperationMax".."0x7fffffff", ) EnumConstant( "{@code SpvKernelEnqueueFlags}", "KernelEnqueueFlagsNoWait".."0", "KernelEnqueueFlagsWaitKernel".."1", "KernelEnqueueFlagsWaitWorkGroup".."2", "KernelEnqueueFlagsMax".."0x7fffffff", ) EnumConstant( "{@code SpvKernelProfilingInfoShift}", "KernelProfilingInfoCmdExecTimeShift".."0", "KernelProfilingInfoMax".."0x7fffffff", ) EnumConstant( "{@code SpvKernelProfilingInfoMask}", "KernelProfilingInfoMaskNone".."0", "KernelProfilingInfoCmdExecTimeMask".."0x00000001" ) EnumConstant( "{@code SpvCapability}", "CapabilityMatrix".."0", "CapabilityShader".."1", "CapabilityGeometry".."2", "CapabilityTessellation".."3", "CapabilityAddresses".."4", "CapabilityLinkage".."5", "CapabilityKernel".."6", "CapabilityVector16".."7", "CapabilityFloat16Buffer".."8", "CapabilityFloat16".."9", "CapabilityFloat64".."10", "CapabilityInt64".."11", "CapabilityInt64Atomics".."12", "CapabilityImageBasic".."13", "CapabilityImageReadWrite".."14", "CapabilityImageMipmap".."15", "CapabilityPipes".."17", "CapabilityGroups".."18", "CapabilityDeviceEnqueue".."19", "CapabilityLiteralSampler".."20", "CapabilityAtomicStorage".."21", "CapabilityInt16".."22", "CapabilityTessellationPointSize".."23", "CapabilityGeometryPointSize".."24", "CapabilityImageGatherExtended".."25", "CapabilityStorageImageMultisample".."27", "CapabilityUniformBufferArrayDynamicIndexing".."28", "CapabilitySampledImageArrayDynamicIndexing".."29", "CapabilityStorageBufferArrayDynamicIndexing".."30", "CapabilityStorageImageArrayDynamicIndexing".."31", "CapabilityClipDistance".."32", "CapabilityCullDistance".."33", "CapabilityImageCubeArray".."34", "CapabilitySampleRateShading".."35", "CapabilityImageRect".."36", "CapabilitySampledRect".."37", "CapabilityGenericPointer".."38", "CapabilityInt8".."39", "CapabilityInputAttachment".."40", "CapabilitySparseResidency".."41", "CapabilityMinLod".."42", "CapabilitySampled1D".."43", "CapabilityImage1D".."44", "CapabilitySampledCubeArray".."45", "CapabilitySampledBuffer".."46", "CapabilityImageBuffer".."47", "CapabilityImageMSArray".."48", "CapabilityStorageImageExtendedFormats".."49", "CapabilityImageQuery".."50", "CapabilityDerivativeControl".."51", "CapabilityInterpolationFunction".."52", "CapabilityTransformFeedback".."53", "CapabilityGeometryStreams".."54", "CapabilityStorageImageReadWithoutFormat".."55", "CapabilityStorageImageWriteWithoutFormat".."56", "CapabilityMultiViewport".."57", "CapabilitySubgroupDispatch".."58", "CapabilityNamedBarrier".."59", "CapabilityPipeStorage".."60", "CapabilityGroupNonUniform".."61", "CapabilityGroupNonUniformVote".."62", "CapabilityGroupNonUniformArithmetic".."63", "CapabilityGroupNonUniformBallot".."64", "CapabilityGroupNonUniformShuffle".."65", "CapabilityGroupNonUniformShuffleRelative".."66", "CapabilityGroupNonUniformClustered".."67", "CapabilityGroupNonUniformQuad".."68", "CapabilityShaderLayer".."69", "CapabilityShaderViewportIndex".."70", "CapabilityUniformDecoration".."71", "CapabilityFragmentShadingRateKHR".."4422", "CapabilitySubgroupBallotKHR".."4423", "CapabilityDrawParameters".."4427", "CapabilityWorkgroupMemoryExplicitLayoutKHR".."4428", "CapabilityWorkgroupMemoryExplicitLayout8BitAccessKHR".."4429", "CapabilityWorkgroupMemoryExplicitLayout16BitAccessKHR".."4430", "CapabilitySubgroupVoteKHR".."4431", "CapabilityStorageBuffer16BitAccess".."4433", "CapabilityStorageUniformBufferBlock16".."4433", "CapabilityStorageUniform16".."4434", "CapabilityUniformAndStorageBuffer16BitAccess".."4434", "CapabilityStoragePushConstant16".."4435", "CapabilityStorageInputOutput16".."4436", "CapabilityDeviceGroup".."4437", "CapabilityMultiView".."4439", "CapabilityVariablePointersStorageBuffer".."4441", "CapabilityVariablePointers".."4442", "CapabilityAtomicStorageOps".."4445", "CapabilitySampleMaskPostDepthCoverage".."4447", "CapabilityStorageBuffer8BitAccess".."4448", "CapabilityUniformAndStorageBuffer8BitAccess".."4449", "CapabilityStoragePushConstant8".."4450", "CapabilityDenormPreserve".."4464", "CapabilityDenormFlushToZero".."4465", "CapabilitySignedZeroInfNanPreserve".."4466", "CapabilityRoundingModeRTE".."4467", "CapabilityRoundingModeRTZ".."4468", "CapabilityRayQueryProvisionalKHR".."4471", "CapabilityRayQueryKHR".."4472", "CapabilityRayTraversalPrimitiveCullingKHR".."4478", "CapabilityRayTracingKHR".."4479", "CapabilityFloat16ImageAMD".."5008", "CapabilityImageGatherBiasLodAMD".."5009", "CapabilityFragmentMaskAMD".."5010", "CapabilityStencilExportEXT".."5013", "CapabilityImageReadWriteLodAMD".."5015", "CapabilityInt64ImageEXT".."5016", "CapabilityShaderClockKHR".."5055", "CapabilitySampleMaskOverrideCoverageNV".."5249", "CapabilityGeometryShaderPassthroughNV".."5251", "CapabilityShaderViewportIndexLayerEXT".."5254", "CapabilityShaderViewportIndexLayerNV".."5254", "CapabilityShaderViewportMaskNV".."5255", "CapabilityShaderStereoViewNV".."5259", "CapabilityPerViewAttributesNV".."5260", "CapabilityFragmentFullyCoveredEXT".."5265", "CapabilityMeshShadingNV".."5266", "CapabilityImageFootprintNV".."5282", "CapabilityFragmentBarycentricKHR".."5284", "CapabilityFragmentBarycentricNV".."5284", "CapabilityComputeDerivativeGroupQuadsNV".."5288", "CapabilityFragmentDensityEXT".."5291", "CapabilityShadingRateNV".."5291", "CapabilityGroupNonUniformPartitionedNV".."5297", "CapabilityShaderNonUniform".."5301", "CapabilityShaderNonUniformEXT".."5301", "CapabilityRuntimeDescriptorArray".."5302", "CapabilityRuntimeDescriptorArrayEXT".."5302", "CapabilityInputAttachmentArrayDynamicIndexing".."5303", "CapabilityInputAttachmentArrayDynamicIndexingEXT".."5303", "CapabilityUniformTexelBufferArrayDynamicIndexing".."5304", "CapabilityUniformTexelBufferArrayDynamicIndexingEXT".."5304", "CapabilityStorageTexelBufferArrayDynamicIndexing".."5305", "CapabilityStorageTexelBufferArrayDynamicIndexingEXT".."5305", "CapabilityUniformBufferArrayNonUniformIndexing".."5306", "CapabilityUniformBufferArrayNonUniformIndexingEXT".."5306", "CapabilitySampledImageArrayNonUniformIndexing".."5307", "CapabilitySampledImageArrayNonUniformIndexingEXT".."5307", "CapabilityStorageBufferArrayNonUniformIndexing".."5308", "CapabilityStorageBufferArrayNonUniformIndexingEXT".."5308", "CapabilityStorageImageArrayNonUniformIndexing".."5309", "CapabilityStorageImageArrayNonUniformIndexingEXT".."5309", "CapabilityInputAttachmentArrayNonUniformIndexing".."5310", "CapabilityInputAttachmentArrayNonUniformIndexingEXT".."5310", "CapabilityUniformTexelBufferArrayNonUniformIndexing".."5311", "CapabilityUniformTexelBufferArrayNonUniformIndexingEXT".."5311", "CapabilityStorageTexelBufferArrayNonUniformIndexing".."5312", "CapabilityStorageTexelBufferArrayNonUniformIndexingEXT".."5312", "CapabilityRayTracingNV".."5340", "CapabilityRayTracingMotionBlurNV".."5341", "CapabilityVulkanMemoryModel".."5345", "CapabilityVulkanMemoryModelKHR".."5345", "CapabilityVulkanMemoryModelDeviceScope".."5346", "CapabilityVulkanMemoryModelDeviceScopeKHR".."5346", "CapabilityPhysicalStorageBufferAddresses".."5347", "CapabilityPhysicalStorageBufferAddressesEXT".."5347", "CapabilityComputeDerivativeGroupLinearNV".."5350", "CapabilityRayTracingProvisionalKHR".."5353", "CapabilityCooperativeMatrixNV".."5357", "CapabilityFragmentShaderSampleInterlockEXT".."5363", "CapabilityFragmentShaderShadingRateInterlockEXT".."5372", "CapabilityShaderSMBuiltinsNV".."5373", "CapabilityFragmentShaderPixelInterlockEXT".."5378", "CapabilityDemoteToHelperInvocation".."5379", "CapabilityDemoteToHelperInvocationEXT".."5379", "CapabilityBindlessTextureNV".."5390", "CapabilitySubgroupShuffleINTEL".."5568", "CapabilitySubgroupBufferBlockIOINTEL".."5569", "CapabilitySubgroupImageBlockIOINTEL".."5570", "CapabilitySubgroupImageMediaBlockIOINTEL".."5579", "CapabilityRoundToInfinityINTEL".."5582", "CapabilityFloatingPointModeINTEL".."5583", "CapabilityIntegerFunctions2INTEL".."5584", "CapabilityFunctionPointersINTEL".."5603", "CapabilityIndirectReferencesINTEL".."5604", "CapabilityAsmINTEL".."5606", "CapabilityAtomicFloat32MinMaxEXT".."5612", "CapabilityAtomicFloat64MinMaxEXT".."5613", "CapabilityAtomicFloat16MinMaxEXT".."5616", "CapabilityVectorComputeINTEL".."5617", "CapabilityVectorAnyINTEL".."5619", "CapabilityExpectAssumeKHR".."5629", "CapabilitySubgroupAvcMotionEstimationINTEL".."5696", "CapabilitySubgroupAvcMotionEstimationIntraINTEL".."5697", "CapabilitySubgroupAvcMotionEstimationChromaINTEL".."5698", "CapabilityVariableLengthArrayINTEL".."5817", "CapabilityFunctionFloatControlINTEL".."5821", "CapabilityFPGAMemoryAttributesINTEL".."5824", "CapabilityFPFastMathModeINTEL".."5837", "CapabilityArbitraryPrecisionIntegersINTEL".."5844", "CapabilityArbitraryPrecisionFloatingPointINTEL".."5845", "CapabilityUnstructuredLoopControlsINTEL".."5886", "CapabilityFPGALoopControlsINTEL".."5888", "CapabilityKernelAttributesINTEL".."5892", "CapabilityFPGAKernelAttributesINTEL".."5897", "CapabilityFPGAMemoryAccessesINTEL".."5898", "CapabilityFPGAClusterAttributesINTEL".."5904", "CapabilityLoopFuseINTEL".."5906", "CapabilityMemoryAccessAliasingINTEL".."5910", "CapabilityFPGABufferLocationINTEL".."5920", "CapabilityArbitraryPrecisionFixedPointINTEL".."5922", "CapabilityUSMStorageClassesINTEL".."5935", "CapabilityIOPipesINTEL".."5943", "CapabilityBlockingPipesINTEL".."5945", "CapabilityFPGARegINTEL".."5948", "CapabilityDotProductInputAll".."6016", "CapabilityDotProductInputAllKHR".."6016", "CapabilityDotProductInput4x8Bit".."6017", "CapabilityDotProductInput4x8BitKHR".."6017", "CapabilityDotProductInput4x8BitPacked".."6018", "CapabilityDotProductInput4x8BitPackedKHR".."6018", "CapabilityDotProduct".."6019", "CapabilityDotProductKHR".."6019", "CapabilityRayCullMaskKHR".."6020", "CapabilityBitInstructions".."6025", "CapabilityGroupNonUniformRotateKHR".."6026", "CapabilityAtomicFloat32AddEXT".."6033", "CapabilityAtomicFloat64AddEXT".."6034", "CapabilityLongConstantCompositeINTEL".."6089", "CapabilityOptNoneINTEL".."6094", "CapabilityAtomicFloat16AddEXT".."6095", "CapabilityDebugInfoModuleINTEL".."6114", "CapabilitySplitBarrierINTEL".."6141", "CapabilityGroupUniformArithmeticKHR".."6400", "CapabilityMax".."0x7fffffff", ) EnumConstant( "{@code SpvRayFlagsShift}", "RayFlagsOpaqueKHRShift".."0", "RayFlagsNoOpaqueKHRShift".."1", "RayFlagsTerminateOnFirstHitKHRShift".."2", "RayFlagsSkipClosestHitShaderKHRShift".."3", "RayFlagsCullBackFacingTrianglesKHRShift".."4", "RayFlagsCullFrontFacingTrianglesKHRShift".."5", "RayFlagsCullOpaqueKHRShift".."6", "RayFlagsCullNoOpaqueKHRShift".."7", "RayFlagsSkipTrianglesKHRShift".."8", "RayFlagsSkipAABBsKHRShift".."9", "RayFlagsMax".."0x7fffffff", ) EnumConstant( "{@code SpvRayFlagsMask}", "RayFlagsMaskNone".."0", "RayFlagsOpaqueKHRMask".."0x00000001", "RayFlagsNoOpaqueKHRMask".."0x00000002", "RayFlagsTerminateOnFirstHitKHRMask".."0x00000004", "RayFlagsSkipClosestHitShaderKHRMask".."0x00000008", "RayFlagsCullBackFacingTrianglesKHRMask".."0x00000010", "RayFlagsCullFrontFacingTrianglesKHRMask".."0x00000020", "RayFlagsCullOpaqueKHRMask".."0x00000040", "RayFlagsCullNoOpaqueKHRMask".."0x00000080", "RayFlagsSkipTrianglesKHRMask".."0x00000100", "RayFlagsSkipAABBsKHRMask".."0x00000200" ) EnumConstant( "{@code SpvRayQueryIntersection}", "RayQueryIntersectionRayQueryCandidateIntersectionKHR".."0", "RayQueryIntersectionRayQueryCommittedIntersectionKHR".."1", "RayQueryIntersectionMax".."0x7fffffff", ) EnumConstant( "{@code SpvRayQueryCommittedIntersectionType}", "RayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionNoneKHR".."0", "RayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionTriangleKHR".."1", "RayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionGeneratedKHR".."2", "RayQueryCommittedIntersectionTypeMax".."0x7fffffff", ) EnumConstant( "{@code SpvRayQueryCandidateIntersectionType}", "RayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionTriangleKHR".."0", "RayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionAABBKHR".."1", "RayQueryCandidateIntersectionTypeMax".."0x7fffffff", ) EnumConstant( "{@code SpvFragmentShadingRateShift}", "FragmentShadingRateVertical2PixelsShift".."0", "FragmentShadingRateVertical4PixelsShift".."1", "FragmentShadingRateHorizontal2PixelsShift".."2", "FragmentShadingRateHorizontal4PixelsShift".."3", "FragmentShadingRateMax".."0x7fffffff", ) EnumConstant( "{@code SpvFragmentShadingRateMask}", "FragmentShadingRateMaskNone".."0", "FragmentShadingRateVertical2PixelsMask".."0x00000001", "FragmentShadingRateVertical4PixelsMask".."0x00000002", "FragmentShadingRateHorizontal2PixelsMask".."0x00000004", "FragmentShadingRateHorizontal4PixelsMask".."0x00000008" ) EnumConstant( "{@code SpvFPDenormMode}", "FPDenormModePreserve".."0", "FPDenormModeFlushToZero".."1", "FPDenormModeMax".."0x7fffffff" ) EnumConstant( "{@code SpvFPOperationMode}", "FPOperationModeIEEE".."0", "FPOperationModeALT".."1", "FPOperationModeMax".."0x7fffffff" ) EnumConstant( "{@code SpvQuantizationModes}", "QuantizationModesTRN".."0", "QuantizationModesTRN_ZERO".."1", "QuantizationModesRND".."2", "QuantizationModesRND_ZERO".."3", "QuantizationModesRND_INF".."4", "QuantizationModesRND_MIN_INF".."5", "QuantizationModesRND_CONV".."6", "QuantizationModesRND_CONV_ODD".."7", "QuantizationModesMax".."0x7fffffff" ) EnumConstant( "{@code SpvOverflowModes}", "OverflowModesWRAP".."0", "OverflowModesSAT".."1", "OverflowModesSAT_ZERO".."2", "OverflowModesSAT_SYM".."3", "OverflowModesMax".."0x7fffffff" ) EnumConstant( "{@code SpvPackedVectorFormat}", "PackedVectorFormatPackedVectorFormat4x8Bit".."0", "PackedVectorFormatPackedVectorFormat4x8BitKHR".."0", "PackedVectorFormatMax".."0x7fffffff" ) EnumConstant( "{@code SpvOp}", "OpNop".."0", "OpUndef".."1", "OpSourceContinued".."2", "OpSource".."3", "OpSourceExtension".."4", "OpName".."5", "OpMemberName".."6", "OpString".."7", "OpLine".."8", "OpExtension".."10", "OpExtInstImport".."11", "OpExtInst".."12", "OpMemoryModel".."14", "OpEntryPoint".."15", "OpExecutionMode".."16", "OpCapability".."17", "OpTypeVoid".."19", "OpTypeBool".."20", "OpTypeInt".."21", "OpTypeFloat".."22", "OpTypeVector".."23", "OpTypeMatrix".."24", "OpTypeImage".."25", "OpTypeSampler".."26", "OpTypeSampledImage".."27", "OpTypeArray".."28", "OpTypeRuntimeArray".."29", "OpTypeStruct".."30", "OpTypeOpaque".."31", "OpTypePointer".."32", "OpTypeFunction".."33", "OpTypeEvent".."34", "OpTypeDeviceEvent".."35", "OpTypeReserveId".."36", "OpTypeQueue".."37", "OpTypePipe".."38", "OpTypeForwardPointer".."39", "OpConstantTrue".."41", "OpConstantFalse".."42", "OpConstant".."43", "OpConstantComposite".."44", "OpConstantSampler".."45", "OpConstantNull".."46", "OpSpecConstantTrue".."48", "OpSpecConstantFalse".."49", "OpSpecConstant".."50", "OpSpecConstantComposite".."51", "OpSpecConstantOp".."52", "OpFunction".."54", "OpFunctionParameter".."55", "OpFunctionEnd".."56", "OpFunctionCall".."57", "OpVariable".."59", "OpImageTexelPointer".."60", "OpLoad".."61", "OpStore".."62", "OpCopyMemory".."63", "OpCopyMemorySized".."64", "OpAccessChain".."65", "OpInBoundsAccessChain".."66", "OpPtrAccessChain".."67", "OpArrayLength".."68", "OpGenericPtrMemSemantics".."69", "OpInBoundsPtrAccessChain".."70", "OpDecorate".."71", "OpMemberDecorate".."72", "OpDecorationGroup".."73", "OpGroupDecorate".."74", "OpGroupMemberDecorate".."75", "OpVectorExtractDynamic".."77", "OpVectorInsertDynamic".."78", "OpVectorShuffle".."79", "OpCompositeConstruct".."80", "OpCompositeExtract".."81", "OpCompositeInsert".."82", "OpCopyObject".."83", "OpTranspose".."84", "OpSampledImage".."86", "OpImageSampleImplicitLod".."87", "OpImageSampleExplicitLod".."88", "OpImageSampleDrefImplicitLod".."89", "OpImageSampleDrefExplicitLod".."90", "OpImageSampleProjImplicitLod".."91", "OpImageSampleProjExplicitLod".."92", "OpImageSampleProjDrefImplicitLod".."93", "OpImageSampleProjDrefExplicitLod".."94", "OpImageFetch".."95", "OpImageGather".."96", "OpImageDrefGather".."97", "OpImageRead".."98", "OpImageWrite".."99", "OpImage".."100", "OpImageQueryFormat".."101", "OpImageQueryOrder".."102", "OpImageQuerySizeLod".."103", "OpImageQuerySize".."104", "OpImageQueryLod".."105", "OpImageQueryLevels".."106", "OpImageQuerySamples".."107", "OpConvertFToU".."109", "OpConvertFToS".."110", "OpConvertSToF".."111", "OpConvertUToF".."112", "OpUConvert".."113", "OpSConvert".."114", "OpFConvert".."115", "OpQuantizeToF16".."116", "OpConvertPtrToU".."117", "OpSatConvertSToU".."118", "OpSatConvertUToS".."119", "OpConvertUToPtr".."120", "OpPtrCastToGeneric".."121", "OpGenericCastToPtr".."122", "OpGenericCastToPtrExplicit".."123", "OpBitcast".."124", "OpSNegate".."126", "OpFNegate".."127", "OpIAdd".."128", "OpFAdd".."129", "OpISub".."130", "OpFSub".."131", "OpIMul".."132", "OpFMul".."133", "OpUDiv".."134", "OpSDiv".."135", "OpFDiv".."136", "OpUMod".."137", "OpSRem".."138", "OpSMod".."139", "OpFRem".."140", "OpFMod".."141", "OpVectorTimesScalar".."142", "OpMatrixTimesScalar".."143", "OpVectorTimesMatrix".."144", "OpMatrixTimesVector".."145", "OpMatrixTimesMatrix".."146", "OpOuterProduct".."147", "OpDot".."148", "OpIAddCarry".."149", "OpISubBorrow".."150", "OpUMulExtended".."151", "OpSMulExtended".."152", "OpAny".."154", "OpAll".."155", "OpIsNan".."156", "OpIsInf".."157", "OpIsFinite".."158", "OpIsNormal".."159", "OpSignBitSet".."160", "OpLessOrGreater".."161", "OpOrdered".."162", "OpUnordered".."163", "OpLogicalEqual".."164", "OpLogicalNotEqual".."165", "OpLogicalOr".."166", "OpLogicalAnd".."167", "OpLogicalNot".."168", "OpSelect".."169", "OpIEqual".."170", "OpINotEqual".."171", "OpUGreaterThan".."172", "OpSGreaterThan".."173", "OpUGreaterThanEqual".."174", "OpSGreaterThanEqual".."175", "OpULessThan".."176", "OpSLessThan".."177", "OpULessThanEqual".."178", "OpSLessThanEqual".."179", "OpFOrdEqual".."180", "OpFUnordEqual".."181", "OpFOrdNotEqual".."182", "OpFUnordNotEqual".."183", "OpFOrdLessThan".."184", "OpFUnordLessThan".."185", "OpFOrdGreaterThan".."186", "OpFUnordGreaterThan".."187", "OpFOrdLessThanEqual".."188", "OpFUnordLessThanEqual".."189", "OpFOrdGreaterThanEqual".."190", "OpFUnordGreaterThanEqual".."191", "OpShiftRightLogical".."194", "OpShiftRightArithmetic".."195", "OpShiftLeftLogical".."196", "OpBitwiseOr".."197", "OpBitwiseXor".."198", "OpBitwiseAnd".."199", "OpNot".."200", "OpBitFieldInsert".."201", "OpBitFieldSExtract".."202", "OpBitFieldUExtract".."203", "OpBitReverse".."204", "OpBitCount".."205", "OpDPdx".."207", "OpDPdy".."208", "OpFwidth".."209", "OpDPdxFine".."210", "OpDPdyFine".."211", "OpFwidthFine".."212", "OpDPdxCoarse".."213", "OpDPdyCoarse".."214", "OpFwidthCoarse".."215", "OpEmitVertex".."218", "OpEndPrimitive".."219", "OpEmitStreamVertex".."220", "OpEndStreamPrimitive".."221", "OpControlBarrier".."224", "OpMemoryBarrier".."225", "OpAtomicLoad".."227", "OpAtomicStore".."228", "OpAtomicExchange".."229", "OpAtomicCompareExchange".."230", "OpAtomicCompareExchangeWeak".."231", "OpAtomicIIncrement".."232", "OpAtomicIDecrement".."233", "OpAtomicIAdd".."234", "OpAtomicISub".."235", "OpAtomicSMin".."236", "OpAtomicUMin".."237", "OpAtomicSMax".."238", "OpAtomicUMax".."239", "OpAtomicAnd".."240", "OpAtomicOr".."241", "OpAtomicXor".."242", "OpPhi".."245", "OpLoopMerge".."246", "OpSelectionMerge".."247", "OpLabel".."248", "OpBranch".."249", "OpBranchConditional".."250", "OpSwitch".."251", "OpKill".."252", "OpReturn".."253", "OpReturnValue".."254", "OpUnreachable".."255", "OpLifetimeStart".."256", "OpLifetimeStop".."257", "OpGroupAsyncCopy".."259", "OpGroupWaitEvents".."260", "OpGroupAll".."261", "OpGroupAny".."262", "OpGroupBroadcast".."263", "OpGroupIAdd".."264", "OpGroupFAdd".."265", "OpGroupFMin".."266", "OpGroupUMin".."267", "OpGroupSMin".."268", "OpGroupFMax".."269", "OpGroupUMax".."270", "OpGroupSMax".."271", "OpReadPipe".."274", "OpWritePipe".."275", "OpReservedReadPipe".."276", "OpReservedWritePipe".."277", "OpReserveReadPipePackets".."278", "OpReserveWritePipePackets".."279", "OpCommitReadPipe".."280", "OpCommitWritePipe".."281", "OpIsValidReserveId".."282", "OpGetNumPipePackets".."283", "OpGetMaxPipePackets".."284", "OpGroupReserveReadPipePackets".."285", "OpGroupReserveWritePipePackets".."286", "OpGroupCommitReadPipe".."287", "OpGroupCommitWritePipe".."288", "OpEnqueueMarker".."291", "OpEnqueueKernel".."292", "OpGetKernelNDrangeSubGroupCount".."293", "OpGetKernelNDrangeMaxSubGroupSize".."294", "OpGetKernelWorkGroupSize".."295", "OpGetKernelPreferredWorkGroupSizeMultiple".."296", "OpRetainEvent".."297", "OpReleaseEvent".."298", "OpCreateUserEvent".."299", "OpIsValidEvent".."300", "OpSetUserEventStatus".."301", "OpCaptureEventProfilingInfo".."302", "OpGetDefaultQueue".."303", "OpBuildNDRange".."304", "OpImageSparseSampleImplicitLod".."305", "OpImageSparseSampleExplicitLod".."306", "OpImageSparseSampleDrefImplicitLod".."307", "OpImageSparseSampleDrefExplicitLod".."308", "OpImageSparseSampleProjImplicitLod".."309", "OpImageSparseSampleProjExplicitLod".."310", "OpImageSparseSampleProjDrefImplicitLod".."311", "OpImageSparseSampleProjDrefExplicitLod".."312", "OpImageSparseFetch".."313", "OpImageSparseGather".."314", "OpImageSparseDrefGather".."315", "OpImageSparseTexelsResident".."316", "OpNoLine".."317", "OpAtomicFlagTestAndSet".."318", "OpAtomicFlagClear".."319", "OpImageSparseRead".."320", "OpSizeOf".."321", "OpTypePipeStorage".."322", "OpConstantPipeStorage".."323", "OpCreatePipeFromPipeStorage".."324", "OpGetKernelLocalSizeForSubgroupCount".."325", "OpGetKernelMaxNumSubgroups".."326", "OpTypeNamedBarrier".."327", "OpNamedBarrierInitialize".."328", "OpMemoryNamedBarrier".."329", "OpModuleProcessed".."330", "OpExecutionModeId".."331", "OpDecorateId".."332", "OpGroupNonUniformElect".."333", "OpGroupNonUniformAll".."334", "OpGroupNonUniformAny".."335", "OpGroupNonUniformAllEqual".."336", "OpGroupNonUniformBroadcast".."337", "OpGroupNonUniformBroadcastFirst".."338", "OpGroupNonUniformBallot".."339", "OpGroupNonUniformInverseBallot".."340", "OpGroupNonUniformBallotBitExtract".."341", "OpGroupNonUniformBallotBitCount".."342", "OpGroupNonUniformBallotFindLSB".."343", "OpGroupNonUniformBallotFindMSB".."344", "OpGroupNonUniformShuffle".."345", "OpGroupNonUniformShuffleXor".."346", "OpGroupNonUniformShuffleUp".."347", "OpGroupNonUniformShuffleDown".."348", "OpGroupNonUniformIAdd".."349", "OpGroupNonUniformFAdd".."350", "OpGroupNonUniformIMul".."351", "OpGroupNonUniformFMul".."352", "OpGroupNonUniformSMin".."353", "OpGroupNonUniformUMin".."354", "OpGroupNonUniformFMin".."355", "OpGroupNonUniformSMax".."356", "OpGroupNonUniformUMax".."357", "OpGroupNonUniformFMax".."358", "OpGroupNonUniformBitwiseAnd".."359", "OpGroupNonUniformBitwiseOr".."360", "OpGroupNonUniformBitwiseXor".."361", "OpGroupNonUniformLogicalAnd".."362", "OpGroupNonUniformLogicalOr".."363", "OpGroupNonUniformLogicalXor".."364", "OpGroupNonUniformQuadBroadcast".."365", "OpGroupNonUniformQuadSwap".."366", "OpCopyLogical".."400", "OpPtrEqual".."401", "OpPtrNotEqual".."402", "OpPtrDiff".."403", "OpTerminateInvocation".."4416", "OpSubgroupBallotKHR".."4421", "OpSubgroupFirstInvocationKHR".."4422", "OpSubgroupAllKHR".."4428", "OpSubgroupAnyKHR".."4429", "OpSubgroupAllEqualKHR".."4430", "OpGroupNonUniformRotateKHR".."4431", "OpSubgroupReadInvocationKHR".."4432", "OpTraceRayKHR".."4445", "OpExecuteCallableKHR".."4446", "OpConvertUToAccelerationStructureKHR".."4447", "OpIgnoreIntersectionKHR".."4448", "OpTerminateRayKHR".."4449", "OpSDot".."4450", "OpSDotKHR".."4450", "OpUDot".."4451", "OpUDotKHR".."4451", "OpSUDot".."4452", "OpSUDotKHR".."4452", "OpSDotAccSat".."4453", "OpSDotAccSatKHR".."4453", "OpUDotAccSat".."4454", "OpUDotAccSatKHR".."4454", "OpSUDotAccSat".."4455", "OpSUDotAccSatKHR".."4455", "OpTypeRayQueryKHR".."4472", "OpRayQueryInitializeKHR".."4473", "OpRayQueryTerminateKHR".."4474", "OpRayQueryGenerateIntersectionKHR".."4475", "OpRayQueryConfirmIntersectionKHR".."4476", "OpRayQueryProceedKHR".."4477", "OpRayQueryGetIntersectionTypeKHR".."4479", "OpGroupIAddNonUniformAMD".."5000", "OpGroupFAddNonUniformAMD".."5001", "OpGroupFMinNonUniformAMD".."5002", "OpGroupUMinNonUniformAMD".."5003", "OpGroupSMinNonUniformAMD".."5004", "OpGroupFMaxNonUniformAMD".."5005", "OpGroupUMaxNonUniformAMD".."5006", "OpGroupSMaxNonUniformAMD".."5007", "OpFragmentMaskFetchAMD".."5011", "OpFragmentFetchAMD".."5012", "OpReadClockKHR".."5056", "OpImageSampleFootprintNV".."5283", "OpGroupNonUniformPartitionNV".."5296", "OpWritePackedPrimitiveIndices4x8NV".."5299", "OpReportIntersectionKHR".."5334", "OpReportIntersectionNV".."5334", "OpIgnoreIntersectionNV".."5335", "OpTerminateRayNV".."5336", "OpTraceNV".."5337", "OpTraceMotionNV".."5338", "OpTraceRayMotionNV".."5339", "OpTypeAccelerationStructureKHR".."5341", "OpTypeAccelerationStructureNV".."5341", "OpExecuteCallableNV".."5344", "OpTypeCooperativeMatrixNV".."5358", "OpCooperativeMatrixLoadNV".."5359", "OpCooperativeMatrixStoreNV".."5360", "OpCooperativeMatrixMulAddNV".."5361", "OpCooperativeMatrixLengthNV".."5362", "OpBeginInvocationInterlockEXT".."5364", "OpEndInvocationInterlockEXT".."5365", "OpDemoteToHelperInvocation".."5380", "OpDemoteToHelperInvocationEXT".."5380", "OpIsHelperInvocationEXT".."5381", "OpConvertUToImageNV".."5391", "OpConvertUToSamplerNV".."5392", "OpConvertImageToUNV".."5393", "OpConvertSamplerToUNV".."5394", "OpConvertUToSampledImageNV".."5395", "OpConvertSampledImageToUNV".."5396", "OpSamplerImageAddressingModeNV".."5397", "OpSubgroupShuffleINTEL".."5571", "OpSubgroupShuffleDownINTEL".."5572", "OpSubgroupShuffleUpINTEL".."5573", "OpSubgroupShuffleXorINTEL".."5574", "OpSubgroupBlockReadINTEL".."5575", "OpSubgroupBlockWriteINTEL".."5576", "OpSubgroupImageBlockReadINTEL".."5577", "OpSubgroupImageBlockWriteINTEL".."5578", "OpSubgroupImageMediaBlockReadINTEL".."5580", "OpSubgroupImageMediaBlockWriteINTEL".."5581", "OpUCountLeadingZerosINTEL".."5585", "OpUCountTrailingZerosINTEL".."5586", "OpAbsISubINTEL".."5587", "OpAbsUSubINTEL".."5588", "OpIAddSatINTEL".."5589", "OpUAddSatINTEL".."5590", "OpIAverageINTEL".."5591", "OpUAverageINTEL".."5592", "OpIAverageRoundedINTEL".."5593", "OpUAverageRoundedINTEL".."5594", "OpISubSatINTEL".."5595", "OpUSubSatINTEL".."5596", "OpIMul32x16INTEL".."5597", "OpUMul32x16INTEL".."5598", "OpConstantFunctionPointerINTEL".."5600", "OpFunctionPointerCallINTEL".."5601", "OpAsmTargetINTEL".."5609", "OpAsmINTEL".."5610", "OpAsmCallINTEL".."5611", "OpAtomicFMinEXT".."5614", "OpAtomicFMaxEXT".."5615", "OpAssumeTrueKHR".."5630", "OpExpectKHR".."5631", "OpDecorateString".."5632", "OpDecorateStringGOOGLE".."5632", "OpMemberDecorateString".."5633", "OpMemberDecorateStringGOOGLE".."5633", "OpVmeImageINTEL".."5699", "OpTypeVmeImageINTEL".."5700", "OpTypeAvcImePayloadINTEL".."5701", "OpTypeAvcRefPayloadINTEL".."5702", "OpTypeAvcSicPayloadINTEL".."5703", "OpTypeAvcMcePayloadINTEL".."5704", "OpTypeAvcMceResultINTEL".."5705", "OpTypeAvcImeResultINTEL".."5706", "OpTypeAvcImeResultSingleReferenceStreamoutINTEL".."5707", "OpTypeAvcImeResultDualReferenceStreamoutINTEL".."5708", "OpTypeAvcImeSingleReferenceStreaminINTEL".."5709", "OpTypeAvcImeDualReferenceStreaminINTEL".."5710", "OpTypeAvcRefResultINTEL".."5711", "OpTypeAvcSicResultINTEL".."5712", "OpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL".."5713", "OpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL".."5714", "OpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL".."5715", "OpSubgroupAvcMceSetInterShapePenaltyINTEL".."5716", "OpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL".."5717", "OpSubgroupAvcMceSetInterDirectionPenaltyINTEL".."5718", "OpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL".."5719", "OpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL".."5720", "OpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL".."5721", "OpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL".."5722", "OpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL".."5723", "OpSubgroupAvcMceSetMotionVectorCostFunctionINTEL".."5724", "OpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL".."5725", "OpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL".."5726", "OpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL".."5727", "OpSubgroupAvcMceSetAcOnlyHaarINTEL".."5728", "OpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL".."5729", "OpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL".."5730", "OpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL".."5731", "OpSubgroupAvcMceConvertToImePayloadINTEL".."5732", "OpSubgroupAvcMceConvertToImeResultINTEL".."5733", "OpSubgroupAvcMceConvertToRefPayloadINTEL".."5734", "OpSubgroupAvcMceConvertToRefResultINTEL".."5735", "OpSubgroupAvcMceConvertToSicPayloadINTEL".."5736", "OpSubgroupAvcMceConvertToSicResultINTEL".."5737", "OpSubgroupAvcMceGetMotionVectorsINTEL".."5738", "OpSubgroupAvcMceGetInterDistortionsINTEL".."5739", "OpSubgroupAvcMceGetBestInterDistortionsINTEL".."5740", "OpSubgroupAvcMceGetInterMajorShapeINTEL".."5741", "OpSubgroupAvcMceGetInterMinorShapeINTEL".."5742", "OpSubgroupAvcMceGetInterDirectionsINTEL".."5743", "OpSubgroupAvcMceGetInterMotionVectorCountINTEL".."5744", "OpSubgroupAvcMceGetInterReferenceIdsINTEL".."5745", "OpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL".."5746", "OpSubgroupAvcImeInitializeINTEL".."5747", "OpSubgroupAvcImeSetSingleReferenceINTEL".."5748", "OpSubgroupAvcImeSetDualReferenceINTEL".."5749", "OpSubgroupAvcImeRefWindowSizeINTEL".."5750", "OpSubgroupAvcImeAdjustRefOffsetINTEL".."5751", "OpSubgroupAvcImeConvertToMcePayloadINTEL".."5752", "OpSubgroupAvcImeSetMaxMotionVectorCountINTEL".."5753", "OpSubgroupAvcImeSetUnidirectionalMixDisableINTEL".."5754", "OpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL".."5755", "OpSubgroupAvcImeSetWeightedSadINTEL".."5756", "OpSubgroupAvcImeEvaluateWithSingleReferenceINTEL".."5757", "OpSubgroupAvcImeEvaluateWithDualReferenceINTEL".."5758", "OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL".."5759", "OpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL".."5760", "OpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL".."5761", "OpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL".."5762", "OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL".."5763", "OpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL".."5764", "OpSubgroupAvcImeConvertToMceResultINTEL".."5765", "OpSubgroupAvcImeGetSingleReferenceStreaminINTEL".."5766", "OpSubgroupAvcImeGetDualReferenceStreaminINTEL".."5767", "OpSubgroupAvcImeStripSingleReferenceStreamoutINTEL".."5768", "OpSubgroupAvcImeStripDualReferenceStreamoutINTEL".."5769", "OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL".."5770", "OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL".."5771", "OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL".."5772", "OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL".."5773", "OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL".."5774", "OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL".."5775", "OpSubgroupAvcImeGetBorderReachedINTEL".."5776", "OpSubgroupAvcImeGetTruncatedSearchIndicationINTEL".."5777", "OpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL".."5778", "OpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL".."5779", "OpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL".."5780", "OpSubgroupAvcFmeInitializeINTEL".."5781", "OpSubgroupAvcBmeInitializeINTEL".."5782", "OpSubgroupAvcRefConvertToMcePayloadINTEL".."5783", "OpSubgroupAvcRefSetBidirectionalMixDisableINTEL".."5784", "OpSubgroupAvcRefSetBilinearFilterEnableINTEL".."5785", "OpSubgroupAvcRefEvaluateWithSingleReferenceINTEL".."5786", "OpSubgroupAvcRefEvaluateWithDualReferenceINTEL".."5787", "OpSubgroupAvcRefEvaluateWithMultiReferenceINTEL".."5788", "OpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL".."5789", "OpSubgroupAvcRefConvertToMceResultINTEL".."5790", "OpSubgroupAvcSicInitializeINTEL".."5791", "OpSubgroupAvcSicConfigureSkcINTEL".."5792", "OpSubgroupAvcSicConfigureIpeLumaINTEL".."5793", "OpSubgroupAvcSicConfigureIpeLumaChromaINTEL".."5794", "OpSubgroupAvcSicGetMotionVectorMaskINTEL".."5795", "OpSubgroupAvcSicConvertToMcePayloadINTEL".."5796", "OpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL".."5797", "OpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL".."5798", "OpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL".."5799", "OpSubgroupAvcSicSetBilinearFilterEnableINTEL".."5800", "OpSubgroupAvcSicSetSkcForwardTransformEnableINTEL".."5801", "OpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL".."5802", "OpSubgroupAvcSicEvaluateIpeINTEL".."5803", "OpSubgroupAvcSicEvaluateWithSingleReferenceINTEL".."5804", "OpSubgroupAvcSicEvaluateWithDualReferenceINTEL".."5805", "OpSubgroupAvcSicEvaluateWithMultiReferenceINTEL".."5806", "OpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL".."5807", "OpSubgroupAvcSicConvertToMceResultINTEL".."5808", "OpSubgroupAvcSicGetIpeLumaShapeINTEL".."5809", "OpSubgroupAvcSicGetBestIpeLumaDistortionINTEL".."5810", "OpSubgroupAvcSicGetBestIpeChromaDistortionINTEL".."5811", "OpSubgroupAvcSicGetPackedIpeLumaModesINTEL".."5812", "OpSubgroupAvcSicGetIpeChromaModeINTEL".."5813", "OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL".."5814", "OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL".."5815", "OpSubgroupAvcSicGetInterRawSadsINTEL".."5816", "OpVariableLengthArrayINTEL".."5818", "OpSaveMemoryINTEL".."5819", "OpRestoreMemoryINTEL".."5820", "OpArbitraryFloatSinCosPiINTEL".."5840", "OpArbitraryFloatCastINTEL".."5841", "OpArbitraryFloatCastFromIntINTEL".."5842", "OpArbitraryFloatCastToIntINTEL".."5843", "OpArbitraryFloatAddINTEL".."5846", "OpArbitraryFloatSubINTEL".."5847", "OpArbitraryFloatMulINTEL".."5848", "OpArbitraryFloatDivINTEL".."5849", "OpArbitraryFloatGTINTEL".."5850", "OpArbitraryFloatGEINTEL".."5851", "OpArbitraryFloatLTINTEL".."5852", "OpArbitraryFloatLEINTEL".."5853", "OpArbitraryFloatEQINTEL".."5854", "OpArbitraryFloatRecipINTEL".."5855", "OpArbitraryFloatRSqrtINTEL".."5856", "OpArbitraryFloatCbrtINTEL".."5857", "OpArbitraryFloatHypotINTEL".."5858", "OpArbitraryFloatSqrtINTEL".."5859", "OpArbitraryFloatLogINTEL".."5860", "OpArbitraryFloatLog2INTEL".."5861", "OpArbitraryFloatLog10INTEL".."5862", "OpArbitraryFloatLog1pINTEL".."5863", "OpArbitraryFloatExpINTEL".."5864", "OpArbitraryFloatExp2INTEL".."5865", "OpArbitraryFloatExp10INTEL".."5866", "OpArbitraryFloatExpm1INTEL".."5867", "OpArbitraryFloatSinINTEL".."5868", "OpArbitraryFloatCosINTEL".."5869", "OpArbitraryFloatSinCosINTEL".."5870", "OpArbitraryFloatSinPiINTEL".."5871", "OpArbitraryFloatCosPiINTEL".."5872", "OpArbitraryFloatASinINTEL".."5873", "OpArbitraryFloatASinPiINTEL".."5874", "OpArbitraryFloatACosINTEL".."5875", "OpArbitraryFloatACosPiINTEL".."5876", "OpArbitraryFloatATanINTEL".."5877", "OpArbitraryFloatATanPiINTEL".."5878", "OpArbitraryFloatATan2INTEL".."5879", "OpArbitraryFloatPowINTEL".."5880", "OpArbitraryFloatPowRINTEL".."5881", "OpArbitraryFloatPowNINTEL".."5882", "OpLoopControlINTEL".."5887", "OpAliasDomainDeclINTEL".."5911", "OpAliasScopeDeclINTEL".."5912", "OpAliasScopeListDeclINTEL".."5913", "OpFixedSqrtINTEL".."5923", "OpFixedRecipINTEL".."5924", "OpFixedRsqrtINTEL".."5925", "OpFixedSinINTEL".."5926", "OpFixedCosINTEL".."5927", "OpFixedSinCosINTEL".."5928", "OpFixedSinPiINTEL".."5929", "OpFixedCosPiINTEL".."5930", "OpFixedSinCosPiINTEL".."5931", "OpFixedLogINTEL".."5932", "OpFixedExpINTEL".."5933", "OpPtrCastToCrossWorkgroupINTEL".."5934", "OpCrossWorkgroupCastToPtrINTEL".."5938", "OpReadPipeBlockingINTEL".."5946", "OpWritePipeBlockingINTEL".."5947", "OpFPGARegINTEL".."5949", "OpRayQueryGetRayTMinKHR".."6016", "OpRayQueryGetRayFlagsKHR".."6017", "OpRayQueryGetIntersectionTKHR".."6018", "OpRayQueryGetIntersectionInstanceCustomIndexKHR".."6019", "OpRayQueryGetIntersectionInstanceIdKHR".."6020", "OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR".."6021", "OpRayQueryGetIntersectionGeometryIndexKHR".."6022", "OpRayQueryGetIntersectionPrimitiveIndexKHR".."6023", "OpRayQueryGetIntersectionBarycentricsKHR".."6024", "OpRayQueryGetIntersectionFrontFaceKHR".."6025", "OpRayQueryGetIntersectionCandidateAABBOpaqueKHR".."6026", "OpRayQueryGetIntersectionObjectRayDirectionKHR".."6027", "OpRayQueryGetIntersectionObjectRayOriginKHR".."6028", "OpRayQueryGetWorldRayDirectionKHR".."6029", "OpRayQueryGetWorldRayOriginKHR".."6030", "OpRayQueryGetIntersectionObjectToWorldKHR".."6031", "OpRayQueryGetIntersectionWorldToObjectKHR".."6032", "OpAtomicFAddEXT".."6035", "OpTypeBufferSurfaceINTEL".."6086", "OpTypeStructContinuedINTEL".."6090", "OpConstantCompositeContinuedINTEL".."6091", "OpSpecConstantCompositeContinuedINTEL".."6092", "OpControlBarrierArriveINTEL".."6142", "OpControlBarrierWaitINTEL".."6143", "OpGroupIMulKHR".."6401", "OpGroupFMulKHR".."6402", "OpGroupBitwiseAndKHR".."6403", "OpGroupBitwiseOrKHR".."6404", "OpGroupBitwiseXorKHR".."6405", "OpGroupLogicalAndKHR".."6406", "OpGroupLogicalOrKHR".."6407", "OpGroupLogicalXorKHR".."6408", "OpMax".."0x7fffffff", ) }
bsd-3-clause
b1c24a0390afe179b43fcec8349b7f96
39.598964
104
0.639709
5.005494
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/creator/BuildSystemWizardStep.kt
1
4112
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.creator import com.demonwav.mcdev.buildsystem.BuildSystem import com.demonwav.mcdev.buildsystem.gradle.GradleBuildSystem import com.demonwav.mcdev.buildsystem.maven.MavenBuildSystem import com.demonwav.mcdev.exception.EmptyFieldSetupException import com.demonwav.mcdev.exception.OtherSetupException import com.demonwav.mcdev.exception.SetupException import com.demonwav.mcdev.platform.forge.ForgeProjectConfiguration import com.demonwav.mcdev.platform.liteloader.LiteLoaderProjectConfiguration import com.demonwav.mcdev.platform.sponge.SpongeProjectConfiguration import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.ui.awt.RelativePoint import javax.swing.JComboBox import javax.swing.JPanel import javax.swing.JTextField class BuildSystemWizardStep(private val creator: MinecraftProjectCreator) : ModuleWizardStep() { private lateinit var groupIdField: JTextField private lateinit var artifactIdField: JTextField private lateinit var versionField: JTextField private lateinit var panel: JPanel private lateinit var buildSystemBox: JComboBox<String> override fun getComponent() = panel override fun updateStep() { if (creator.configs.size > 1) { buildSystemBox.selectedIndex = 1 buildSystemBox.isVisible = false return } when { creator.configs.any { s -> s is ForgeProjectConfiguration || s is LiteLoaderProjectConfiguration } -> { buildSystemBox.selectedIndex = 1 buildSystemBox.setVisible(false) } creator.configs.any { s -> s is SpongeProjectConfiguration } -> { buildSystemBox.selectedIndex = 1 buildSystemBox.setVisible(true) } else -> { buildSystemBox.selectedIndex = 0 buildSystemBox.setVisible(true) } } } override fun updateDataModel() {} override fun onStepLeaving() { creator.buildSystem = createBuildSystem() } private fun createBuildSystem(): BuildSystem { return if (buildSystemBox.selectedIndex == 0) { MavenBuildSystem(artifactIdField.text, groupIdField.text, versionField.text) } else { GradleBuildSystem(artifactIdField.text, groupIdField.text, versionField.text) } } override fun validate(): Boolean { try { if (groupIdField.text.isEmpty()) { throw EmptyFieldSetupException(groupIdField) } if (artifactIdField.text.isEmpty()) { throw EmptyFieldSetupException(artifactIdField) } if (versionField.text.isBlank()) { throw EmptyFieldSetupException(versionField) } if (!groupIdField.text.matches(NO_WHITESPACE)) { throw OtherSetupException("The GroupId field cannot contain any whitespace", groupIdField) } if (!artifactIdField.text.matches(NO_WHITESPACE)) { throw OtherSetupException("The ArtifactId field cannot contain any whitespace", artifactIdField) } if (creator.configs.any { s -> s is ForgeProjectConfiguration } && buildSystemBox.selectedIndex == 0) { throw OtherSetupException("Forge does not support Maven", buildSystemBox) } } catch (e: SetupException) { JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(e.error, MessageType.ERROR, null) .setFadeoutTime(2000) .createBalloon() .show(RelativePoint.getSouthWestOf(e.j), Balloon.Position.below) return false } return true } companion object { val NO_WHITESPACE = Regex("\\S+") } }
mit
35805eb9f87749d60d40887d2a71f22b
34.448276
115
0.668288
5.165829
false
true
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ContentRootTestEntityImpl.kt
1
13860
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.extractOneToOneChild import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ContentRootTestEntityImpl(val dataSource: ContentRootTestEntityData) : ContentRootTestEntity, WorkspaceEntityBase() { companion object { internal val MODULE_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleTestEntity::class.java, ContentRootTestEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val SOURCEROOTORDER_CONNECTION_ID: ConnectionId = ConnectionId.create(ContentRootTestEntity::class.java, SourceRootTestOrderEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) internal val SOURCEROOTS_CONNECTION_ID: ConnectionId = ConnectionId.create(ContentRootTestEntity::class.java, SourceRootTestEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( MODULE_CONNECTION_ID, SOURCEROOTORDER_CONNECTION_ID, SOURCEROOTS_CONNECTION_ID, ) } override val module: ModuleTestEntity get() = snapshot.extractOneToManyParent(MODULE_CONNECTION_ID, this)!! override val sourceRootOrder: SourceRootTestOrderEntity? get() = snapshot.extractOneToOneChild(SOURCEROOTORDER_CONNECTION_ID, this) override val sourceRoots: List<SourceRootTestEntity> get() = snapshot.extractOneToManyChildren<SourceRootTestEntity>(SOURCEROOTS_CONNECTION_ID, this)!!.toList() override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ContentRootTestEntityData?) : ModifiableWorkspaceEntityBase<ContentRootTestEntity>(), ContentRootTestEntity.Builder { constructor() : this(ContentRootTestEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ContentRootTestEntity 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().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(MODULE_CONNECTION_ID, this) == null) { error("Field ContentRootTestEntity#module should be initialized") } } else { if (this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] == null) { error("Field ContentRootTestEntity#module should be initialized") } } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(SOURCEROOTS_CONNECTION_ID, this) == null) { error("Field ContentRootTestEntity#sourceRoots should be initialized") } } else { if (this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] == null) { error("Field ContentRootTestEntity#sourceRoots should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ContentRootTestEntity this.entitySource = dataSource.entitySource if (parents != null) { this.module = parents.filterIsInstance<ModuleTestEntity>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var module: ModuleTestEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(MODULE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleTestEntity } else { this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleTestEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToManyParentOfChild(MODULE_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] = value } changedProperty.add("module") } override var sourceRootOrder: SourceRootTestOrderEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(SOURCEROOTORDER_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] as? SourceRootTestOrderEntity } else { this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] as? SourceRootTestOrderEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, SOURCEROOTORDER_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(SOURCEROOTORDER_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, SOURCEROOTORDER_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] = value } changedProperty.add("sourceRootOrder") } // List of non-abstract referenced types var _sourceRoots: List<SourceRootTestEntity>? = emptyList() override var sourceRoots: List<SourceRootTestEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<SourceRootTestEntity>(SOURCEROOTS_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink( true, SOURCEROOTS_CONNECTION_ID)] as? List<SourceRootTestEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] as? List<SourceRootTestEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(SOURCEROOTS_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, SOURCEROOTS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] = value } changedProperty.add("sourceRoots") } override fun getEntityData(): ContentRootTestEntityData = result ?: super.getEntityData() as ContentRootTestEntityData override fun getEntityClass(): Class<ContentRootTestEntity> = ContentRootTestEntity::class.java } } class ContentRootTestEntityData : WorkspaceEntityData<ContentRootTestEntity>() { override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ContentRootTestEntity> { val modifiable = ContentRootTestEntityImpl.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): ContentRootTestEntity { return getCached(snapshot) { val entity = ContentRootTestEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ContentRootTestEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ContentRootTestEntity(entitySource) { this.module = parents.filterIsInstance<ModuleTestEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(ModuleTestEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ContentRootTestEntityData 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 ContentRootTestEntityData return true } override fun hashCode(): Int { var result = entitySource.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
f9d1a677a5961ed7ff0addf516b8d1b1
40.25
166
0.671284
5.550661
false
true
false
false
RuneSuite/client
plugins-dev/src/main/java/org/runestar/client/plugins/dev/EvictingHashTableDebug.kt
1
1076
package org.runestar.client.plugins.dev import org.kxtra.slf4j.info import org.runestar.client.api.plugins.DisposablePlugin import org.runestar.client.raw.access.XEvictingDualNodeHashTable import org.runestar.client.api.plugins.PluginSettings class EvictingHashTableDebug : DisposablePlugin<PluginSettings>() { override val defaultSettings = PluginSettings() override fun onStart() { add(XEvictingDualNodeHashTable.get.exit.filter { it.returned == null && it.instance.remainingCapacity == 0 }.subscribe { val stack = Throwable().stackTrace.asList() .drop(7) .dropLast(1) .filter { !it.methodName.contains('$') } .map { "${it.className}.${it.methodName}" } val elementType = it.instance.deque.sentinel.nextDual.javaClass.interfaces.firstOrNull()?.simpleName ?: "?" logger.info { "Cache miss: ${it.arguments[0]} in ${it.instance}(capacity=${it.instance.capacity}, type=$elementType) at $stack" } }) } }
mit
b74bd6e2e82284cd16131fbf331c8c2d
42.08
129
0.644981
4.33871
false
false
false
false
google/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/expressions.kt
1
14903
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.tree.TokenSet import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.config.AnalysisFlags import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.idea.base.projectStructure.ExternalCompilerVersionProvider import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.compiler.configuration.KotlinJpsPluginSettings import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.nj2k.conversions.RecursiveApplicableConversionBase import org.jetbrains.kotlin.nj2k.symbols.JKMethodSymbol import org.jetbrains.kotlin.nj2k.symbols.JKSymbol import org.jetbrains.kotlin.nj2k.symbols.JKUnresolvedMethod import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.JKNoType import org.jetbrains.kotlin.nj2k.types.JKType import org.jetbrains.kotlin.nj2k.types.JKTypeFactory import org.jetbrains.kotlin.nj2k.types.replaceJavaClassWithKotlinClassType import org.jetbrains.kotlin.resolve.annotations.KOTLIN_THROWS_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.utils.addToStdlib.cast import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.safeAs fun JKOperator.isEquals() = token.safeAs<JKKtSingleValueOperatorToken>()?.psiToken in equalsOperators private val equalsOperators = TokenSet.create( KtTokens.EQEQEQ, KtTokens.EXCLEQEQEQ, KtTokens.EQEQ, KtTokens.EXCLEQ ) fun untilToExpression( from: JKExpression, to: JKExpression, conversionContext: NewJ2kConverterContext ): JKExpression { val isPossibleToUseRangeUntil = conversionContext.converter.targetModule ?.let { it.languageVersionSettings.isPossibleToUseRangeUntil(it, conversionContext.project) } == true return rangeExpression( from, to, if (isPossibleToUseRangeUntil) "..<" else "until", conversionContext ) } fun downToExpression( from: JKExpression, to: JKExpression, conversionContext: NewJ2kConverterContext ): JKExpression = rangeExpression( from, to, "downTo", conversionContext ) fun JKExpression.parenthesizeIfCompoundExpression() = when (this) { is JKIfElseExpression, is JKBinaryExpression, is JKTypeCastExpression -> JKParenthesizedExpression(this) else -> this } fun JKExpression.parenthesize() = JKParenthesizedExpression(this) fun rangeExpression( from: JKExpression, to: JKExpression, operatorName: String, conversionContext: NewJ2kConverterContext ): JKExpression = JKBinaryExpression( from, to, JKKtOperatorImpl( JKKtWordOperatorToken(operatorName), conversionContext.symbolProvider.provideMethodSymbol("kotlin.ranges.$operatorName").returnType!! ) ) fun blockStatement(vararg statements: JKStatement) = JKBlockStatement(JKBlockImpl(statements.toList())) fun blockStatement(statements: List<JKStatement>) = JKBlockStatement(JKBlockImpl(statements)) fun useExpression( receiver: JKExpression, variableIdentifier: JKNameIdentifier?, body: JKStatement, symbolProvider: JKSymbolProvider ): JKExpression { val useSymbol = symbolProvider.provideMethodSymbol("kotlin.io.use") val lambdaParameter = if (variableIdentifier != null) JKParameter(JKTypeElement(JKNoType), variableIdentifier) else null val lambda = JKLambdaExpression( body, listOfNotNull(lambdaParameter) ) val methodCall = JKCallExpressionImpl( useSymbol, listOf(lambda).toArgumentList() ) return JKQualifiedExpression(receiver, methodCall) } fun kotlinAssert(assertion: JKExpression, message: JKExpression?, typeFactory: JKTypeFactory) = JKCallExpressionImpl( JKUnresolvedMethod(//TODO resolve assert "assert", typeFactory, typeFactory.types.unit ), listOfNotNull(assertion, message).toArgumentList() ) fun jvmAnnotation(name: String, symbolProvider: JKSymbolProvider) = JKAnnotation( symbolProvider.provideClassSymbol("kotlin.jvm.$name") ) fun throwAnnotation(throws: List<JKType>, symbolProvider: JKSymbolProvider) = JKAnnotation( symbolProvider.provideClassSymbol(KOTLIN_THROWS_ANNOTATION_FQ_NAME.asString()), throws.map { JKAnnotationParameterImpl( JKClassLiteralExpression(JKTypeElement(it), JKClassLiteralExpression.ClassLiteralType.KOTLIN_CLASS) ) } ) fun JKAnnotationList.annotationByFqName(fqName: String): JKAnnotation? = annotations.firstOrNull { it.classSymbol.fqName == fqName } fun stringLiteral(content: String, typeFactory: JKTypeFactory): JKExpression { val lines = content.split('\n') return lines.mapIndexed { i, line -> val newlineSeparator = if (i == lines.size - 1) "" else "\\n" JKLiteralExpression("\"$line$newlineSeparator\"", JKLiteralExpression.LiteralType.STRING) }.reduce { acc: JKExpression, literalExpression: JKLiteralExpression -> JKBinaryExpression(acc, literalExpression, JKKtOperatorImpl(JKOperatorToken.PLUS, typeFactory.types.string)) } } fun JKVariable.findUsages(scope: JKTreeElement, context: NewJ2kConverterContext): List<JKFieldAccessExpression> { val symbol = context.symbolProvider.provideUniverseSymbol(this) val usages = mutableListOf<JKFieldAccessExpression>() val searcher = object : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element is JKExpression) { element.unboxFieldReference()?.also { if (it.identifier == symbol) { usages += it } } } return recurse(element) } } searcher.runConversion(scope, context) return usages } internal fun JKTreeElement.forEachDescendant(action: (JKElement) -> Unit) { action(this) this.forEachChild { it.forEachDescendant(action) } } internal inline fun <reified E: JKElement> JKTreeElement.forEachDescendantOfType(crossinline action: (E) -> Unit) { forEachDescendant { if (it is E) action(it) } } fun JKExpression.unboxFieldReference(): JKFieldAccessExpression? = when { this is JKFieldAccessExpression -> this this is JKQualifiedExpression && receiver is JKThisExpression -> selector as? JKFieldAccessExpression else -> null } fun JKFieldAccessExpression.asAssignmentFromTarget(): JKKtAssignmentStatement? = parent.safeAs<JKKtAssignmentStatement>()?.takeIf { it.field == this } fun JKFieldAccessExpression.isInDecrementOrIncrement(): Boolean = when (parent.safeAs<JKUnaryExpression>()?.operator?.token) { JKOperatorToken.PLUSPLUS, JKOperatorToken.MINUSMINUS -> true else -> false } fun JKVariable.hasWritableUsages(scope: JKTreeElement, context: NewJ2kConverterContext): Boolean = findUsages(scope, context).any { it.asAssignmentFromTarget() != null || it.isInDecrementOrIncrement() } fun equalsExpression(left: JKExpression, right: JKExpression, typeFactory: JKTypeFactory) = JKBinaryExpression( left, right, JKKtOperatorImpl( JKOperatorToken.EQEQ, typeFactory.types.boolean ) ) fun createCompanion(declarations: List<JKDeclaration>): JKClass = JKClass( JKNameIdentifier(""), JKInheritanceInfo(emptyList(), emptyList()), JKClass.ClassKind.COMPANION, JKTypeParameterList(), JKClassBody(declarations), JKAnnotationList(), emptyList(), JKVisibilityModifierElement(Visibility.PUBLIC), JKModalityModifierElement(Modality.FINAL) ) fun JKClass.getCompanion(): JKClass? = declarationList.firstOrNull { it is JKClass && it.classKind == JKClass.ClassKind.COMPANION } as? JKClass fun JKClass.getOrCreateCompanionObject(): JKClass = getCompanion() ?: createCompanion(declarations = emptyList()) .also { classBody.declarations += it } fun runExpression(body: JKStatement, symbolProvider: JKSymbolProvider): JKExpression { val lambda = JKLambdaExpression( body, emptyList() ) return JKCallExpressionImpl( symbolProvider.provideMethodSymbol("kotlin.run"), listOf(lambda).toArgumentList() ) } fun assignmentStatement(target: JKVariable, expression: JKExpression, symbolProvider: JKSymbolProvider): JKKtAssignmentStatement = JKKtAssignmentStatement( field = JKFieldAccessExpression(symbolProvider.provideUniverseSymbol(target)), expression = expression, token = JKOperatorToken.EQ, ) fun JKAnnotationMemberValue.toExpression(symbolProvider: JKSymbolProvider): JKExpression { fun handleAnnotationParameter(element: JKTreeElement): JKTreeElement = when (element) { is JKClassLiteralExpression -> element.also { element.literalType = JKClassLiteralExpression.ClassLiteralType.KOTLIN_CLASS } is JKTypeElement -> JKTypeElement( element.type.replaceJavaClassWithKotlinClassType(symbolProvider), element::annotationList.detached() ) else -> applyRecursive(element, ::handleAnnotationParameter) } return handleAnnotationParameter( when (this) { is JKStubExpression -> this is JKAnnotation -> JKNewExpression( classSymbol, JKArgumentList( arguments.map { argument -> val value = argument.value.copyTreeAndDetach().toExpression(symbolProvider) when (argument) { is JKAnnotationNameParameter -> JKNamedArgument(value, JKNameIdentifier(argument.name.value)) else -> JKArgumentImpl(value) } } ), JKTypeArgumentList() ) is JKKtAnnotationArrayInitializerExpression -> JKKtAnnotationArrayInitializerExpression(initializers.map { it.detached(this).toExpression(symbolProvider) }) is JKExpression -> this else -> error("Bad initializer") } ) as JKExpression } fun JKExpression.asLiteralTextWithPrefix(): String? = when { this is JKPrefixExpression && (operator.token == JKOperatorToken.MINUS || operator.token == JKOperatorToken.PLUS) && expression is JKLiteralExpression -> operator.token.text + expression.cast<JKLiteralExpression>().literal this is JKLiteralExpression -> literal else -> null } fun JKClass.primaryConstructor(): JKKtPrimaryConstructor? = classBody.declarations.firstIsInstanceOrNull() fun List<JKExpression>.toArgumentList(): JKArgumentList = JKArgumentList(map { JKArgumentImpl(it) }) fun JKExpression.asStatement(): JKExpressionStatement = JKExpressionStatement(this) fun <T : JKExpression> T.nullIfStubExpression(): T? = if (this is JKStubExpression) null else this fun JKExpression.qualified(qualifier: JKExpression?) = if (qualifier != null && qualifier !is JKStubExpression) { JKQualifiedExpression(qualifier, this) } else this fun JKExpression.callOn( symbol: JKMethodSymbol, arguments: List<JKExpression> = emptyList(), typeArguments: List<JKTypeElement> = emptyList() ) = JKQualifiedExpression( this, JKCallExpressionImpl( symbol, JKArgumentList(arguments.map { JKArgumentImpl(it) }), JKTypeArgumentList(typeArguments) ) ) val JKStatement.statements: List<JKStatement> get() = when (this) { is JKBlockStatement -> block.statements else -> listOf(this) } val JKElement.psi: PsiElement? get() = (this as? PsiOwner)?.psi inline fun <reified Elem : PsiElement> JKElement.psi(): Elem? = (this as? PsiOwner)?.psi as? Elem fun JKTypeElement.present(): Boolean = type != JKNoType fun JKStatement.isEmpty(): Boolean = when (this) { is JKEmptyStatement -> true is JKBlockStatement -> block is JKBodyStub is JKExpressionStatement -> expression is JKStubExpression else -> false } fun JKInheritanceInfo.present(): Boolean = extends.isNotEmpty() || implements.isNotEmpty() fun JKClass.isLocalClass(): Boolean = parent !is JKClassBody && parent !is JKFile val JKClass.declarationList: List<JKDeclaration> get() = classBody.declarations val JKTreeElement.identifier: JKSymbol? get() = when (this) { is JKFieldAccessExpression -> identifier is JKCallExpression -> identifier is JKClassAccessExpression -> identifier is JKPackageAccessExpression -> identifier is JKNewExpression -> classSymbol else -> null } val JKClass.isObjectOrCompanionObject get() = classKind == JKClass.ClassKind.OBJECT || classKind == JKClass.ClassKind.COMPANION const val EXPERIMENTAL_STDLIB_API_ANNOTATION = "kotlin.ExperimentalStdlibApi" @ApiStatus.Internal fun LanguageVersionSettings.isPossibleToUseRangeUntil(module: Module, project: Project): Boolean = areKotlinVersionsSufficientToUseRangeUntil(module, project) && FqName(EXPERIMENTAL_STDLIB_API_ANNOTATION).asString() in getFlag(AnalysisFlags.optIn) /** * Checks that compilerVersion and languageVersion (or -XXLanguage:+RangeUntilOperator) versions are high enough to use rangeUntil * operator. * * Note that this check is not enough. You also need to check for OptIn (because stdlib declarations are annotated with OptIn) */ @ApiStatus.Internal fun LanguageVersionSettings.areKotlinVersionsSufficientToUseRangeUntil(module: Module, project: Project): Boolean { val compilerVersion = ExternalCompilerVersionProvider.get(module) ?: IdeKotlinVersion.opt(KotlinJpsPluginSettings.jpsVersion(project)) ?: return false // `rangeUntil` is added to languageVersion 1.8 only since 1.7.20-Beta compiler return compilerVersion >= COMPILER_VERSION_WITH_RANGEUNTIL_SUPPORT && supportsFeature(LanguageFeature.RangeUntilOperator) } private val COMPILER_VERSION_WITH_RANGEUNTIL_SUPPORT = IdeKotlinVersion.get("1.7.20-Beta")
apache-2.0
62da237d5407ef0228016baff6258f75
35.980149
130
0.70979
5.249384
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/DynamicPlugins.kt
1
56815
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.plugins import com.fasterxml.jackson.databind.type.TypeFactory import com.intellij.openapi.util.registry.RegistryManager import com.intellij.configurationStore.jdomSerializer import com.intellij.configurationStore.runInAutoSaveDisabledMode import com.intellij.configurationStore.saveProjectsAndApp import com.intellij.diagnostic.MessagePool import com.intellij.diagnostic.PerformanceWatcher import com.intellij.diagnostic.hprof.action.SystemTempFilenameSupplier import com.intellij.diagnostic.hprof.analysis.AnalyzeClassloaderReferencesGraph import com.intellij.diagnostic.hprof.analysis.HProfAnalysis import com.intellij.ide.DataManager import com.intellij.ide.IdeBundle import com.intellij.ide.IdeEventQueue import com.intellij.ide.SaveAndSyncHandler import com.intellij.ide.actions.RevealFileAction import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.impl.runBlockingUnderModalProgress import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.ide.plugins.cl.PluginClassLoader import com.intellij.ide.ui.TopHitCache import com.intellij.ide.ui.UIThemeProvider import com.intellij.ide.util.TipAndTrickManager import com.intellij.idea.IdeaLogger import com.intellij.lang.Language import com.intellij.notification.NotificationType import com.intellij.notification.NotificationsManager import com.intellij.notification.impl.NotificationsManagerImpl import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.impl.ActionManagerImpl import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.actionSystem.impl.PresentationFactory import com.intellij.openapi.application.Application import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.application.impl.LaterInvocator import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionDescriptor import com.intellij.openapi.extensions.ExtensionPointDescriptor import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.keymap.impl.BundledKeymapBean import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.PotemkinProgress import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.impl.ProjectManagerImpl import com.intellij.openapi.updateSettings.impl.UpdateChecker import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.objectTree.ThrowableInterner import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.newvfs.FileAttribute import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.impl.IdeFrameImpl import com.intellij.openapi.wm.impl.ProjectFrameHelper import com.intellij.psi.util.CachedValuesManager import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.ui.IconDeferrer import com.intellij.ui.mac.touchbar.TouchbarSupport import com.intellij.util.CachedValuesManagerImpl import com.intellij.util.MemoryDumpHelper import com.intellij.util.ReflectionUtil import com.intellij.util.SystemProperties import com.intellij.util.containers.WeakList import com.intellij.util.messages.impl.MessageBusEx import com.intellij.util.ref.GCWatcher import net.sf.cglib.core.ClassNameReader import java.awt.KeyboardFocusManager import java.awt.Window import java.nio.channels.FileChannel import java.nio.file.Paths import java.nio.file.StandardOpenOption import java.text.SimpleDateFormat import java.util.* import java.util.function.Predicate import javax.swing.JComponent import javax.swing.ToolTipManager import kotlin.collections.component1 import kotlin.collections.component2 private val LOG = logger<DynamicPlugins>() private val classloadersFromUnloadedPlugins = mutableMapOf<PluginId, WeakList<PluginClassLoader>>() object DynamicPlugins { @JvmStatic @JvmOverloads fun allowLoadUnloadWithoutRestart(descriptor: IdeaPluginDescriptorImpl, baseDescriptor: IdeaPluginDescriptorImpl? = null, context: List<IdeaPluginDescriptorImpl> = emptyList()): Boolean { val reason = checkCanUnloadWithoutRestart(module = descriptor, parentModule = baseDescriptor, context = context) if (reason != null) { LOG.info(reason) } return reason == null } /** * @return true if the requested enabled state was applied without restart, false if restart is required */ fun loadPlugins(descriptors: Collection<IdeaPluginDescriptor>): Boolean { return updateDescriptorsWithoutRestart(descriptors, load = true) { loadPlugin(it, checkImplementationDetailDependencies = true) } } /** * @return true if the requested enabled state was applied without restart, false if restart is required */ fun unloadPlugins( descriptors: Collection<IdeaPluginDescriptor>, project: Project? = null, parentComponent: JComponent? = null, options: UnloadPluginOptions = UnloadPluginOptions(disable = true), ): Boolean { return updateDescriptorsWithoutRestart(descriptors, load = false) { unloadPluginWithProgress(project, parentComponent, it, options) } } private fun updateDescriptorsWithoutRestart( plugins: Collection<IdeaPluginDescriptor>, load: Boolean, executor: (IdeaPluginDescriptorImpl) -> Boolean, ): Boolean { if (plugins.isEmpty()) { return true } val pluginSet = PluginManagerCore.getPluginSet() @Suppress("UNCHECKED_CAST") val descriptors = (plugins as Collection<IdeaPluginDescriptorImpl>).filter { pluginSet.isPluginEnabled(it.pluginId) != load } val operationText = if (load) "load" else "unload" val message = descriptors.joinToString(prefix = "Plugins to $operationText: [", postfix = "]") LOG.info(message) if (!descriptors.all { allowLoadUnloadWithoutRestart(it, context = descriptors) }) { return false } // todo plugin installation should be done not in this method var allPlugins = pluginSet.allPlugins for (descriptor in descriptors) { if (!allPlugins.contains(descriptor)) { allPlugins = allPlugins + descriptor } } // todo make internal: // 1) ModuleGraphBase; // 2) SortedModuleGraph; // 3) SortedModuleGraph.topologicalComparator; // 4) PluginSetBuilder.sortedModuleGraph. var comparator = PluginSetBuilder(allPlugins) .moduleGraph .topologicalComparator if (!load) { comparator = comparator.reversed() } for (descriptor in descriptors.sortedWith(comparator)) { descriptor.isEnabled = load if (!executor.invoke(descriptor)) { LOG.info("Failed to $operationText: $descriptor, restart required") InstalledPluginsState.getInstance().isRestartRequired = true return false } } return true } fun checkCanUnloadWithoutRestart(module: IdeaPluginDescriptorImpl): String? { return checkCanUnloadWithoutRestart(module, parentModule = null) } /** * @param context Plugins which are being loaded at the same time as [module] */ private fun checkCanUnloadWithoutRestart(module: IdeaPluginDescriptorImpl, parentModule: IdeaPluginDescriptorImpl?, optionalDependencyPluginId: PluginId? = null, context: List<IdeaPluginDescriptorImpl> = emptyList(), checkImplementationDetailDependencies: Boolean = true): String? { if (parentModule == null) { if (module.isRequireRestart) { return "Plugin ${module.pluginId} is explicitly marked as requiring restart" } if (module.productCode != null && !module.isBundled && !PluginManagerCore.isDevelopedByJetBrains(module)) { return "Plugin ${module.pluginId} is a paid plugin" } if (InstalledPluginsState.getInstance().isRestartRequired) { return InstalledPluginsState.RESTART_REQUIRED_MESSAGE } } val pluginSet = PluginManagerCore.getPluginSet() if (classloadersFromUnloadedPlugins[module.pluginId]?.isEmpty() == false) { return "Not allowing load/unload of ${module.pluginId} because of incomplete previous unload operation for that plugin" } findMissingRequiredDependency(module, context, pluginSet)?.let { pluginDependency -> return "Required dependency ${pluginDependency} of plugin ${module.pluginId} is not currently loaded" } val app = ApplicationManager.getApplication() if (parentModule == null) { if (!RegistryManager.getInstance().`is`("ide.plugins.allow.unload")) { if (!allowLoadUnloadSynchronously(module)) { return "ide.plugins.allow.unload is disabled and synchronous load/unload is not possible for ${module.pluginId}" } return null } try { app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).checkUnloadPlugin(module) } catch (e: CannotUnloadPluginException) { return e.cause?.localizedMessage ?: "checkUnloadPlugin listener blocked plugin unload" } } if (!Registry.`is`("ide.plugins.allow.unload.from.sources")) { if (pluginSet.findEnabledPlugin(module.pluginId) != null && module === parentModule && !module.isUseIdeaClassLoader) { val pluginClassLoader = module.pluginClassLoader if (pluginClassLoader != null && pluginClassLoader !is PluginClassLoader && !app.isUnitTestMode) { return "Plugin ${module.pluginId} is not unload-safe because of use of ${pluginClassLoader.javaClass.name} as the default class loader. " + "For example, the IDE is started from the sources with the plugin." } } } val epNameToExtensions = module.epNameToExtensions if (epNameToExtensions != null) { doCheckExtensionsCanUnloadWithoutRestart( extensions = epNameToExtensions, descriptor = module, baseDescriptor = parentModule, app = app, optionalDependencyPluginId = optionalDependencyPluginId, context = context, pluginSet = pluginSet, )?.let { return it } } checkNoComponentsOrServiceOverrides(module)?.let { return it } ActionManagerImpl.checkUnloadActions(module)?.let { return it } for (moduleRef in module.content.modules) { if (pluginSet.isModuleEnabled(moduleRef.name)) { val subModule = moduleRef.requireDescriptor() checkCanUnloadWithoutRestart(module = subModule, parentModule = module, optionalDependencyPluginId = null, context = context)?.let { return "$it in optional dependency on ${subModule.pluginId}" } } } for (dependency in module.pluginDependencies) { if (pluginSet.isPluginEnabled(dependency.pluginId)) { checkCanUnloadWithoutRestart(dependency.subDescriptor ?: continue, parentModule ?: module, null, context)?.let { return "$it in optional dependency on ${dependency.pluginId}" } } } // if not a sub plugin descriptor, then check that any dependent plugin also reloadable if (parentModule != null && module !== parentModule) { return null } var dependencyMessage: String? = null processOptionalDependenciesOnPlugin(module, pluginSet, isLoaded = true) { mainDescriptor, subDescriptor -> if (subDescriptor.packagePrefix == null || mainDescriptor.pluginId.idString == "org.jetbrains.kotlin" || mainDescriptor.pluginId == PluginManagerCore.JAVA_PLUGIN_ID) { dependencyMessage = "Plugin ${subDescriptor.pluginId} that optionally depends on ${module.pluginId}" + " does not have a separate classloader for the dependency" return@processOptionalDependenciesOnPlugin false } dependencyMessage = checkCanUnloadWithoutRestart(subDescriptor, mainDescriptor, subDescriptor.pluginId, context) if (dependencyMessage == null) { true } else { dependencyMessage = "Plugin ${subDescriptor.pluginId} that optionally depends on ${module.pluginId} requires restart: $dependencyMessage" false } } if (dependencyMessage == null && checkImplementationDetailDependencies) { val contextWithImplementationDetails = context.toMutableList() contextWithImplementationDetails.add(module) processImplementationDetailDependenciesOnPlugin(module, pluginSet, contextWithImplementationDetails::add) processImplementationDetailDependenciesOnPlugin(module, pluginSet) { dependentDescriptor -> // don't check a plugin that is an implementation-detail dependency on the current plugin if it has other disabled dependencies // and won't be loaded anyway if (findMissingRequiredDependency(dependentDescriptor, contextWithImplementationDetails, pluginSet) == null) { dependencyMessage = checkCanUnloadWithoutRestart(module = dependentDescriptor, parentModule = null, context = contextWithImplementationDetails, checkImplementationDetailDependencies = false) if (dependencyMessage != null) { dependencyMessage = "implementation-detail plugin ${dependentDescriptor.pluginId} which depends on ${module.pluginId}" + " requires restart: $dependencyMessage" } } dependencyMessage == null } } return dependencyMessage } private fun findMissingRequiredDependency(descriptor: IdeaPluginDescriptorImpl, context: List<IdeaPluginDescriptorImpl>, pluginSet: PluginSet): PluginId? { for (dependency in descriptor.pluginDependencies) { if (!dependency.isOptional && !PluginManagerCore.isModuleDependency(dependency.pluginId) && !pluginSet.isPluginEnabled(dependency.pluginId) && context.none { it.pluginId == dependency.pluginId }) { return dependency.pluginId } } return null } /** * Checks if the plugin can be loaded/unloaded immediately when the corresponding action is invoked in the * plugins settings, without pressing the Apply button. */ @JvmStatic fun allowLoadUnloadSynchronously(module: IdeaPluginDescriptorImpl): Boolean { val extensions = (module.unsortedEpNameToExtensionElements.takeIf { it.isNotEmpty() } ?: module.appContainerDescriptor.extensions) if (extensions != null && !extensions.all { it.key == UIThemeProvider.EP_NAME.name || it.key == BundledKeymapBean.EP_NAME.name }) { return false } return checkNoComponentsOrServiceOverrides(module) == null && module.actions.isEmpty() } private fun checkNoComponentsOrServiceOverrides(module: IdeaPluginDescriptorImpl): String? { val id = module.pluginId return checkNoComponentsOrServiceOverrides(id, module.appContainerDescriptor) ?: checkNoComponentsOrServiceOverrides(id, module.projectContainerDescriptor) ?: checkNoComponentsOrServiceOverrides(id, module.moduleContainerDescriptor) } private fun checkNoComponentsOrServiceOverrides(pluginId: PluginId?, containerDescriptor: ContainerDescriptor): String? { if (!containerDescriptor.components.isNullOrEmpty()) { return "Plugin $pluginId is not unload-safe because it declares components" } if (containerDescriptor.services.any { it.overrides }) { return "Plugin $pluginId is not unload-safe because it overrides services" } return null } fun unloadPluginWithProgress(project: Project? = null, parentComponent: JComponent?, pluginDescriptor: IdeaPluginDescriptorImpl, options: UnloadPluginOptions): Boolean { var result = false if (!allowLoadUnloadSynchronously(pluginDescriptor)) { runInAutoSaveDisabledMode { val saveAndSyncHandler = SaveAndSyncHandler.getInstance() saveAndSyncHandler.saveSettingsUnderModalProgress(ApplicationManager.getApplication()) for (openProject in ProjectUtil.getOpenProjects()) { saveAndSyncHandler.saveSettingsUnderModalProgress(openProject) } } } val indicator = PotemkinProgress(IdeBundle.message("plugins.progress.unloading.plugin.title", pluginDescriptor.name), project, parentComponent, null) indicator.runInSwingThread { result = unloadPlugin(pluginDescriptor, options.withSave(false)) } return result } data class UnloadPluginOptions( var disable: Boolean = true, var isUpdate: Boolean = false, var save: Boolean = true, var requireMemorySnapshot: Boolean = false, var waitForClassloaderUnload: Boolean = false, var checkImplementationDetailDependencies: Boolean = true, var unloadWaitTimeout: Int? = null, ) { fun withUpdate(isUpdate: Boolean): UnloadPluginOptions = also { this.isUpdate = isUpdate } fun withWaitForClassloaderUnload(waitForClassloaderUnload: Boolean) = also { this.waitForClassloaderUnload = waitForClassloaderUnload } fun withDisable(disable: Boolean) = also { this.disable = disable } fun withRequireMemorySnapshot(requireMemorySnapshot: Boolean) = also { this.requireMemorySnapshot = requireMemorySnapshot } fun withUnloadWaitTimeout(unloadWaitTimeout: Int) = also { this.unloadWaitTimeout = unloadWaitTimeout } fun withSave(save: Boolean) = also { this.save = save } fun withCheckImplementationDetailDependencies(checkImplementationDetailDependencies: Boolean) = also { this.checkImplementationDetailDependencies = checkImplementationDetailDependencies } } @JvmOverloads fun unloadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl, options: UnloadPluginOptions = UnloadPluginOptions(disable = true)): Boolean { val app = ApplicationManager.getApplication() as ApplicationImpl val pluginId = pluginDescriptor.pluginId val pluginSet = PluginManagerCore.getPluginSet() if (options.checkImplementationDetailDependencies) { processImplementationDetailDependenciesOnPlugin(pluginDescriptor, pluginSet) { dependentDescriptor -> dependentDescriptor.isEnabled = false unloadPlugin(dependentDescriptor, UnloadPluginOptions(save = false, waitForClassloaderUnload = false, checkImplementationDetailDependencies = false)) true } } try { if (options.save) { runInAutoSaveDisabledMode { FileDocumentManager.getInstance().saveAllDocuments() runBlockingUnderModalProgress { saveProjectsAndApp(true) } } } TipAndTrickManager.getInstance().closeTipDialog() app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).beforePluginUnload(pluginDescriptor, options.isUpdate) IdeEventQueue.getInstance().flushQueue() } catch (e: Exception) { logger<DynamicPlugins>().error(e) logDescriptorUnload(pluginDescriptor, success = false) return false } var classLoaderUnloaded: Boolean val classLoaders = WeakList<PluginClassLoader>() try { app.runWriteAction { // must be after flushQueue (e.g. https://youtrack.jetbrains.com/issue/IDEA-252010) val forbidGettingServicesToken = app.forbidGettingServices("Plugin $pluginId being unloaded.") try { (pluginDescriptor.pluginClassLoader as? PluginClassLoader)?.let { classLoaders.add(it) } // https://youtrack.jetbrains.com/issue/IDEA-245031 // mark plugin classloaders as being unloaded to ensure that new extension instances will be not created during unload setClassLoaderState(pluginDescriptor, PluginClassLoader.UNLOAD_IN_PROGRESS) unloadLoadedOptionalDependenciesOnPlugin(pluginDescriptor, pluginSet = pluginSet, classLoaders = classLoaders) unloadDependencyDescriptors(pluginDescriptor, pluginSet, classLoaders) unloadModuleDescriptorNotRecursively(pluginDescriptor) clearPluginClassLoaderParentListCache(pluginSet) app.extensionArea.clearUserCache() for (project in ProjectUtil.getOpenProjects()) { (project.extensionArea as ExtensionsAreaImpl).clearUserCache() } clearCachedValues() jdomSerializer.clearSerializationCaches() TypeFactory.defaultInstance().clearCache() app.getServiceIfCreated(TopHitCache::class.java)?.clear() ActionToolbarImpl.resetAllToolbars() PresentationFactory.clearPresentationCaches() TouchbarSupport.reloadAllActions() (serviceIfCreated<NotificationsManager>() as? NotificationsManagerImpl)?.expireAll() MessagePool.getInstance().clearErrors() LaterInvocator.purgeExpiredItems() FileAttribute.resetRegisteredIds() resetFocusCycleRoot() clearNewFocusOwner() hideTooltip() PerformanceWatcher.getInstance().clearFreezeStacktraces() for (classLoader in classLoaders) { IconLoader.detachClassLoader(classLoader) Language.unregisterAllLanguagesIn(classLoader, pluginDescriptor) } serviceIfCreated<IconDeferrer>()?.clearCache() (ApplicationManager.getApplication().messageBus as MessageBusEx).clearPublisherCache() @Suppress("TestOnlyProblems") (ProjectManager.getInstanceIfCreated() as? ProjectManagerImpl)?.disposeDefaultProjectAndCleanupComponentsForDynamicPluginTests() val newPluginSet = pluginSet.withoutModule( module = pluginDescriptor, disable = options.disable, ).createPluginSetWithEnabledModulesMap() PluginManagerCore.setPluginSet(newPluginSet) } finally { try { forbidGettingServicesToken.finish() } finally { app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).pluginUnloaded(pluginDescriptor, options.isUpdate) } } } } catch (e: Exception) { logger<DynamicPlugins>().error(e) } finally { IdeEventQueue.getInstance().flushQueue() // do it after IdeEventQueue.flushQueue() to ensure that Disposer.isDisposed(...) works as expected in flushed tasks. Disposer.clearDisposalTraces() // ensure we don't have references to plugin classes in disposal backtraces ThrowableInterner.clearInternedBacktraces() IdeaLogger.ourErrorsOccurred = null // ensure we don't have references to plugin classes in exception stacktraces clearTemporaryLostComponent() clearCglibStopBacktrace() if (app.isUnitTestMode && pluginDescriptor.pluginClassLoader !is PluginClassLoader) { classLoaderUnloaded = true } else { classloadersFromUnloadedPlugins[pluginId] = classLoaders ClassLoaderTreeChecker(pluginDescriptor, classLoaders).checkThatClassLoaderNotReferencedByPluginClassLoader() val checkClassLoaderUnload = options.waitForClassloaderUnload || options.requireMemorySnapshot || Registry.`is`("ide.plugins.snapshot.on.unload.fail") val timeout = if (checkClassLoaderUnload) { options.unloadWaitTimeout ?: Registry.intValue("ide.plugins.unload.timeout", 5000) } else { 0 } classLoaderUnloaded = unloadClassLoader(pluginDescriptor, timeout) if (classLoaderUnloaded) { LOG.info("Successfully unloaded plugin $pluginId (classloader unload checked=$checkClassLoaderUnload)") classloadersFromUnloadedPlugins.remove(pluginId) } else { if ((options.requireMemorySnapshot || (Registry.`is`("ide.plugins.snapshot.on.unload.fail") && !app.isUnitTestMode)) && MemoryDumpHelper.memoryDumpAvailable()) { classLoaderUnloaded = saveMemorySnapshot(pluginId) } else { LOG.info("Plugin $pluginId is not unload-safe because class loader cannot be unloaded") } } if (!classLoaderUnloaded) { InstalledPluginsState.getInstance().isRestartRequired = true } logDescriptorUnload(pluginDescriptor, success = classLoaderUnloaded) } } if (!classLoaderUnloaded) { setClassLoaderState(pluginDescriptor, PluginAwareClassLoader.ACTIVE) } ActionToolbarImpl.updateAllToolbarsImmediately(true) return classLoaderUnloaded } private fun resetFocusCycleRoot() { val focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager() var focusCycleRoot = focusManager.currentFocusCycleRoot if (focusCycleRoot != null) { while (focusCycleRoot != null && focusCycleRoot !is IdeFrameImpl) { focusCycleRoot = focusCycleRoot.parent } if (focusCycleRoot is IdeFrameImpl) { focusManager.setGlobalCurrentFocusCycleRoot(focusCycleRoot) } else { focusCycleRoot = focusManager.currentFocusCycleRoot val dataContext = DataManager.getInstance().getDataContext(focusCycleRoot) val project = CommonDataKeys.PROJECT.getData(dataContext) if (project != null) { val projectFrame = WindowManager.getInstance().getFrame(project) if (projectFrame != null) { focusManager.setGlobalCurrentFocusCycleRoot(projectFrame) } } } } } private fun unloadLoadedOptionalDependenciesOnPlugin(dependencyPlugin: IdeaPluginDescriptorImpl, pluginSet: PluginSet, classLoaders: WeakList<PluginClassLoader>) { val dependencyClassloader = dependencyPlugin.classLoader processOptionalDependenciesOnPlugin(dependencyPlugin, pluginSet, isLoaded = true) { mainDescriptor, subDescriptor -> val classLoader = subDescriptor.classLoader unloadModuleDescriptorNotRecursively(subDescriptor) // this additional code is required because in unit tests PluginClassLoader is not used if (mainDescriptor !== subDescriptor) { subDescriptor.pluginClassLoader = null } if (dependencyClassloader is PluginClassLoader && classLoader is PluginClassLoader) { LOG.info("Detach classloader $dependencyClassloader from $classLoader") if (mainDescriptor !== subDescriptor && classLoader.pluginDescriptor === subDescriptor) { classLoaders.add(classLoader) classLoader.state = PluginClassLoader.UNLOAD_IN_PROGRESS } } true } } private fun unloadDependencyDescriptors(plugin: IdeaPluginDescriptorImpl, pluginSet: PluginSet, classLoaders: WeakList<PluginClassLoader>) { for (dependency in plugin.pluginDependencies) { val subDescriptor = dependency.subDescriptor ?: continue val classLoader = subDescriptor.pluginClassLoader if (!pluginSet.isPluginEnabled(dependency.pluginId)) { LOG.assertTrue(classLoader == null, "Expected not to have any sub descriptor classloader when dependency ${dependency.pluginId} is not loaded") continue } if (classLoader is PluginClassLoader && classLoader.pluginDescriptor === subDescriptor) { classLoaders.add(classLoader) } unloadDependencyDescriptors(subDescriptor, pluginSet, classLoaders) unloadModuleDescriptorNotRecursively(subDescriptor) subDescriptor.pluginClassLoader = null } for (module in plugin.content.modules) { val subDescriptor = module.requireDescriptor() val classLoader = subDescriptor.pluginClassLoader ?: continue if (classLoader is PluginClassLoader && classLoader.pluginDescriptor === subDescriptor) { classLoaders.add(classLoader) } unloadModuleDescriptorNotRecursively(subDescriptor) subDescriptor.pluginClassLoader = null } } internal fun notify(@NlsContexts.NotificationContent text: String, notificationType: NotificationType, vararg actions: AnAction) { val notification = UpdateChecker.getNotificationGroupForPluginUpdateResults().createNotification(text, notificationType) for (action in actions) { notification.addAction(action) } notification.notify(null) } // PluginId cannot be used to unload related resources because one plugin descriptor may consist of several sub descriptors, // each of them depends on presense of another plugin, here not the whole plugin is unloaded, but only one part. private fun unloadModuleDescriptorNotRecursively(module: IdeaPluginDescriptorImpl) { val app = ApplicationManager.getApplication() as ApplicationImpl (ActionManager.getInstance() as ActionManagerImpl).unloadActions(module) val openedProjects = ProjectUtil.getOpenProjects().asList() val appExtensionArea = app.extensionArea val priorityUnloadListeners = mutableListOf<Runnable>() val unloadListeners = mutableListOf<Runnable>() unregisterUnknownLevelExtensions(module.unsortedEpNameToExtensionElements, module, appExtensionArea, openedProjects, priorityUnloadListeners, unloadListeners) for (epName in (module.appContainerDescriptor.extensions?.keys ?: emptySet())) { appExtensionArea.unregisterExtensions(epName, module, priorityUnloadListeners, unloadListeners) } for (epName in (module.projectContainerDescriptor.extensions?.keys ?: emptySet())) { for (project in openedProjects) { (project.extensionArea as ExtensionsAreaImpl).unregisterExtensions(epName, module, priorityUnloadListeners, unloadListeners) } } // not an error - unsorted goes to module level, see registerExtensions unregisterUnknownLevelExtensions(module.moduleContainerDescriptor.extensions, module, appExtensionArea, openedProjects, priorityUnloadListeners, unloadListeners) for (priorityUnloadListener in priorityUnloadListeners) { priorityUnloadListener.run() } for (unloadListener in unloadListeners) { unloadListener.run() } // first, reset all plugin extension points before unregistering, so that listeners don't see plugin in semi-torn-down state processExtensionPoints(module, openedProjects) { points, area -> area.resetExtensionPoints(points, module) } // unregister plugin extension points processExtensionPoints(module, openedProjects) { points, area -> area.unregisterExtensionPoints(points, module) } val pluginId = module.pluginId app.unloadServices(module.appContainerDescriptor.services, pluginId) val appMessageBus = app.messageBus as MessageBusEx module.appContainerDescriptor.listeners?.let { appMessageBus.unsubscribeLazyListeners(module, it) } for (project in openedProjects) { (project as ComponentManagerImpl).unloadServices(module.projectContainerDescriptor.services, pluginId) module.projectContainerDescriptor.listeners?.let { ((project as ComponentManagerImpl).messageBus as MessageBusEx).unsubscribeLazyListeners(module, it) } val moduleServices = module.moduleContainerDescriptor.services for (ideaModule in ModuleManager.getInstance(project).modules) { (ideaModule as ComponentManagerImpl).unloadServices(moduleServices, pluginId) createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(ideaModule, it) } } createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(project, it) } } appMessageBus.disconnectPluginConnections(Predicate { aClass -> (aClass.classLoader as? PluginClassLoader)?.pluginDescriptor === module }) createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(ApplicationManager.getApplication(), it) } } private fun unregisterUnknownLevelExtensions(extensionMap: Map<String, List<ExtensionDescriptor>>?, pluginDescriptor: IdeaPluginDescriptorImpl, appExtensionArea: ExtensionsAreaImpl, openedProjects: List<Project>, priorityUnloadListeners: MutableList<Runnable>, unloadListeners: MutableList<Runnable>) { for (epName in (extensionMap?.keys ?: return)) { val isAppLevelEp = appExtensionArea.unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners, unloadListeners) if (isAppLevelEp) { continue } for (project in openedProjects) { val isProjectLevelEp = (project.extensionArea as ExtensionsAreaImpl) .unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners, unloadListeners) if (!isProjectLevelEp) { for (module in ModuleManager.getInstance(project).modules) { (module.extensionArea as ExtensionsAreaImpl) .unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners, unloadListeners) } } } } } private inline fun processExtensionPoints(pluginDescriptor: IdeaPluginDescriptorImpl, projects: List<Project>, processor: (points: List<ExtensionPointDescriptor>, area: ExtensionsAreaImpl) -> Unit) { pluginDescriptor.appContainerDescriptor.extensionPoints?.let { processor(it, ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl) } pluginDescriptor.projectContainerDescriptor.extensionPoints?.let { extensionPoints -> for (project in projects) { processor(extensionPoints, project.extensionArea as ExtensionsAreaImpl) } } pluginDescriptor.moduleContainerDescriptor.extensionPoints?.let { extensionPoints -> for (project in projects) { for (module in ModuleManager.getInstance(project).modules) { processor(extensionPoints, module.extensionArea as ExtensionsAreaImpl) } } } } fun loadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl): Boolean { return loadPlugin(pluginDescriptor, checkImplementationDetailDependencies = true) } private fun loadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl, checkImplementationDetailDependencies: Boolean = true): Boolean { if (classloadersFromUnloadedPlugins[pluginDescriptor.pluginId]?.isEmpty() == false) { LOG.info("Requiring restart for loading plugin ${pluginDescriptor.pluginId}" + " because previous version of the plugin wasn't fully unloaded") return false } val loadStartTime = System.currentTimeMillis() val pluginSet = PluginManagerCore.getPluginSet() .withModule(pluginDescriptor) .createPluginSetWithEnabledModulesMap() val classLoaderConfigurator = ClassLoaderConfigurator(pluginSet) // todo loadPlugin should be called per each module, temporary solution val pluginWithContentModules = pluginSet.getEnabledModules() .filter { it.pluginId == pluginDescriptor.pluginId } .filter(classLoaderConfigurator::configureModule) .toList() val app = ApplicationManager.getApplication() as ApplicationImpl app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).beforePluginLoaded(pluginDescriptor) app.runWriteAction { try { PluginManagerCore.setPluginSet(pluginSet) val listenerCallbacks = mutableListOf<Runnable>() // 4. load into service container loadModules(pluginWithContentModules, app, listenerCallbacks) loadModules( optionalDependenciesOnPlugin(pluginDescriptor, classLoaderConfigurator, pluginSet), app, listenerCallbacks, ) clearPluginClassLoaderParentListCache(pluginSet) clearCachedValues() listenerCallbacks.forEach(Runnable::run) logDescriptorLoad(pluginDescriptor) LOG.info("Plugin ${pluginDescriptor.pluginId} loaded without restart in ${System.currentTimeMillis() - loadStartTime} ms") } finally { app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).pluginLoaded(pluginDescriptor) } } if (checkImplementationDetailDependencies) { var implementationDetailsLoadedWithoutRestart = true processImplementationDetailDependenciesOnPlugin(pluginDescriptor, pluginSet) { dependentDescriptor -> val dependencies = dependentDescriptor.pluginDependencies if (dependencies.all { it.isOptional || PluginManagerCore.getPlugin(it.pluginId) != null }) { if (!loadPlugin(dependentDescriptor, checkImplementationDetailDependencies = false)) { implementationDetailsLoadedWithoutRestart = false } } implementationDetailsLoadedWithoutRestart } return implementationDetailsLoadedWithoutRestart } return true } fun onPluginUnload(parentDisposable: Disposable, callback: Runnable) { ApplicationManager.getApplication().messageBus.connect(parentDisposable) .subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener { override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) { callback.run() } }) } } private fun clearTemporaryLostComponent() { try { val clearMethod = Window::class.java.declaredMethods.find { it.name == "setTemporaryLostComponent" } if (clearMethod == null) { LOG.info("setTemporaryLostComponent method not found") return } clearMethod.isAccessible = true loop@ for (frame in WindowManager.getInstance().allProjectFrames) { val window = when (frame) { is ProjectFrameHelper -> frame.frameOrNull is Window -> frame else -> continue@loop } clearMethod.invoke(window, null) } } catch (e: Throwable) { LOG.info("Failed to clear Window.temporaryLostComponent", e) } } private fun hideTooltip() { try { val showMethod = ToolTipManager::class.java.declaredMethods.find { it.name == "show" } if (showMethod == null) { LOG.info("ToolTipManager.show method not found") return } showMethod.isAccessible = true showMethod.invoke(ToolTipManager.sharedInstance(), null) } catch (e: Throwable) { LOG.info("Failed to hide tooltip", e) } } private fun clearCglibStopBacktrace() { val field = ReflectionUtil.getDeclaredField(ClassNameReader::class.java, "EARLY_EXIT") if (field != null) { try { ThrowableInterner.clearBacktrace((field[null] as Throwable)) } catch (e: Throwable) { LOG.info(e) } } } private fun clearNewFocusOwner() { val field = ReflectionUtil.getDeclaredField(KeyboardFocusManager::class.java, "newFocusOwner") if (field != null) { try { field.set(null, null) } catch (e: Throwable) { LOG.info(e) } } } private fun saveMemorySnapshot(pluginId: PluginId): Boolean { val snapshotDate = SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(Date()) val snapshotFileName = "unload-$pluginId-$snapshotDate.hprof" val snapshotPath = System.getProperty("memory.snapshots.path", SystemProperties.getUserHome()) + "/" + snapshotFileName MemoryDumpHelper.captureMemoryDump(snapshotPath) if (classloadersFromUnloadedPlugins[pluginId]?.isEmpty() != false) { LOG.info("Successfully unloaded plugin $pluginId (classloader collected during memory snapshot generation)") return true } if (Registry.`is`("ide.plugins.analyze.snapshot")) { val analysisResult = analyzeSnapshot(snapshotPath, pluginId) @Suppress("ReplaceSizeZeroCheckWithIsEmpty") if (analysisResult.length == 0) { LOG.info("Successfully unloaded plugin $pluginId (no strong references to classloader in .hprof file)") classloadersFromUnloadedPlugins.remove(pluginId) return true } else { LOG.info("Snapshot analysis result: $analysisResult") } } DynamicPlugins.notify( IdeBundle.message("memory.snapshot.captured.text", snapshotPath, snapshotFileName), NotificationType.WARNING, object : AnAction(IdeBundle.message("ide.restart.action")), DumbAware { override fun actionPerformed(e: AnActionEvent) = ApplicationManager.getApplication().restart() }, object : AnAction( IdeBundle.message("memory.snapshot.captured.action.text", snapshotFileName, RevealFileAction.getFileManagerName())), DumbAware { override fun actionPerformed(e: AnActionEvent) = RevealFileAction.openFile(Paths.get(snapshotPath)) } ) LOG.info("Plugin $pluginId is not unload-safe because class loader cannot be unloaded. Memory snapshot created at $snapshotPath") return false } private fun processImplementationDetailDependenciesOnPlugin(pluginDescriptor: IdeaPluginDescriptorImpl, pluginSet: PluginSet, processor: (descriptor: IdeaPluginDescriptorImpl) -> Boolean) { processDependenciesOnPlugin(dependencyPlugin = pluginDescriptor, pluginSet = pluginSet, loadStateFilter = LoadStateFilter.ANY, onlyOptional = false) { _, module -> if (module.isImplementationDetail) { processor(module) } else { true } } } /** * Load all sub plugins that depend on specified [dependencyPlugin]. */ private fun optionalDependenciesOnPlugin( dependencyPlugin: IdeaPluginDescriptorImpl, classLoaderConfigurator: ClassLoaderConfigurator, pluginSet: PluginSet, ): Set<IdeaPluginDescriptorImpl> { // 1. collect optional descriptors val modulesToMain = LinkedHashMap<IdeaPluginDescriptorImpl, IdeaPluginDescriptorImpl>() processOptionalDependenciesOnPlugin(dependencyPlugin, pluginSet, isLoaded = false) { main, module -> modulesToMain[module] = main true } if (modulesToMain.isEmpty()) { return emptySet() } // 2. sort topologically val topologicalComparator = PluginSetBuilder(modulesToMain.values) .moduleGraph .topologicalComparator return modulesToMain.toSortedMap(topologicalComparator) .filter { (moduleDescriptor, mainDescriptor) -> // 3. setup classloaders classLoaderConfigurator.configureDependency(mainDescriptor, moduleDescriptor) }.keys } private fun loadModules( modules: Collection<IdeaPluginDescriptorImpl>, app: ApplicationImpl, listenerCallbacks: MutableList<in Runnable>, ) { fun registerComponents(componentManager: ComponentManager) { (componentManager as ComponentManagerImpl).registerComponents(modules.toList(), app, null, listenerCallbacks) } registerComponents(app) for (openProject in ProjectUtil.getOpenProjects()) { registerComponents(openProject) for (module in ModuleManager.getInstance(openProject).modules) { registerComponents(module) } } (ActionManager.getInstance() as ActionManagerImpl).registerActions(modules) } private fun analyzeSnapshot(hprofPath: String, pluginId: PluginId): String { FileChannel.open(Paths.get(hprofPath), StandardOpenOption.READ).use { channel -> val analysis = HProfAnalysis(channel, SystemTempFilenameSupplier()) { analysisContext, progressIndicator -> AnalyzeClassloaderReferencesGraph(analysisContext, pluginId.idString).analyze(progressIndicator) } analysis.onlyStrongReferences = true analysis.includeClassesAsRoots = false analysis.setIncludeMetaInfo(false) return analysis.analyze(ProgressManager.getGlobalProgressIndicator() ?: EmptyProgressIndicator()) } } private fun createDisposeTreePredicate(pluginDescriptor: IdeaPluginDescriptorImpl): Predicate<Disposable>? { val classLoader = pluginDescriptor.pluginClassLoader as? PluginClassLoader ?: return null return Predicate { if (it is PluginManager.PluginAwareDisposable) { it.classLoaderId == classLoader.instanceId } else { it::class.java.classLoader === classLoader } } } private fun processOptionalDependenciesOnPlugin( dependencyPlugin: IdeaPluginDescriptorImpl, pluginSet: PluginSet, isLoaded: Boolean, processor: (pluginDescriptor: IdeaPluginDescriptorImpl, moduleDescriptor: IdeaPluginDescriptorImpl) -> Boolean, ) { processDependenciesOnPlugin( dependencyPlugin = dependencyPlugin, pluginSet = pluginSet, onlyOptional = true, loadStateFilter = if (isLoaded) LoadStateFilter.LOADED else LoadStateFilter.NOT_LOADED, processor = processor, ) } private fun processDependenciesOnPlugin( dependencyPlugin: IdeaPluginDescriptorImpl, pluginSet: PluginSet, loadStateFilter: LoadStateFilter, onlyOptional: Boolean, processor: (pluginDescriptor: IdeaPluginDescriptorImpl, moduleDescriptor: IdeaPluginDescriptorImpl) -> Boolean, ) { val wantedIds = HashSet<String>(1 + dependencyPlugin.content.modules.size) wantedIds.add(dependencyPlugin.pluginId.idString) for (module in dependencyPlugin.content.modules) { wantedIds.add(module.name) } for (plugin in pluginSet.enabledPlugins) { if (plugin === dependencyPlugin) { continue } if (!processOptionalDependenciesInOldFormatOnPlugin(dependencyPluginId = dependencyPlugin.pluginId, mainDescriptor = plugin, loadStateFilter = loadStateFilter, onlyOptional = onlyOptional, processor = processor)) { return } for (moduleItem in plugin.content.modules) { val module = moduleItem.requireDescriptor() if (loadStateFilter != LoadStateFilter.ANY) { val isModuleLoaded = module.pluginClassLoader != null if (isModuleLoaded != (loadStateFilter == LoadStateFilter.LOADED)) { continue } } for (item in module.dependencies.modules) { if (wantedIds.contains(item.name) && !processor(plugin, module)) { return } } for (item in module.dependencies.plugins) { if (dependencyPlugin.pluginId == item.id && !processor(plugin, module)) { return } } } } } private enum class LoadStateFilter { LOADED, NOT_LOADED, ANY } private fun processOptionalDependenciesInOldFormatOnPlugin( dependencyPluginId: PluginId, mainDescriptor: IdeaPluginDescriptorImpl, loadStateFilter: LoadStateFilter, onlyOptional: Boolean, processor: (main: IdeaPluginDescriptorImpl, sub: IdeaPluginDescriptorImpl) -> Boolean ): Boolean { for (dependency in mainDescriptor.pluginDependencies) { if (!dependency.isOptional) { if (!onlyOptional && dependency.pluginId == dependencyPluginId && !processor(mainDescriptor, mainDescriptor)) { return false } continue } val subDescriptor = dependency.subDescriptor ?: continue if (loadStateFilter != LoadStateFilter.ANY) { val isModuleLoaded = subDescriptor.pluginClassLoader != null if (isModuleLoaded != (loadStateFilter == LoadStateFilter.LOADED)) { continue } } if (dependency.pluginId == dependencyPluginId && !processor(mainDescriptor, subDescriptor)) { return false } if (!processOptionalDependenciesInOldFormatOnPlugin( dependencyPluginId = dependencyPluginId, mainDescriptor = subDescriptor, loadStateFilter = loadStateFilter, onlyOptional = onlyOptional, processor = processor)) { return false } } return true } private fun doCheckExtensionsCanUnloadWithoutRestart( extensions: Map<String, List<ExtensionDescriptor>>, descriptor: IdeaPluginDescriptorImpl, baseDescriptor: IdeaPluginDescriptorImpl?, app: Application, optionalDependencyPluginId: PluginId?, context: List<IdeaPluginDescriptorImpl>, pluginSet: PluginSet, ): String? { val firstProject = ProjectUtil.getOpenProjects().firstOrNull() val anyProject = firstProject ?: ProjectManager.getInstance().defaultProject val anyModule = firstProject?.let { ModuleManager.getInstance(it).modules.firstOrNull() } val seenPlugins: MutableSet<IdeaPluginDescriptorImpl> = Collections.newSetFromMap(IdentityHashMap()) epLoop@ for (epName in extensions.keys) { seenPlugins.clear() fun getNonDynamicUnloadError(optionalDependencyPluginId: PluginId?): String = optionalDependencyPluginId?.let { "Plugin ${baseDescriptor?.pluginId} is not unload-safe because of use of non-dynamic EP $epName in plugin $it that optionally depends on it" } ?: "Plugin ${descriptor.pluginId} is not unload-safe because of extension to non-dynamic EP $epName" val result = findLoadedPluginExtensionPointRecursive( pluginDescriptor = baseDescriptor ?: descriptor, epName = epName, pluginSet = pluginSet, context = context, seenPlugins = seenPlugins, ) if (result != null) { val (pluginExtensionPoint, foundInDependencies) = result // descriptor.pluginId is null when we check the optional dependencies of the plugin which is being loaded // if an optional dependency of a plugin extends a non-dynamic EP of that plugin, it shouldn't prevent plugin loading if (!pluginExtensionPoint.isDynamic) { if (baseDescriptor == null || foundInDependencies) { return getNonDynamicUnloadError(null) } else if (descriptor === baseDescriptor) { return getNonDynamicUnloadError(descriptor.pluginId) } } continue } @Suppress("RemoveExplicitTypeArguments") val ep = app.extensionArea.getExtensionPointIfRegistered<Any>(epName) ?: anyProject.extensionArea.getExtensionPointIfRegistered<Any>(epName) ?: anyModule?.extensionArea?.getExtensionPointIfRegistered<Any>(epName) if (ep != null) { if (!ep.isDynamic) { return getNonDynamicUnloadError(optionalDependencyPluginId) } continue } if (anyModule == null) { val corePlugin = pluginSet.findEnabledPlugin(PluginManagerCore.CORE_ID) if (corePlugin != null) { val coreEP = findPluginExtensionPoint(corePlugin, epName) if (coreEP != null) { if (!coreEP.isDynamic) { return getNonDynamicUnloadError(optionalDependencyPluginId) } continue } } } for (contextPlugin in context) { val contextEp = findPluginExtensionPoint(contextPlugin, epName) ?: continue if (!contextEp.isDynamic) { return getNonDynamicUnloadError(null) } continue@epLoop } // special case Kotlin EPs registered via code in Kotlin compiler if (epName.startsWith("org.jetbrains.kotlin") && descriptor.pluginId.idString == "org.jetbrains.kotlin") { continue } return "Plugin ${descriptor.pluginId} is not unload-safe because of unresolved extension $epName" } return null } private fun findPluginExtensionPoint(pluginDescriptor: IdeaPluginDescriptorImpl, epName: String): ExtensionPointDescriptor? { fun findContainerExtensionPoint(containerDescriptor: ContainerDescriptor): ExtensionPointDescriptor? { return containerDescriptor.extensionPoints?.find { it.nameEquals(epName, pluginDescriptor) } } return findContainerExtensionPoint(pluginDescriptor.appContainerDescriptor) ?: findContainerExtensionPoint(pluginDescriptor.projectContainerDescriptor) ?: findContainerExtensionPoint(pluginDescriptor.moduleContainerDescriptor) } private fun findLoadedPluginExtensionPointRecursive(pluginDescriptor: IdeaPluginDescriptorImpl, epName: String, pluginSet: PluginSet, context: List<IdeaPluginDescriptorImpl>, seenPlugins: MutableSet<IdeaPluginDescriptorImpl>): Pair<ExtensionPointDescriptor, Boolean>? { if (!seenPlugins.add(pluginDescriptor)) { return null } findPluginExtensionPoint(pluginDescriptor, epName)?.let { return it to false } for (dependency in pluginDescriptor.pluginDependencies) { if (pluginSet.isPluginEnabled(dependency.pluginId) || context.any { it.pluginId == dependency.pluginId }) { dependency.subDescriptor?.let { subDescriptor -> findLoadedPluginExtensionPointRecursive(subDescriptor, epName, pluginSet, context, seenPlugins)?.let { return it } } pluginSet.findEnabledPlugin(dependency.pluginId)?.let { dependencyDescriptor -> findLoadedPluginExtensionPointRecursive(dependencyDescriptor, epName, pluginSet, context, seenPlugins)?.let { return it.first to true } } } } processDirectDependencies(pluginDescriptor, pluginSet) { dependency -> findLoadedPluginExtensionPointRecursive(dependency, epName, pluginSet, context, seenPlugins)?.let { return it.first to true } } return null } private inline fun processDirectDependencies(module: IdeaPluginDescriptorImpl, pluginSet: PluginSet, processor: (IdeaPluginDescriptorImpl) -> Unit) { for (item in module.dependencies.modules) { val descriptor = pluginSet.findEnabledModule(item.name) if (descriptor != null) { processor(descriptor) } } for (item in module.dependencies.plugins) { val descriptor = pluginSet.findEnabledPlugin(item.id) if (descriptor != null) { processor(descriptor) } } } private fun unloadClassLoader(pluginDescriptor: IdeaPluginDescriptorImpl, timeoutMs: Int): Boolean { if (timeoutMs == 0) { pluginDescriptor.pluginClassLoader = null return true } val watcher = GCWatcher.tracking(pluginDescriptor.pluginClassLoader) pluginDescriptor.pluginClassLoader = null return watcher.tryCollect(timeoutMs) } private fun setClassLoaderState(pluginDescriptor: IdeaPluginDescriptorImpl, state: Int) { (pluginDescriptor.pluginClassLoader as? PluginClassLoader)?.state = state for (dependency in pluginDescriptor.pluginDependencies) { dependency.subDescriptor?.let { setClassLoaderState(it, state) } } } private fun clearPluginClassLoaderParentListCache(pluginSet: PluginSet) { // yes, clear not only enabled plugins, but all, just to be sure; it's a cheap operation for (descriptor in pluginSet.allPlugins) { (descriptor.pluginClassLoader as? PluginClassLoader)?.clearParentListCache() } } private fun clearCachedValues() { for (project in ProjectUtil.getOpenProjects()) { (CachedValuesManager.getManager(project) as? CachedValuesManagerImpl)?.clearCachedValues() } }
apache-2.0
1e6d9864d37e40e4d7177c331a44a71d
40.683786
169
0.703846
5.838557
false
false
false
false
apollographql/apollo-android
tests/integration-tests/src/commonTest/kotlin/test/CacheFlagsTest.kt
1
4329
package test import com.apollographql.apollo3.ApolloClient import com.apollographql.apollo3.annotations.ApolloExperimental import com.apollographql.apollo3.api.AnyAdapter import com.apollographql.apollo3.api.toJsonString import com.apollographql.apollo3.cache.normalized.ApolloStore import com.apollographql.apollo3.cache.normalized.FetchPolicy import com.apollographql.apollo3.cache.normalized.api.ApolloCacheHeaders import com.apollographql.apollo3.cache.normalized.api.CacheHeaders import com.apollographql.apollo3.cache.normalized.api.MemoryCacheFactory import com.apollographql.apollo3.cache.normalized.cacheHeaders import com.apollographql.apollo3.cache.normalized.doNotStore import com.apollographql.apollo3.cache.normalized.fetchPolicy import com.apollographql.apollo3.cache.normalized.store import com.apollographql.apollo3.cache.normalized.storePartialResponses import com.apollographql.apollo3.exception.CacheMissException import com.apollographql.apollo3.integration.normalizer.HeroNameQuery import com.apollographql.apollo3.mockserver.MockServer import com.apollographql.apollo3.mockserver.enqueue import com.apollographql.apollo3.testing.enqueue import com.apollographql.apollo3.testing.runTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertNotNull @OptIn(ApolloExperimental::class) class CacheFlagsTest { private lateinit var mockServer: MockServer private lateinit var apolloClient: ApolloClient private lateinit var store: ApolloStore private suspend fun setUp() { store = ApolloStore(MemoryCacheFactory()) mockServer = MockServer() apolloClient = ApolloClient.Builder().serverUrl(mockServer.url()).store(store).build() } private suspend fun tearDown() { mockServer.stop() } @Test fun doNotStore() = runTest(before = { setUp() }, after = { tearDown() }) { val query = HeroNameQuery() val data = HeroNameQuery.Data(HeroNameQuery.Hero("R2-D2")) mockServer.enqueue(query, data) apolloClient.query(query).doNotStore(true).execute() // Since the previous request was not stored, this should fail assertFailsWith(CacheMissException::class) { apolloClient.query(query).fetchPolicy(FetchPolicy.CacheOnly).execute() } } @Test fun testEvictAfterRead() = runTest(before = { setUp() }, after = { tearDown() }) { val query = HeroNameQuery() val data = HeroNameQuery.Data(HeroNameQuery.Hero("R2-D2")) mockServer.enqueue(query, data) // Store the data apolloClient.query(query).fetchPolicy(FetchPolicy.NetworkOnly).execute() // This should work and evict the entries val response = apolloClient.query(query) .fetchPolicy(FetchPolicy.CacheOnly) .cacheHeaders(CacheHeaders.builder().addHeader(ApolloCacheHeaders.EVICT_AFTER_READ, "true").build()) .execute() assertEquals("R2-D2", response.data?.hero?.name) // Second time should fail assertFailsWith(CacheMissException::class) { apolloClient.query(query).fetchPolicy(FetchPolicy.CacheOnly).execute() } } private val partialResponse = mapOf( "data" to mapOf( "hero" to null ), "errors" to listOf( mapOf( "message" to "An error Happened", "locations" to listOf( mapOf( "line" to 0, "column" to 0 ) ) ) ) ) @Test fun partialResponsesAreNotStored() = runTest(before = { setUp() }, after = { tearDown() }) { val query = HeroNameQuery() mockServer.enqueue(AnyAdapter.toJsonString(partialResponse)) // this should not store the response apolloClient.query(query).execute() assertFailsWith(CacheMissException::class) { apolloClient.query(query).fetchPolicy(FetchPolicy.CacheOnly).execute() } } @Test fun storePartialResponse() = runTest(before = { setUp() }, after = { tearDown() }) { val query = HeroNameQuery() mockServer.enqueue(AnyAdapter.toJsonString(partialResponse)) // this should not store the response apolloClient.query(query).storePartialResponses(true).execute() val response = apolloClient.query(query).fetchPolicy(FetchPolicy.CacheOnly).execute() assertNotNull(response.data) } }
mit
ca5c79e26b472406305f2964fa60eebe
34.491803
112
0.729268
4.561644
false
true
false
false
JetBrains/intellij-community
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/KotlinDescriptorTestCaseWithStepping.kt
1
16482
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.test import com.intellij.debugger.actions.MethodSmartStepTarget import com.intellij.debugger.actions.SmartStepTarget import com.intellij.debugger.engine.BasicStepMethodFilter import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.MethodFilter import com.intellij.debugger.engine.SuspendContextImpl import com.intellij.debugger.engine.evaluation.EvaluateException import com.intellij.debugger.engine.evaluation.EvaluationContextImpl import com.intellij.debugger.engine.events.SuspendContextCommandImpl import com.intellij.debugger.engine.managerThread.DebuggerCommand import com.intellij.debugger.impl.DebuggerContextImpl import com.intellij.debugger.impl.JvmSteppingCommandProvider import com.intellij.debugger.impl.PositionUtil import com.intellij.execution.configurations.JavaParameters import com.intellij.execution.process.ProcessOutputTypes import com.intellij.jarRepository.JarRepositoryManager import com.intellij.jarRepository.RemoteRepositoryDescription import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runReadAction import com.intellij.openapi.roots.libraries.ui.OrderRoot import com.intellij.psi.PsiElement import com.intellij.testFramework.runInEdtAndWait import com.intellij.xdebugger.XDebuggerTestUtil import com.intellij.xdebugger.frame.XStackFrame import junit.framework.AssertionFailedError import org.jetbrains.idea.maven.aether.ArtifactKind import org.jetbrains.jps.model.library.JpsMavenRepositoryLibraryDescriptor import org.jetbrains.kotlin.idea.base.psi.getTopmostElementAtOffset import org.jetbrains.kotlin.idea.debugger.KotlinPositionManager import org.jetbrains.kotlin.idea.debugger.core.stackFrame.KotlinStackFrame import org.jetbrains.kotlin.idea.debugger.core.stepping.KotlinSteppingCommandProvider import org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto.KotlinSmartStepIntoHandler import org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto.KotlinSmartStepTarget import org.jetbrains.kotlin.idea.debugger.test.util.KotlinOutputChecker import org.jetbrains.kotlin.idea.debugger.test.util.SteppingInstruction import org.jetbrains.kotlin.idea.debugger.test.util.SteppingInstructionKind import org.jetbrains.kotlin.idea.debugger.test.util.render import org.jetbrains.kotlin.idea.test.ConfigLibraryUtil import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils.isIgnoredTarget import org.jetbrains.kotlin.idea.test.KotlinBaseTest import org.jetbrains.kotlin.psi.KtTreeVisitorVoid import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.test.InTextDirectivesUtils import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance import java.io.ByteArrayOutputStream import java.io.PrintStream import java.nio.charset.StandardCharsets abstract class KotlinDescriptorTestCaseWithStepping : KotlinDescriptorTestCase() { companion object { //language=RegExp const val MAVEN_DEPENDENCY_REGEX = """maven\(([a-zA-Z0-9_\-.]+):([a-zA-Z0-9_\-.]+):([a-zA-Z0-9_\-.]+)\)""" } private val dp: DebugProcessImpl get() = debugProcess ?: throw AssertionError("createLocalProcess() should be called before getDebugProcess()") @Volatile private var myEvaluationContext: EvaluationContextImpl? = null val evaluationContext get() = myEvaluationContext!! @Volatile private var myDebuggerContext: DebuggerContextImpl? = null protected open val debuggerContext get() = myDebuggerContext!! @Volatile private var myCommandProvider: KotlinSteppingCommandProvider? = null private val commandProvider get() = myCommandProvider!! private val classPath = mutableListOf<String>() private val thrownExceptions = mutableListOf<Throwable>() private fun initContexts(suspendContext: SuspendContextImpl) { myEvaluationContext = createEvaluationContext(suspendContext) myDebuggerContext = createDebuggerContext(suspendContext) myCommandProvider = JvmSteppingCommandProvider.EP_NAME.extensions.firstIsInstance<KotlinSteppingCommandProvider>() } private fun SuspendContextImpl.getKotlinStackFrames(): List<KotlinStackFrame> { val proxy = frameProxy ?: return emptyList() if (myInProgress) { val positionManager = KotlinPositionManager(debugProcess) return positionManager.createStackFrames( proxy, debugProcess, proxy.location() ).filterIsInstance<KotlinStackFrame>() } return emptyList() } override fun createEvaluationContext(suspendContext: SuspendContextImpl): EvaluationContextImpl? { return try { val proxy = suspendContext.getKotlinStackFrames().firstOrNull()?.stackFrameProxy ?: suspendContext.frameProxy assertNotNull(proxy) EvaluationContextImpl(suspendContext, proxy, proxy?.thisObject()) } catch (e: EvaluateException) { error(e) null } } internal fun process(instructions: List<SteppingInstruction>) { instructions.forEach(this::process) } internal fun doOnBreakpoint(action: SuspendContextImpl.() -> Unit) { super.onBreakpoint { try { initContexts(it) it.printContext() it.action() } catch (e: AssertionError) { throw e } catch (e: Throwable) { e.printStackTrace() resume(it) } } } internal fun finish() { doOnBreakpoint { resume(this) } } private fun SuspendContextImpl.doStepInto(ignoreFilters: Boolean, smartStepFilter: MethodFilter?) { val stepIntoCommand = runReadAction { commandProvider.getStepIntoCommand(this, ignoreFilters, smartStepFilter) } ?: dp.createStepIntoCommand(this, ignoreFilters, smartStepFilter) dp.managerThread.schedule(stepIntoCommand) } private fun SuspendContextImpl.doStepOut() { val stepOutCommand = runReadAction { commandProvider.getStepOutCommand(this, debuggerContext) } ?: dp.createStepOutCommand(this) dp.managerThread.schedule(stepOutCommand) } override fun tearDown() { try { classPath.clear() } catch (e: Throwable) { addSuppressedException(e) } finally { super.tearDown() } } private fun SuspendContextImpl.doStepOver(ignoreBreakpoints: Boolean = false) { val stepOverCommand = runReadAction { val sourcePosition = debuggerContext.sourcePosition commandProvider.getStepOverCommand(this, ignoreBreakpoints, sourcePosition) } ?: dp.createStepOverCommand(this, ignoreBreakpoints) dp.managerThread.schedule(stepOverCommand) } private fun process(instruction: SteppingInstruction) { fun loop(count: Int, block: SuspendContextImpl.() -> Unit) { repeat(count) { doOnBreakpoint(block) } } when (instruction.kind) { SteppingInstructionKind.StepInto -> loop(instruction.arg) { doStepInto(false, null) } SteppingInstructionKind.StepOut -> loop(instruction.arg) { doStepOut() } SteppingInstructionKind.StepOver -> loop(instruction.arg) { doStepOver() } SteppingInstructionKind.ForceStepOver -> loop(instruction.arg) { doStepOver(ignoreBreakpoints = true) } SteppingInstructionKind.SmartStepInto -> loop(instruction.arg) { doSmartStepInto() } SteppingInstructionKind.SmartStepIntoByIndex -> doOnBreakpoint { doSmartStepInto(instruction.arg) } SteppingInstructionKind.Resume -> loop(instruction.arg) { resume(this) } SteppingInstructionKind.SmartStepTargetsExpectedNumber -> doOnBreakpoint { checkNumberOfSmartStepTargets(instruction.arg) resume(this) } } } private fun checkNumberOfSmartStepTargets(expectedNumber: Int) { val smartStepFilters = createSmartStepIntoFilters() try { assertEquals( "Actual and expected numbers of smart step targets do not match", expectedNumber, smartStepFilters.size ) } catch (ex: AssertionFailedError) { thrownExceptions.add(ex) } } private fun SuspendContextImpl.doSmartStepInto(chooseFromList: Int = 0) { this.doSmartStepInto(chooseFromList, false) } override fun throwExceptionsIfAny() { if (thrownExceptions.isNotEmpty()) { if (!isTestIgnored()) { throw AssertionError( "Test failed with exceptions:\n${thrownExceptions.renderStackTraces()}" ) } else { (checker as? KotlinOutputChecker)?.threwException = true } } } private fun List<Throwable>.renderStackTraces(): String { val outputStream = ByteArrayOutputStream() PrintStream(outputStream, true, StandardCharsets.UTF_8).use { for (throwable in this) { throwable.printStackTrace(it) } } return outputStream.toString(StandardCharsets.UTF_8) } protected fun isTestIgnored(): Boolean { val outputFile = getExpectedOutputFile() return outputFile.exists() && isIgnoredTarget(targetBackend(), outputFile) } private fun SuspendContextImpl.printContext() { runReadAction { if (this.frameProxy == null) { return@runReadAction println("Context thread is null", ProcessOutputTypes.SYSTEM) } val sourcePosition = PositionUtil.getSourcePosition(this) println(sourcePosition?.render() ?: "null", ProcessOutputTypes.SYSTEM) } } private fun SuspendContextImpl.doSmartStepInto(chooseFromList: Int, ignoreFilters: Boolean) { val filters = createSmartStepIntoFilters() if (chooseFromList == 0) { filters.forEach { doStepInto(ignoreFilters, it) } } else { try { doStepInto(ignoreFilters, filters[chooseFromList - 1]) } catch (e: IndexOutOfBoundsException) { val elementText = runReadAction { debuggerContext.sourcePosition.elementAt.getElementTextWithContext() } throw AssertionError("Couldn't find smart step into command at: \n$elementText", e) } } } private fun createSmartStepIntoFilters(): List<MethodFilter> { val position = debuggerContext.sourcePosition val stepTargets = KotlinSmartStepIntoHandler() .findStepIntoTargets(position, debuggerSession) .blockingGet(XDebuggerTestUtil.TIMEOUT_MS) ?: error("Couldn't calculate smart step targets") return runReadAction { stepTargets.sortedByPositionInTree().mapNotNull { stepTarget -> when (stepTarget) { is KotlinSmartStepTarget -> stepTarget.createMethodFilter() is MethodSmartStepTarget -> BasicStepMethodFilter(stepTarget.method, stepTarget.getCallingExpressionLines()) else -> null } } } } private fun List<SmartStepTarget>.sortedByPositionInTree(): List<SmartStepTarget> { if (isEmpty()) return emptyList() val sortedTargets = MutableList(size) { first() } for ((i, indexInTree) in getIndicesInTree().withIndex()) { sortedTargets[indexInTree] = get(i) } return sortedTargets } private fun List<SmartStepTarget>.getIndicesInTree(): List<Int> { val targetsIndicesInTree = MutableList(size) { 0 } runReadAction { val elementAt = debuggerContext.sourcePosition.elementAt val topmostElement = getTopmostElementAtOffset(elementAt, elementAt.textRange.startOffset) topmostElement.accept(object : KtTreeVisitorVoid() { private var elementIndex = 0 override fun visitElement(element: PsiElement) { for ((i, target) in withIndex()) { if (element === target.highlightElement) { targetsIndicesInTree[i] = elementIndex++ break } } super.visitElement(element) } }) } return targetsIndicesInTree } protected fun SuspendContextImpl.runActionInSuspendCommand(action: SuspendContextImpl.() -> Unit) { if (myInProgress) { action() } else { val command = object : SuspendContextCommandImpl(this) { override fun contextAction(suspendContext: SuspendContextImpl) { action(suspendContext) } } // Try to execute the action inside a command if we aren't already inside it. debuggerSession.process.managerThread.invoke(command) } } protected fun processStackFramesOnPooledThread(callback: List<XStackFrame>.() -> Unit) { val frameProxy = debuggerContext.frameProxy ?: error("Frame proxy is absent") val debugProcess = debuggerContext.debugProcess ?: error("Debug process is absent") val nodeManager = debugProcess.xdebugProcess!!.nodeManager val descriptor = nodeManager.getStackFrameDescriptor(null, frameProxy) val stackFrames = debugProcess.positionManager.createStackFrames(descriptor) if (stackFrames.isEmpty()) { error("Can't create stack frame for $descriptor") } ApplicationManager.getApplication().executeOnPooledThread { stackFrames.callback() } } protected fun countBreakpointsNumber(file: KotlinBaseTest.TestFile) = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.content, "//Breakpoint!").size protected fun SuspendContextImpl.invokeInManagerThread(callback: () -> Unit) { assert(debugProcess.isAttached) debugProcess.managerThread.invokeCommand(object : DebuggerCommand { override fun action() = callback() override fun commandCancelled() = error(message = "Test was cancelled") }) } override fun addMavenDependency(compilerFacility: DebuggerTestCompilerFacility, library: String) { val regex = Regex(MAVEN_DEPENDENCY_REGEX) val result = regex.matchEntire(library) ?: return val (_, groupId: String, artifactId: String, version: String) = result.groupValues addMavenDependency(compilerFacility, groupId, artifactId, version) } override fun createJavaParameters(mainClass: String?): JavaParameters { val params = super.createJavaParameters(mainClass) for (entry in classPath) { params.classPath.add(entry) } return params } protected fun addMavenDependency(compilerFacility: DebuggerTestCompilerFacility, groupId: String, artifactId: String, version: String) { val description = JpsMavenRepositoryLibraryDescriptor(groupId, artifactId, version) val artifacts = loadDependencies(description) compilerFacility.addDependencies(artifacts.map { it.file.presentableUrl }) addLibraries(artifacts) } private fun addLibraries(artifacts: MutableList<OrderRoot>) { runInEdtAndWait { ConfigLibraryUtil.addLibrary(module, "ARTIFACTS") { for (artifact in artifacts) { classPath.add(artifact.file.presentableUrl) // for sandbox jvm addRoot(artifact.file, artifact.type) } } } } protected fun loadDependencies( description: JpsMavenRepositoryLibraryDescriptor ): MutableList<OrderRoot> { return JarRepositoryManager.loadDependenciesSync( project, description, setOf(ArtifactKind.ARTIFACT), RemoteRepositoryDescription.DEFAULT_REPOSITORIES, null ) ?: throw AssertionError("Maven Dependency not found: $description") } }
apache-2.0
5c11c40aa874f8b5b5456b28d59ae268
41.479381
140
0.679772
5.50869
false
true
false
false
stupacki/MultiFunctions
multi-functions/src/main/kotlin/io/multifunctions/MultiMapIndexed.kt
1
3640
package io.multifunctions import io.multifunctions.models.Hepta import io.multifunctions.models.Hexa import io.multifunctions.models.Penta import io.multifunctions.models.Quad /** * Returns a list containing the results of applying the given [transform] function * to each element and its index in the original collection. * @param [transform] function that takes the index of an element and the element itself * and returns the result of the transform applied to the element. */ public inline infix fun <A, B, R> Iterable<Pair<A?, B?>>.mapIndexed(transform: (Int, A?, B?) -> R): List<R?> = mapIndexed { index, (first, second) -> transform(index, first, second) } /** * Returns a list containing the results of applying the given [transform] function * to each element and its index in the original collection. * @param [transform] function that takes the index of an element and the element itself * and returns the result of the transform applied to the element. */ public inline infix fun <A, B, C, R> Iterable<Triple<A?, B?, C?>>.mapIndexed(transform: (Int, A?, B?, C?) -> R): List<R?> = mapIndexed { index, (first, second, third) -> transform(index, first, second, third) } /** * Returns a list containing the results of applying the given [transform] function * to each element and its index in the original collection. * @param [transform] function that takes the index of an element and the element itself * and returns the result of the transform applied to the element. */ public inline infix fun <A, B, C, D, R> Iterable<Quad<A?, B?, C?, D?>>.mapIndexed(transform: (Int, A?, B?, C?, D?) -> R): List<R?> = mapIndexed { index, (first, second, third, fourth) -> transform(index, first, second, third, fourth) } /** * Returns a list containing the results of applying the given [transform] function * to each element and its index in the original collection. * @param [transform] function that takes the index of an element and the element itself * and returns the result of the transform applied to the element. */ public inline infix fun <A, B, C, D, E, R> Iterable<Penta<A?, B?, C?, D?, E?>>.mapIndexed(transform: (Int, A?, B?, C?, D?, E?) -> R): List<R?> = mapIndexed { index, (first, second, third, fourth, fifth) -> transform(index, first, second, third, fourth, fifth) } /** * Returns a list containing the results of applying the given [transform] function * to each element and its index in the original collection. * @param [transform] function that takes the index of an element and the element itself * and returns the result of the transform applied to the element. */ public inline infix fun <A, B, C, D, E, F, R> Iterable<Hexa<A?, B?, C?, D?, E?, F?>>.mapIndexed( transform: (Int, A?, B?, C?, D?, E?, F?) -> R ): List<R?> = mapIndexed { index, (first, second, third, fourth, fifth, sixth) -> transform(index, first, second, third, fourth, fifth, sixth) } /** * Returns a list containing the results of applying the given [transform] function * to each element and its index in the original collection. * @param [transform] function that takes the index of an element and the element itself * and returns the result of the transform applied to the element. */ public inline infix fun <A, B, C, D, E, F, G, R> Iterable<Hepta<A?, B?, C?, D?, E?, F?, G?>>.mapIndexed( transform: (Int, A?, B?, C?, D?, E?, F?, G?) -> R ): List<R?> = mapIndexed { index, (first, second, third, fourth, fifth, sixth, seventh) -> transform(index, first, second, third, fourth, fifth, sixth, seventh) }
apache-2.0
190e1c64462ce535c460c55b657caef2
46.894737
144
0.681868
3.775934
false
false
false
false
youdonghai/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/PopupActions.kt
1
7456
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.hints import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager import com.intellij.codeInsight.hints.settings.ParameterNameHintsConfigurable import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.injected.editor.EditorWindow import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.util.PsiTreeUtil private fun String.capitalize() = StringUtil.capitalizeWords(this, true) class ShowSettingsWithAddedPattern : AnAction() { init { templatePresentation.description = CodeInsightBundle.message("inlay.hints.show.settings.description") templatePresentation.text = CodeInsightBundle.message("inlay.hints.show.settings", "_") } override fun update(e: AnActionEvent) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val info = getMethodInfoAtOffset(editor, file) ?: return val name = info.getMethodName() e.presentation.text = CodeInsightBundle.message("inlay.hints.show.settings", name) } override fun actionPerformed(e: AnActionEvent) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val language = file.language.baseLanguage ?: file.language InlayParameterHintsExtension.forLanguage(language) ?: return val info = getMethodInfoAtOffset(editor, file) ?: return val dialog = ParameterNameHintsConfigurable(language, info.toPattern()) dialog.show() } } class BlacklistCurrentMethodIntention : IntentionAction, HighPriorityAction { companion object { private val presentableText = CodeInsightBundle.message("inlay.hints.blacklist.method") private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name") } override fun getText(): String = presentableText override fun getFamilyName(): String = presentableFamilyName override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { return InlayParameterHintsExtension.hasAnyExtensions() && hasParameterHintAtOffset(editor, file) } override fun invoke(project: Project, editor: Editor, file: PsiFile) { addMethodAtCaretToBlackList(editor, file) } override fun startInWriteAction() = false } class ToggleInlineHintsAction : AnAction() { companion object { private val disableText = CodeInsightBundle.message("inlay.hints.disable.action.text").capitalize() private val enableText = CodeInsightBundle.message("inlay.hints.enable.action.text").capitalize() } override fun update(e: AnActionEvent) { if (!InlayParameterHintsExtension.hasAnyExtensions()) { e.presentation.isEnabledAndVisible = false return } val isHintsShownNow = EditorSettingsExternalizable.getInstance().isShowParameterNameHints e.presentation.text = if (isHintsShownNow) disableText else enableText e.presentation.isEnabledAndVisible = true if (isInMainEditorPopup(e)) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val caretOffset = editor.caretModel.offset e.presentation.isEnabledAndVisible = !isHintsShownNow && isPossibleHintNearOffset(file, caretOffset) } } private fun isInMainEditorPopup(e: AnActionEvent): Boolean { if (e.place != ActionPlaces.EDITOR_POPUP) return false val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return false val offset = editor.caretModel.offset return !editor.inlayModel.hasInlineElementAt(offset) } override fun actionPerformed(e: AnActionEvent) { val settings = EditorSettingsExternalizable.getInstance() val before = settings.isShowParameterNameHints settings.isShowParameterNameHints = !before refreshAllOpenEditors() } } private fun hasParameterHintAtOffset(editor: Editor, file: PsiFile): Boolean { if (editor is EditorWindow) return false val offset = editor.caretModel.offset val element = file.findElementAt(offset) val startOffset = element?.textRange?.startOffset ?: offset val endOffset = element?.textRange?.endOffset ?: offset return editor.inlayModel .getInlineElementsInRange(startOffset, endOffset) .find { ParameterHintsPresentationManager.getInstance().isParameterHint(it) } != null } private fun refreshAllOpenEditors() { ProjectManager.getInstance().openProjects.forEach { val psiManager = PsiManager.getInstance(it) val daemonCodeAnalyzer = DaemonCodeAnalyzer.getInstance(it) val fileEditorManager = FileEditorManager.getInstance(it) fileEditorManager.selectedFiles.forEach { psiManager.findFile(it)?.let { daemonCodeAnalyzer.restart(it) } } } } private fun getMethodInfoAtOffset(editor: Editor, file: PsiFile): MethodInfo? { val offset = editor.caretModel.offset val element = file.findElementAt(offset) val hintsProvider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null val method = PsiTreeUtil.findFirstParent(element, { e -> hintsProvider.getMethodInfo(e) != null }) ?: return null return hintsProvider.getMethodInfo(method) } private fun addMethodAtCaretToBlackList(editor: Editor, file: PsiFile) { val info = getMethodInfoAtOffset(editor, file) ?: return ParameterNameHintsSettings.getInstance().addIgnorePattern(file.language, info.toPattern()) refreshAllOpenEditors() } fun isPossibleHintNearOffset(file: PsiFile, offset: Int): Boolean { val hintProvider = InlayParameterHintsExtension.forLanguage(file.language) ?: return false var element = file.findElementAt(offset) for (i in 0..3) { if (element == null) return false val hints = hintProvider.getParameterHints(element) if (hints.isNotEmpty()) return true element = element.parent } return false } fun MethodInfo.toPattern() = this.fullyQualifiedName + '(' + this.paramNames.joinToString(",") + ')'
apache-2.0
13327bd33c56997ef61adf77aebe9281
38.036649
115
0.771862
4.80103
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/data/course/repository/CoursePurchaseDataRepositoryImpl.kt
1
1086
package org.stepik.android.data.course.repository import org.stepik.android.domain.course.repository.CoursePurchaseDataRepository import org.stepik.android.domain.course_payments.model.DeeplinkPromoCode import org.stepik.android.presentation.course_purchase.model.CoursePurchaseDataResult import javax.inject.Inject class CoursePurchaseDataRepositoryImpl @Inject constructor() : CoursePurchaseDataRepository { private var deeplinkPromoCode: DeeplinkPromoCode = DeeplinkPromoCode.EMPTY private var coursePurchaseDataResult: CoursePurchaseDataResult = CoursePurchaseDataResult.Empty @Synchronized override fun getDeeplinkPromoCode(): DeeplinkPromoCode = deeplinkPromoCode @Synchronized override fun getCoursePurchaseData(): CoursePurchaseDataResult = coursePurchaseDataResult @Synchronized override fun savePurchaseData(deeplinkPromoCode: DeeplinkPromoCode, coursePurchaseDataResult: CoursePurchaseDataResult) { this.deeplinkPromoCode = deeplinkPromoCode this.coursePurchaseDataResult = coursePurchaseDataResult } }
apache-2.0
b62fe5bc3cff80698db6cbf238b67d5a
39.259259
125
0.823204
5.626943
false
false
false
false
ursjoss/sipamato
core/core-sync/src/main/kotlin/ch/difty/scipamato/core/sync/Aliases.kt
2
838
package ch.difty.scipamato.core.sync typealias PublicCode = ch.difty.scipamato.publ.db.tables.pojos.Code typealias PublicCodeClass = ch.difty.scipamato.publ.db.tables.pojos.CodeClass typealias PublicKeyword = ch.difty.scipamato.publ.db.tables.pojos.Keyword typealias PublicLanguage = ch.difty.scipamato.publ.db.tables.pojos.Language typealias PublicNewsletter = ch.difty.scipamato.publ.db.tables.pojos.Newsletter typealias PublicNewsletterTopic = ch.difty.scipamato.publ.db.tables.pojos.NewsletterTopic typealias PublicNewStudy = ch.difty.scipamato.publ.db.tables.pojos.NewStudy typealias PublicNewStudyTopic = ch.difty.scipamato.publ.db.tables.pojos.NewStudyTopic typealias PublicNewStudyPageLink = ch.difty.scipamato.publ.db.tables.pojos.NewStudyPageLink typealias PublicPaper = ch.difty.scipamato.publ.db.tables.pojos.Paper
gpl-3.0
d3cf134fff272764324500206a6c5b97
68.833333
92
0.836516
3.675439
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/refactoring/rename/RenameInplacePopupUsagesCollector.kt
2
1465
// 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.rename import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector class RenameInplacePopupUsagesCollector : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP companion object { private val GROUP = EventLogGroup("rename.inplace.popup", 2) @JvmField val changedOnHide = EventFields.Boolean("changedOnHide") @JvmField val linkUsed = EventFields.Boolean("linkUsed") @JvmField val searchInCommentsOnHide = EventFields.Boolean("search_in_comments_on_hide") @JvmField val searchInTextOccurrencesOnHide = EventFields.Boolean("search_in_text_occurrences_on_hide") @JvmField val show = registerInplacePopupEventEvent("show"); @JvmField val hide = registerInplacePopupEventEvent("hide"); @JvmField val openRenameDialog = registerInplacePopupEventEvent("openRenameDialog"); @JvmField val settingsChanged = registerInplacePopupEventEvent("settingsChanged"); private fun registerInplacePopupEventEvent(eventId: String) = GROUP.registerVarargEvent(eventId, EventFields.InputEvent, searchInCommentsOnHide, searchInTextOccurrencesOnHide, changedOnHide, linkUsed) } }
apache-2.0
4a91d5f876e6fb58f379068d981212ea
51.357143
144
0.799317
5.176678
false
false
false
false
leafclick/intellij-community
platform/lang-impl/src/com/intellij/platform/ModuleAttachProcessor.kt
1
7595
// 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.platform import com.intellij.CommonBundle import com.intellij.configurationStore.StoreUtil import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector import com.intellij.ide.impl.OpenProjectTask import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.impl.ModuleManagerImpl import com.intellij.openapi.project.Project import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.project.modifyModules import com.intellij.openapi.project.rootManager import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsDirectoryMapping import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.platform.ModuleAttachProcessor.Companion.getPrimaryModule import com.intellij.projectImport.ProjectAttachProcessor import com.intellij.projectImport.ProjectOpenedCallback import com.intellij.util.io.directoryStreamIfExists import com.intellij.util.io.exists import com.intellij.util.io.systemIndependentPath import java.io.File import java.nio.file.Path import java.util.* private val LOG = logger<ModuleAttachProcessor>() class ModuleAttachProcessor : ProjectAttachProcessor() { companion object { @JvmStatic fun findModuleInBaseDir(project: Project): Module? { val baseDir = project.baseDir return ModuleManager.getInstance(project).modules.firstOrNull { module -> module.rootManager.contentRoots.any { it == baseDir } } } @JvmStatic fun getPrimaryModule(project: Project) = if (canAttachToProject()) findModuleInBaseDir(project) else null @JvmStatic fun getSortedModules(project: Project): List<Module> { val primaryModule = getPrimaryModule(project) val result = ArrayList<Module>() ModuleManager.getInstance(project).modules.filterTo(result) { it !== primaryModule} result.sortBy(Module::getName) primaryModule?.let { result.add(0, it) } return result } /** * @param project the project * @return null if either multi-projects are not enabled or the project has only one module */ @JvmStatic fun getMultiProjectDisplayName(project: Project): String? { if (!canAttachToProject()) { return null } val modules = ModuleManager.getInstance(project).modules if (modules.size <= 1) { return null } val primaryModule = getPrimaryModule(project) ?: modules.first() val result = StringBuilder(primaryModule.name) result.append(", ") for (module in modules) { if (module === primaryModule) { continue } result.append(module.name) break } if (modules.size > 2) { result.append("...") } return result.toString() } } override fun attachToProject(project: Project, projectDir: Path, callback: ProjectOpenedCallback?): Boolean { val dotIdeaDir = projectDir.resolve(Project.DIRECTORY_STORE_FOLDER) if (!dotIdeaDir.exists()) { val options = OpenProjectTask(useDefaultProjectAsTemplate = true, isNewProject = true) val newProject = ProjectManagerEx.getInstanceEx().newProject(projectDir, null, options) ?: return false PlatformProjectOpenProcessor.runDirectoryProjectConfigurators(projectDir, newProject, true) StoreUtil.saveSettings(newProject) runWriteAction { Disposer.dispose(newProject) } } val newModule = try { findMainModule(project, dotIdeaDir) ?: findMainModule(project, projectDir) } catch (e: Exception) { LOG.info(e) Messages.showErrorDialog(project, "Cannot attach project: ${e.message}", CommonBundle.getErrorTitle()) return false } LifecycleUsageTriggerCollector.onProjectModuleAttached(project) if (newModule != null) { callback?.projectOpened(project, newModule) return true } return Messages.showYesNoDialog(project, "The project at $projectDir uses a non-standard layout and cannot be attached to this project. Would you like to open it in a new window?", "Open Project", Messages.getQuestionIcon()) != Messages.YES } override fun beforeDetach(module: Module) { removeVcsMapping(module) } } private fun findMainModule(project: Project, projectDir: Path): Module? { projectDir.directoryStreamIfExists({ path -> path.fileName.toString().endsWith(ModuleManagerImpl.IML_EXTENSION) }) { directoryStream -> for (file in directoryStream) { return attachModule(project, file) } } return null } private fun attachModule(project: Project, imlFile: Path): Module { val module = project.modifyModules { loadModule(imlFile.systemIndependentPath) } val newModule = ModuleManager.getInstance(project).findModuleByName(module.name)!! val primaryModule = addPrimaryModuleDependency(project, newModule) if (primaryModule != null) { val dotIdeaDirParent = imlFile.parent?.parent?.let { LocalFileSystem.getInstance().findFileByPath(it.toString()) } if (dotIdeaDirParent != null) { addVcsMapping(primaryModule, dotIdeaDirParent) } } return newModule } private fun addVcsMapping(primaryModule: Module, addedModuleContentRoot: VirtualFile) { val project = primaryModule.project val vcsManager = ProjectLevelVcsManager.getInstance(project) val mappings = vcsManager.directoryMappings if (mappings.size == 1) { val contentRoots = ModuleRootManager.getInstance(primaryModule).contentRoots // if we had one mapping for the root of the primary module and the added module uses the same VCS, change mapping to <Project Root> if (contentRoots.size == 1 && FileUtil.filesEqual(File(contentRoots[0].path), File(mappings[0].directory))) { val vcs = vcsManager.findVersioningVcs(addedModuleContentRoot) if (vcs != null && vcs.name == mappings[0].vcs) { vcsManager.directoryMappings = listOf(VcsDirectoryMapping.createDefault(vcs.name)) return } } } val vcs = vcsManager.findVersioningVcs(addedModuleContentRoot) if (vcs != null) { val newMappings = ArrayList(mappings) newMappings.add(VcsDirectoryMapping(addedModuleContentRoot.path, vcs.name)) vcsManager.directoryMappings = newMappings } } private fun addPrimaryModuleDependency(project: Project, newModule: Module): Module? { val module = getPrimaryModule(project) if (module != null && module !== newModule) { ModuleRootModificationUtil.addDependency(module, newModule) return module } return null } private fun removeVcsMapping(module: Module) { val project = module.project val vcsManager = ProjectLevelVcsManager.getInstance(project) val mappings = vcsManager.directoryMappings val newMappings = ArrayList(mappings) for (mapping in mappings) { for (root in ModuleRootManager.getInstance(module).contentRoots) { if (FileUtil.filesEqual(File(root.path), File(mapping.directory))) { newMappings.remove(mapping) } } } vcsManager.directoryMappings = newMappings }
apache-2.0
37a328b3f5e993c94a05a64f220b1700
37.165829
145
0.742989
4.758772
false
false
false
false
romannurik/muzei
wearable/src/main/java/com/google/android/apps/muzei/MuzeiArtworkItem.kt
1
4354
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei import android.app.Application import android.content.Intent import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.view.isVisible import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.get import androidx.lifecycle.viewModelScope import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import androidx.wear.widget.RoundedDrawable import coil.load import com.google.android.apps.muzei.room.Artwork import com.google.android.apps.muzei.room.MuzeiDatabase import com.google.android.apps.muzei.room.contentUri import com.google.android.apps.muzei.util.collectIn import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.shareIn import net.nurik.roman.muzei.R import net.nurik.roman.muzei.databinding.MuzeiArtworkItemBinding class MuzeiArtworkViewModel(application: Application) : AndroidViewModel(application) { val currentArtwork = MuzeiDatabase.getInstance(application).artworkDao().currentArtwork .shareIn(viewModelScope, SharingStarted.WhileSubscribed(5000L), 1) } class MuzeiArtworkViewHolder( private val binding: MuzeiArtworkItemBinding ) : RecyclerView.ViewHolder(binding.root) { init { val context = binding.root.context binding.image.setOnClickListener { context.startActivity(Intent(context, FullScreenActivity::class.java)) } } fun bind(artwork: Artwork) = binding.run { image.load(artwork.contentUri) { allowHardware(false) target { loadedDrawable -> image.setImageDrawable(RoundedDrawable().apply { isClipEnabled = true radius = root.context.resources.getDimensionPixelSize(R.dimen.art_detail_image_radius) drawable = loadedDrawable }) } listener( onError = { _, _ -> image.isVisible = false }, onSuccess = { _, _ -> image.isVisible = true } ) } image.contentDescription = artwork.title ?: artwork.byline ?: artwork.attribution title.text = artwork.title title.isVisible = !artwork.title.isNullOrBlank() byline.text = artwork.byline byline.isVisible = !artwork.byline.isNullOrBlank() attribution.text = artwork.attribution attribution.isVisible = !artwork.attribution.isNullOrBlank() } } class MuzeiArtworkAdapter<O>(owner: O) : ListAdapter<Artwork, MuzeiArtworkViewHolder>( object : DiffUtil.ItemCallback<Artwork>() { override fun areItemsTheSame( artwork1: Artwork, artwork2: Artwork ) = artwork1.id == artwork2.id override fun areContentsTheSame( artwork1: Artwork, artwork2: Artwork ) = artwork1 == artwork2 } ) where O : LifecycleOwner, O : ViewModelStoreOwner { init { val viewModel: MuzeiArtworkViewModel = ViewModelProvider(owner).get() viewModel.currentArtwork.collectIn(owner) { artwork -> submitList(listOfNotNull(artwork)) } } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ) = MuzeiArtworkViewHolder(MuzeiArtworkItemBinding.inflate( LayoutInflater.from(parent.context), parent, false)) override fun onBindViewHolder(holder: MuzeiArtworkViewHolder, position: Int) { holder.bind(getItem(position)) } }
apache-2.0
a3f2e23f1e763f6633416702d3b04d6f
37.530973
106
0.696371
4.8757
false
false
false
false
leafclick/intellij-community
platform/vcs-impl/src/com/intellij/util/ui/cloneDialog/VcsCloneDialogExtensionListItem.kt
1
2531
// 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.util.ui.cloneDialog import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtensionStatusLine import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.components.panels.VerticalLayout import com.intellij.util.IconUtil import com.intellij.util.ui.GridBag import com.intellij.util.ui.JBUI import java.awt.Color import java.awt.GridBagLayout import javax.swing.Icon import javax.swing.JLabel import javax.swing.JPanel import javax.swing.SwingConstants open class VcsCloneDialogExtensionListItem : JPanel(GridBagLayout()) { private val iconLabel: JLabel = JLabel() private val titleLabel: JLabel = JLabel() private val labelsPool = ArrayList<SimpleColoredComponent>() private val additionalLinesPanel = JPanel(VerticalLayout(0, SwingConstants.LEFT)) init { border = JBUI.Borders.empty(VcsCloneDialogUiSpec.ExtensionsList.topBottomInsets, VcsCloneDialogUiSpec.ExtensionsList.leftRightInsets) relayout() } private fun relayout() { var gbc = GridBag().nextLine().next() .insets(JBUI.insetsRight(VcsCloneDialogUiSpec.ExtensionsList.iconTitleGap)) .weightx(0.0) .anchor(GridBag.LINE_START) .fillCellNone() add(iconLabel, gbc) gbc = gbc.next() .weightx(1.0) .insets(JBUI.emptyInsets()) .fillCellHorizontally() titleLabel.font = JBUI.Fonts.label().asBold() add(titleLabel, gbc) gbc = gbc.nextLine().next().next() .insets(JBUI.emptyInsets()) .fillCellHorizontally() add(additionalLinesPanel, gbc) } fun setTitle(title: String) { titleLabel.text = title } fun setIcon(icon: Icon) { val scale = VcsCloneDialogUiSpec.ExtensionsList.iconSize.float / icon.iconWidth iconLabel.icon = IconUtil.scale(icon, null, scale) } fun setAdditionalStatusLines(additionalLines: List<VcsCloneDialogExtensionStatusLine>) { additionalLinesPanel.removeAll() while (labelsPool.size < additionalLines.size) { labelsPool.add(SimpleColoredComponent()) } for ((index, line) in additionalLines.withIndex()) { val component = labelsPool[index] component.ipad = JBUI.emptyInsets() component.clear() component.append(line.text, line.attribute, line.actionListener) additionalLinesPanel.add(component) } } fun setTitleForeground(foreground: Color) { titleLabel.foreground = foreground } }
apache-2.0
dcd2fd75ef7b9c8e18834bf65671c5de
31.883117
140
0.741604
4.282572
false
false
false
false
mrbublos/vkm
app/src/main/java/vkm/vkm/adapters/CompositionListAdapter.kt
1
4506
package vkm.vkm.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.lifecycle.Observer import kotlinx.android.synthetic.main.composition_list_element.view.* import vkm.vkm.* import vkm.vkm.utils.Composition import vkm.vkm.utils.VkmFragment import vkm.vkm.utils.equalsTo class CompositionListAdapter(private val fragment: VkmFragment, resource: Int, val data: List<Composition>, private var elementClickListener: (composition: Composition, view: View) -> Unit? = { _, _ -> }) : ArrayAdapter<Composition>(fragment.context, resource, data) { private val activity = fragment.activity as PagerActivity private var playing: Composition? = null private var loading: Composition? = null init { activity.musicPlayer?.loadingComposition?.observe(fragment, Observer { loading = it notifyDataSetChanged() }) activity.musicPlayer?.displayedComposition?.observe(fragment, Observer { playing = it notifyDataSetChanged() }) } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.composition_list_element, null) val composition = getItem(position) composition?.let { view.name.text = composition.name view.artist.text = composition.artist // determining icon to display var withAction = false val trackAvailable = composition.hash.isNotEmpty() || composition.url.trim().isNotEmpty() val actionButton = view.imageView val audioControl = view.audioControl audioControl.visibility = View.VISIBLE if (trackAvailable) { when { activity.musicPlayer?.isPlaying() == true && playing?.equalsTo(composition) == true -> audioControl.apply { setImageDrawable(context.getDrawable(R.drawable.ic_stop)) setOnClickListener { activity.musicPlayer?.stop() } } loading?.equalsTo(composition) == true -> audioControl.apply { setImageDrawable(context.getDrawable(R.drawable.ic_loading)) setOnClickListener { activity.musicPlayer?.stop() } } else -> audioControl?.apply { setOnClickListener { activity.playNewTrack(data, composition) } setImageDrawable(context.getDrawable(R.drawable.ic_play)) } } } else { audioControl?.setImageDrawable(context.getDrawable(R.drawable.ic_unavailable)) } if (fragment is SearchFragment) { if (trackAvailable) { withAction = true actionButton?.setImageDrawable(context.getDrawable(R.drawable.ic_add)) DownloadManager.getDownloaded().find { it.equalsTo(composition) }?.let { actionButton?.setImageDrawable(context.getDrawable(R.drawable.ic_downloaded)) } DownloadManager.getQueue().find { it.equalsTo(composition) }?.let { actionButton?.setImageDrawable(context.getDrawable(R.drawable.ic_downloading)) withAction = false } DownloadManager.getInProgress().find { it.equalsTo(composition) }?.let { actionButton?.setImageDrawable(context.getDrawable(R.drawable.ic_downloading)) withAction = false audioControl?.visibility = View.INVISIBLE } } else { withAction = false actionButton?.setImageDrawable(context.getDrawable(R.drawable.ic_unavailable)) } } else if (fragment is HistoryFragment) { actionButton?.setImageDrawable(context.getDrawable(android.R.drawable.ic_delete)) withAction = true } // adding icon click listener actionButton?.takeIf { withAction }?.setOnClickListener { v -> elementClickListener.invoke(composition, v) this.notifyDataSetInvalidated() } } return view } }
gpl-3.0
315d3a77cf0f5a2141c689c09862f8f3
43.623762
268
0.595428
5.660804
false
false
false
false
mrbublos/vkm
app/src/main/java/vkm/vkm/utils/db/Db.kt
1
1015
package vkm.vkm.utils.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import vkm.vkm.utils.Composition import vkm.vkm.utils.Proxy @Database(entities = [Composition::class, Proxy::class], version = 1, exportSchema = false) abstract class Db : RoomDatabase() { companion object { @Volatile private var instance: Db? = null fun instance(context: Context): Db { val i = instance if (i != null) { return i } return synchronized(this) { val i2 = instance if (i2 != null) { i2 } else { val newInstance = Room.databaseBuilder(context.applicationContext, Db::class.java, "vkm.db").build() instance = newInstance newInstance } } } } abstract fun tracksDao(): TracksDao abstract fun proxyDao(): ProxyDao }
gpl-3.0
8abbffde489836a2620d9db812e9f0a4
28.028571
120
0.574384
4.72093
false
false
false
false
smmribeiro/intellij-community
platform/external-system-api/src/com/intellij/openapi/externalSystem/model/serialization.kt
11
3406
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.model import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.externalSystem.ExternalSystemManager import com.intellij.openapi.externalSystem.service.project.ProjectDataManager import com.intellij.serialization.NonDefaultConstructorInfo import com.intellij.serialization.ReadConfiguration import com.intellij.serialization.WriteConfiguration // do not use SkipNullAndEmptySerializationFilter for now because can lead to issues fun createCacheWriteConfiguration() = WriteConfiguration(allowAnySubTypes = true) private fun createDataClassResolver(log: Logger): (name: String, hostObject: DataNode<*>?) -> Class<*>? { val projectDataManager = ProjectDataManager.getInstance() val managerClassLoaders = ExternalSystemManager.EP_NAME.iterable.asSequence() .map { it.javaClass.classLoader } .toSet() return fun(name: String, hostObject: DataNode<*>?): Class<*>? { var classLoadersToSearch = managerClassLoaders val services = if (hostObject == null) emptyList() else projectDataManager!!.findService(hostObject.key) if (!services.isNullOrEmpty()) { val set = LinkedHashSet<ClassLoader>(managerClassLoaders.size + services.size) set.addAll(managerClassLoaders) services.mapTo(set) { it.javaClass.classLoader } classLoadersToSearch = set } for (classLoader in classLoadersToSearch) { try { return classLoader.loadClass(name) } catch (e: ClassNotFoundException) { } } log.warn("Cannot find class `$name`") return null } } @JvmOverloads fun createCacheReadConfiguration(log: Logger, testOnlyClassLoader: ClassLoader? = null): ReadConfiguration { val dataNodeResolver = if (testOnlyClassLoader == null) createDataClassResolver(log) else null return createDataNodeReadConfiguration(fun(name: String, hostObject: Any): Class<*>? { return when { hostObject !is DataNode<*> -> { val hostObjectClass = hostObject.javaClass try { hostObjectClass.classLoader.loadClass(name) } catch (e: ClassNotFoundException) { log.debug("cannot find class $name using class loader of class ${hostObjectClass.name} (classLoader=${hostObjectClass.classLoader})", e) // let's try system manager class loaders dataNodeResolver?.invoke(name, null) ?: throw e } } dataNodeResolver == null -> testOnlyClassLoader!!.loadClass(name) else -> dataNodeResolver(name, hostObject) } }) } fun createDataNodeReadConfiguration(loadClass: ((name: String, hostObject: Any) -> Class<*>?)): ReadConfiguration { return ReadConfiguration(allowAnySubTypes = true, resolvePropertyMapping = { beanClass -> when (beanClass.name) { "org.jetbrains.kotlin.idea.configuration.KotlinTargetData" -> NonDefaultConstructorInfo(listOf("externalName"), beanClass.getDeclaredConstructor(String::class.java)) "org.jetbrains.kotlin.idea.configuration.KotlinAndroidSourceSetData" -> NonDefaultConstructorInfo(listOf("sourceSetInfos"), beanClass.constructors.first()) else -> null } }, loadClass = loadClass, beanConstructed = { if (it is ProjectSystemId) { it.intern() } else { it } }) }
apache-2.0
afcc09807b7ba0712ce46f3e6fc187ec
42.126582
171
0.729301
4.803949
false
true
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/viewholders/RewardViewHolder.kt
1
12131
package com.kickstarter.ui.viewholders import android.annotation.SuppressLint import android.content.Intent import android.util.Pair import android.view.View import androidx.annotation.NonNull import androidx.recyclerview.widget.LinearLayoutManager import com.jakewharton.rxbinding.view.RxView import com.kickstarter.R import com.kickstarter.databinding.ItemRewardBinding import com.kickstarter.libs.rx.transformers.Transformers.observeForUI import com.kickstarter.libs.utils.NumberUtils import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.libs.utils.ObjectUtils.requireNonNull import com.kickstarter.libs.utils.RewardItemDecorator import com.kickstarter.libs.utils.RewardUtils import com.kickstarter.libs.utils.RewardViewUtils import com.kickstarter.libs.utils.TransitionUtils.slideInFromRight import com.kickstarter.libs.utils.TransitionUtils.transition import com.kickstarter.libs.utils.ViewUtils import com.kickstarter.libs.utils.extensions.isTrue import com.kickstarter.libs.utils.extensions.setGone import com.kickstarter.models.Project import com.kickstarter.models.Reward import com.kickstarter.ui.IntentKey import com.kickstarter.ui.activities.BackingActivity import com.kickstarter.ui.adapters.RewardItemsAdapter import com.kickstarter.ui.data.ProjectData import com.kickstarter.viewmodels.RewardViewHolderViewModel import rx.android.schedulers.AndroidSchedulers class RewardViewHolder(private val binding: ItemRewardBinding, val delegate: Delegate?, private val inset: Boolean = false) : KSViewHolder(binding.root) { interface Delegate { fun rewardClicked(reward: Reward) } private val ksString = requireNotNull(environment().ksString()) private var viewModel = RewardViewHolderViewModel.ViewModel(environment()) private val currencyConversionString = context().getString(R.string.About_reward_amount) private val remainingRewardsString = context().getString(R.string.Left_count_left_few) init { val rewardItemAdapter = setUpRewardItemsAdapter() this.viewModel.outputs.conversionIsGone() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe(ViewUtils.setGone(this.binding.rewardConversionTextView)) this.viewModel.outputs.conversion() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { setConversionTextView(it) } this.viewModel.outputs.descriptionForNoReward() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { this.binding.rewardDescriptionTextView.setText(it) } this.viewModel.outputs.descriptionForReward() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { this.binding.rewardDescriptionTextView.text = it } this.viewModel.outputs.descriptionIsGone() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { ViewUtils.setGone(this.binding.rewardDescriptionContainer, it) } this.viewModel.outputs.buttonIsEnabled() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { this.binding.rewardPledgeButton.isEnabled = it } this.viewModel.outputs.remainingIsGone() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe(ViewUtils.setGone(this.binding.rewardRemainingTextView)) this.viewModel.outputs.limitContainerIsGone() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { ViewUtils.setGone(this.binding.rewardLimitContainer, it) } this.viewModel.outputs.remaining() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { setRemainingRewardsTextView(it) } this.viewModel.outputs.buttonCTA() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { this.binding.rewardPledgeButton.setText(it) } this.viewModel.outputs.shippingSummary() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { setShippingSummaryText(it) } this.viewModel.outputs.shippingSummaryIsGone() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { this.binding.rewardShippingSummary.setGone(it) } this.viewModel.outputs.minimumAmountTitle() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { this.binding.rewardMinimumTextView.text = it } this.viewModel.outputs.reward() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { this.binding.rewardEndingTextView.text = formattedExpirationString(it) } this.viewModel.outputs.endDateSectionIsGone() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { ViewUtils.setGone(this.binding.rewardEndingTextView, it) } this.viewModel.outputs.rewardItems() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { rewardItemAdapter.rewardsItems(it) } this.viewModel.outputs.rewardItemsAreGone() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe(ViewUtils.setGone(this.binding.rewardsItemSection)) this.viewModel.outputs.titleForNoReward() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { this.binding.rewardTitleTextView.setText(it) } this.viewModel.outputs.titleForReward() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { this.binding.rewardTitleTextView.text = it } this.viewModel.outputs.titleIsGone() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { ViewUtils.setGone(this.binding.rewardTitleTextView, it) } this.viewModel.outputs.showFragment() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { this.delegate?.rewardClicked(it.second) } this.viewModel.outputs.buttonIsGone() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { setPledgeButtonVisibility(it) } this.viewModel.outputs.backersCount() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { setBackersCountTextView(it) } this.viewModel.outputs.backersCountIsGone() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { ViewUtils.setGone(this.binding.rewardBackersCount, it) } this.viewModel.outputs.estimatedDelivery() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { this.binding.rewardEstimatedDelivery.text = it } this.viewModel.outputs.estimatedDeliveryIsGone() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { ViewUtils.setGone(this.binding.rewardEstimatedDeliverySection, it) } this.viewModel.outputs.isMinimumPledgeAmountGone() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { ViewUtils.setGone(this.binding.rewardConversionTextView, it) ViewUtils.setGone(this.binding.rewardMinimumTextView, it) } RxView.clicks(this.binding.rewardPledgeButton) .compose(bindToLifecycle()) .subscribe { this.viewModel.inputs.rewardClicked(this.adapterPosition) } this.viewModel.outputs.hasAddOnsAvailable() .filter { ObjectUtils.isNotNull(it) } .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { ViewUtils.setGone(this.binding.rewardAddOnsAvailable, !it) } this.viewModel.outputs.selectedRewardTagIsGone() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { isGone -> if (!isGone) this.binding.rewardSelectedRewardTag.visibility = View.VISIBLE else ViewUtils.setGone(this.binding.rewardSelectedRewardTag, true) } this.viewModel.outputs.localPickUpIsGone() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { this.binding.localPickupContainer.localPickupGroup.setGone(it) } this.viewModel.outputs.localPickUpName() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { this.binding.localPickupContainer.localPickupLocation.text = it } } override fun bindData(data: Any?) { @Suppress("UNCHECKED_CAST") val projectAndReward = requireNonNull(data as Pair<ProjectData, Reward>) val projectTracking = requireNonNull(projectAndReward.first, ProjectData::class.java) val reward = requireNonNull(projectAndReward.second, Reward::class.java) this.viewModel.inputs.configureWith(projectTracking, reward) } private fun formattedExpirationString(@NonNull reward: Reward): String { val detail = RewardUtils.deadlineCountdownDetail(reward, context(), this.ksString) val value = RewardUtils.deadlineCountdownValue(reward) return "$value $detail" } private fun setBackersCountTextView(count: Int) { val backersCountText = this.ksString.format( "rewards_info_backer_count_backers", count, "backer_count", NumberUtils.format(count) ) this.binding.rewardBackersCount.text = backersCountText } private fun setConversionTextView(@NonNull amount: String) { this.binding.rewardConversionTextView.text = this.ksString.format( this.currencyConversionString, "reward_amount", amount ) } private fun setPledgeButtonVisibility(gone: Boolean) { if (this.inset.isTrue()) { ViewUtils.setGone(this.binding.rewardButtonContainer, true) ViewUtils.setGone(this.binding.rewardButtonPlaceholder, true) } else { ViewUtils.setGone(this.binding.rewardButtonContainer, gone) when { gone -> ViewUtils.setGone(this.binding.rewardButtonPlaceholder, true) else -> ViewUtils.setInvisible(this.binding.rewardButtonPlaceholder, true) } } } private fun setRemainingRewardsTextView(@NonNull remaining: String) { this.binding.rewardRemainingTextView.text = this.ksString.format( this.remainingRewardsString, "left_count", remaining ) } private fun setShippingSummaryText(stringResAndLocationName: Pair<Int, String?>) { this.binding.rewardShippingSummary.text = RewardViewUtils.shippingSummary(context(), this.ksString, stringResAndLocationName) } @SuppressLint("UseCompatLoadingForDrawables") private fun setUpRewardItemsAdapter(): RewardItemsAdapter { val rewardItemAdapter = RewardItemsAdapter() val itemRecyclerView = binding.rewardsItemRecyclerView itemRecyclerView.adapter = rewardItemAdapter itemRecyclerView.layoutManager = LinearLayoutManager(context()) this.context().getDrawable(R.drawable.divider_grey_300_horizontal)?.let { itemRecyclerView.addItemDecoration(RewardItemDecorator(it)) } return rewardItemAdapter } private fun startBackingActivity(@NonNull project: Project) { val context = context() val intent = Intent(context, BackingActivity::class.java) .putExtra(IntentKey.PROJECT, project) context.startActivity(intent) transition(context, slideInFromRight()) } }
apache-2.0
dfecd7b05eaaa5641de24c4b0bec78e5
39.436667
154
0.672245
5.159932
false
false
false
false
Flank/flank
flank-scripts/src/main/kotlin/flank/scripts/ops/assemble/ios/BuildExample.kt
1
2233
package flank.scripts.ops.assemble.ios import flank.common.archive import flank.common.currentPath import flank.common.iOSTestProjectsPath import flank.scripts.ops.common.downloadXcPrettyIfNeeded import flank.scripts.ops.common.installPodsIfNeeded import flank.scripts.utils.failIfWindows import flank.scripts.utils.pipe import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.nio.file.StandardCopyOption import java.util.stream.Collectors fun buildIosExample() { failIfWindows() downloadXcPrettyIfNeeded() buildExample() } private fun buildExample() { val projectPath: Path = Paths.get(iOSTestProjectsPath, EARLGREY_EXAMPLE) val buildPath: Path = Paths.get(projectPath.toString(), "build").apply { toFile().deleteRecursively() } val xcodeCommandSwiftTests = createXcodeBuildForTestingCommand( buildDir = buildPath.toString(), scheme = "EarlGreyExampleSwiftTests", workspace = Paths.get(projectPath.toString(), "EarlGreyExample.xcworkspace").toString(), useLegacyBuildSystem = true ) installPodsIfNeeded(path = projectPath) xcodeCommandSwiftTests pipe "xcpretty" val xcodeCommandTests = createXcodeBuildForTestingCommand( buildDir = buildPath.toString(), scheme = "EarlGreyExampleTests", workspace = Paths.get(projectPath.toString(), "EarlGreyExample.xcworkspace").toString(), useLegacyBuildSystem = true ) xcodeCommandTests pipe "xcpretty" copyExampleOutputFiles(buildPath.toString()) } private fun copyExampleOutputFiles(buildPath: String) { val archiveFileName = "earlgrey_example.zip" val buildProductPath = Paths.get(buildPath, "Build", "Products") Files.walk(Paths.get("")) .filter { it.fileName.toString().endsWith("-iphoneos") || it.fileName.toString().endsWith(".xctestrun") } .map { it.toFile() } .collect(Collectors.toList()) .archive(archiveFileName, currentPath.toFile()) Files.move( Paths.get("", archiveFileName), Paths.get(buildProductPath.toString(), archiveFileName), StandardCopyOption.REPLACE_EXISTING ) } private const val EARLGREY_EXAMPLE = "EarlGreyExample"
apache-2.0
d6bfac4e8780180d6b5f08e04050c121
32.328358
113
0.730855
4.492958
false
true
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BolusElement.kt
1
588
package info.nightscout.androidaps.plugins.general.tidepool.elements import com.google.gson.annotations.Expose import info.nightscout.androidaps.db.Treatment import java.util.* class BolusElement(treatment: Treatment) : BaseElement(treatment.date, UUID.nameUUIDFromBytes(("AAPS-bolus" + treatment.date).toByteArray()).toString()) { @Expose var subType = "normal" @Expose var normal: Double = 0.0 @Expose var expectedNormal: Double = 0.0 init { type = "bolus" normal = treatment.insulin expectedNormal = treatment.insulin } }
agpl-3.0
a00239cfa52ac17db71265764bfd3109
25.772727
117
0.704082
4.140845
false
false
false
false
Briseus/Lurker
app/src/main/java/torille/fi/lurkforreddit/utils/test/SimpleCountingIdlingResource.kt
1
2798
/* * Copyright (C) 2015 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 torille.fi.lurkforreddit.utils.test import android.support.test.espresso.IdlingResource import java.util.concurrent.atomic.AtomicInteger /** * A simple counter implementation of [IdlingResource] that determines idleness by * maintaining an internal counter. When the counter is 0 - it is considered to be idle, when it is * non-zero it is not idle. This is very similar to the way a [java.util.concurrent.Semaphore] * behaves. * * * This class can then be used to wrap up operations that while in progress should block tests from * accessing the UI. */ class SimpleCountingIdlingResource /** * Creates a SimpleCountingIdlingResource * @param resourceName the resource name this resource should report to Espresso. */ (private val mResourceName: String) : IdlingResource { private val counter = AtomicInteger(0) // written from main thread, read from any thread. @Volatile private var resourceCallback: IdlingResource.ResourceCallback? = null override fun getName(): String { return mResourceName } override fun isIdleNow(): Boolean { return counter.get() == 0 } override fun registerIdleTransitionCallback(resourceCallback: IdlingResource.ResourceCallback) { this.resourceCallback = resourceCallback } /** * Increments the count of in-flight transactions to the resource being monitored. */ fun increment() { counter.getAndIncrement() } /** * Decrements the count of in-flight transactions to the resource being monitored. * * * If this operation results in the counter falling below 0 - an exception is raised. * @throws IllegalStateException if the counter is below 0. */ fun decrement() { val counterVal = counter.decrementAndGet() if (counterVal == 0) { // we've gone from non-zero to zero. That means we're idle now! Tell espresso. if (null != resourceCallback) { resourceCallback!!.onTransitionToIdle() } } if (counterVal < 0) { throw IllegalArgumentException("Counter has been corrupted!") } } }
mit
62c9a615096f4766dfd45a88b01b5878
31.16092
100
0.694067
4.742373
false
false
false
false
ohmae/VoiceMessageBoard
app/src/main/java/net/mm2d/android/vmb/font/FontFileChooserActivity.kt
1
6496
/* * Copyright (c) 2018 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.android.vmb.font import android.Manifest import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.Environment import android.view.MenuItem import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.DividerItemDecoration import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.functions.Consumer import io.reactivex.rxkotlin.addTo import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_file_chooser.* import net.mm2d.android.vmb.R.layout import net.mm2d.android.vmb.R.string import net.mm2d.android.vmb.dialog.PermissionDialog import net.mm2d.android.vmb.dialog.PermissionDialog.OnCancelListener import net.mm2d.android.vmb.dialog.PermissionDialog.OnPositiveClickListener import net.mm2d.android.vmb.permission.PermissionHelper import net.mm2d.android.vmb.util.Toaster import java.io.File /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ class FontFileChooserActivity : AppCompatActivity(), OnCancelListener, OnPositiveClickListener { private val defaultPath = Environment.getExternalStorageDirectory() private var currentPath = defaultPath private val compositeDisposable = CompositeDisposable() private lateinit var fileAdapter: FileAdapter private lateinit var permissionHelper: PermissionHelper private val comparator = Comparator<File> { o1, o2 -> if (o1.isDirectory != o2.isDirectory) { if (o1.isDirectory) -1 else 1 } else { o1.compareTo(o2) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(layout.activity_file_chooser) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setTitle(string.title_file_chooser) permissionHelper = PermissionHelper( this, Manifest.permission.READ_EXTERNAL_STORAGE, PERMISSION_REQUEST_CODE ) setInitialPath() initRecyclerView() if (savedInstanceState == null) { checkPermission() } else { savedInstanceState.getString(CURRENT_PATH_KEY)?.let { currentPath = File(it) } setUpDirectory(currentPath) } } private fun setInitialPath() { val path = intent?.getStringExtra(EXTRA_INITIAL_PATH) ?: return File(path).let { if (it.exists() && it.canRead()) currentPath = if (it.isFile) it.parentFile else it } intent = null } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(CURRENT_PATH_KEY, currentPath.absolutePath) } private fun initRecyclerView() { fileAdapter = FileAdapter(this) { if (!it.canRead()) { Toaster.show(this, string.toast_can_not_read_file_or_directory) } else if (it.isDirectory) { setUpDirectory(it) } else if (FontUtils.isValidFontFile(it)) { setResult(Activity.RESULT_OK, Intent().setData(Uri.fromFile(it))) finish() } else { Toaster.showShort(this, string.toast_not_a_valid_font) } } recyclerView.adapter = fileAdapter recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL)) } private fun setUpDirectory(file: File) { currentPath = file supportActionBar?.subtitle = currentPath.absolutePath fileAdapter.setFiles(emptyArray()) progressBar.visibility = View.VISIBLE Single.fromCallable { file.listFiles().apply { sortWith(comparator) } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(Consumer { fileAdapter.setFiles(it) fileAdapter.notifyDataSetChanged() progressBar.visibility = View.INVISIBLE }) .addTo(compositeDisposable) } override fun onDestroy() { super.onDestroy() compositeDisposable.dispose() } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } override fun onBackPressed() { if (currentPath != defaultPath) { setUpDirectory(currentPath.parentFile) return } setResult(Activity.RESULT_CANCELED) super.onBackPressed() } private fun checkPermission() { if (permissionHelper.requestPermissionIfNeed()) { return } setUpDirectory(currentPath) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { when (permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults)) { PermissionHelper.Result.OTHER -> return PermissionHelper.Result.GRANTED -> setUpDirectory(currentPath) PermissionHelper.Result.DENIED -> { Toaster.show(this, string.toast_should_allow_storage_permission) finish() } PermissionHelper.Result.DENIED_ALWAYS -> PermissionDialog.show(this, string.dialog_storage_permission_message) } } override fun onCancel() { Toaster.show(this, string.toast_should_allow_storage_permission) finish() } override fun onPositiveClick() { finish() } companion object { private const val PERMISSION_REQUEST_CODE = 1 private const val CURRENT_PATH_KEY = "CURRENT_PATH_KEY" private const val EXTRA_INITIAL_PATH = "EXTRA_INITIAL_PATH" fun makeIntent(context: Context, path: String): Intent = Intent(context, FontFileChooserActivity::class.java).apply { putExtra(EXTRA_INITIAL_PATH, path) } } }
mit
3deca899b0713c3432fec1b182d5fa75
33.652406
100
0.660031
4.875847
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/introduceTypeAliasImpl.kt
1
14313
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce.introduceTypeAlias import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiElement import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.util.containers.LinkedMultiMap import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.descriptors.TypeAliasDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange import org.jetbrains.kotlin.idea.base.psi.unifier.toRange import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.compareDescriptors import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.refactoring.introduce.insertDeclaration import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier import org.jetbrains.kotlin.idea.util.psi.patternMatching.UnifierParameter import org.jetbrains.kotlin.idea.util.psi.patternMatching.match import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens.* import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.types.TypeUtils sealed class IntroduceTypeAliasAnalysisResult { class Error(@NlsContexts.DialogMessage val message: String) : IntroduceTypeAliasAnalysisResult() class Success(val descriptor: IntroduceTypeAliasDescriptor) : IntroduceTypeAliasAnalysisResult() } private fun IntroduceTypeAliasData.getTargetScope() = targetSibling.getResolutionScope(bindingContext, resolutionFacade) fun IntroduceTypeAliasData.analyze(): IntroduceTypeAliasAnalysisResult { val psiFactory = KtPsiFactory(originalTypeElement) val contextExpression = originalTypeElement.getStrictParentOfType<KtExpression>()!! val targetScope = getTargetScope() val dummyVar = psiFactory.createProperty("val a: Int").apply { typeReference!!.replace( originalTypeElement.parent as? KtTypeReference ?: if (originalTypeElement is KtTypeElement) psiFactory.createType( originalTypeElement ) else psiFactory.createType(originalTypeElement.text) ) } val newTypeReference = dummyVar.typeReference!! val newReferences = newTypeReference.collectDescendantsOfType<KtTypeReference> { it.resolveInfo != null } val newContext = dummyVar.analyzeInContext(targetScope, contextExpression) val project = originalTypeElement.project val unifier = KotlinPsiUnifier.DEFAULT val groupedReferencesToExtract = LinkedMultiMap<TypeReferenceInfo, TypeReferenceInfo>() val forcedCandidates = if (extractTypeConstructor) newTypeReference.typeElement!!.typeArgumentsAsTypes else emptyList() for (newReference in newReferences) { val resolveInfo = newReference.resolveInfo!! if (newReference !in forcedCandidates) { val originalDescriptor = resolveInfo.type.constructor.declarationDescriptor val newDescriptor = newContext[BindingContext.TYPE, newReference]?.constructor?.declarationDescriptor if (compareDescriptors(project, originalDescriptor, newDescriptor)) continue } val equivalenceRepresentative = groupedReferencesToExtract .keySet() .firstOrNull { unifier.unify(it.reference, resolveInfo.reference).isMatched } if (equivalenceRepresentative != null) { groupedReferencesToExtract.putValue(equivalenceRepresentative, resolveInfo) } else { groupedReferencesToExtract.putValue(resolveInfo, resolveInfo) } val referencesToExtractIterator = groupedReferencesToExtract.values().iterator() while (referencesToExtractIterator.hasNext()) { val referenceToExtract = referencesToExtractIterator.next() if (resolveInfo.reference.isAncestor(referenceToExtract.reference, true)) { referencesToExtractIterator.remove() } } } val typeParameterNameValidator = CollectingNameValidator() val brokenReferences = groupedReferencesToExtract.keySet().filter { groupedReferencesToExtract[it].isNotEmpty() } val typeParameterNames = KotlinNameSuggester.suggestNamesForTypeParameters(brokenReferences.size, typeParameterNameValidator) val typeParameters = (typeParameterNames zip brokenReferences).map { TypeParameter(it.first, groupedReferencesToExtract[it.second]) } if (typeParameters.any { it.typeReferenceInfos.any { info -> info.reference.typeElement == originalTypeElement } }) { return IntroduceTypeAliasAnalysisResult.Error(KotlinBundle.message("text.type.alias.cannot.refer.to.types.which.aren.t.accessible.in.the.scope.where.it.s.defined")) } val descriptor = IntroduceTypeAliasDescriptor(this, "Dummy", null, typeParameters) val initialName = KotlinNameSuggester.suggestTypeAliasNameByPsi(descriptor.generateTypeAlias(true).getTypeReference()!!.typeElement!!) { targetScope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null } return IntroduceTypeAliasAnalysisResult.Success(descriptor.copy(name = initialName)) } fun IntroduceTypeAliasData.getApplicableVisibilities(): List<KtModifierKeywordToken> = when (targetSibling.parent) { is KtClassBody -> listOf(PRIVATE_KEYWORD, PUBLIC_KEYWORD, INTERNAL_KEYWORD, PROTECTED_KEYWORD) is KtFile -> listOf(PRIVATE_KEYWORD, PUBLIC_KEYWORD, INTERNAL_KEYWORD) else -> emptyList() } fun IntroduceTypeAliasDescriptor.validate(): IntroduceTypeAliasDescriptorWithConflicts { val conflicts = MultiMap<PsiElement, String>() val originalType = originalData.originalTypeElement when { name.isEmpty() -> conflicts.putValue(originalType, KotlinBundle.message("text.no.name.provided.for.type.alias")) !name.isIdentifier() -> conflicts.putValue(originalType, KotlinBundle.message("text.type.alias.name.must.be.a.valid.identifier.0", name)) originalData.getTargetScope().findClassifier(Name.identifier(name), NoLookupLocation.FROM_IDE) != null -> conflicts.putValue(originalType, KotlinBundle.message("text.type.already.exists.in.the.target.scope", name)) } if (typeParameters.distinctBy { it.name }.size != typeParameters.size) { conflicts.putValue(originalType, KotlinBundle.message("text.type.parameter.names.must.be.distinct")) } if (visibility != null && visibility !in originalData.getApplicableVisibilities()) { conflicts.putValue(originalType, KotlinBundle.message("text.0.is.not.allowed.in.the.target.context", visibility)) } return IntroduceTypeAliasDescriptorWithConflicts(this, conflicts) } fun findDuplicates(typeAlias: KtTypeAlias): Map<KotlinPsiRange, () -> Unit> { val aliasName = typeAlias.name?.quoteIfNeeded() ?: return emptyMap() val aliasRange = typeAlias.textRange val typeAliasDescriptor = typeAlias.unsafeResolveToDescriptor() as TypeAliasDescriptor val unifierParameters = typeAliasDescriptor.declaredTypeParameters.map { UnifierParameter(it, null) } val unifier = KotlinPsiUnifier(unifierParameters) val psiFactory = KtPsiFactory(typeAlias) fun replaceTypeElement(occurrence: KtTypeElement, typeArgumentsText: String) { occurrence.replace(psiFactory.createType("$aliasName$typeArgumentsText").typeElement!!) } fun replaceOccurrence(occurrence: PsiElement, arguments: List<KtTypeElement>) { val typeArgumentsText = if (arguments.isNotEmpty()) "<${arguments.joinToString { it.text }}>" else "" when (occurrence) { is KtTypeElement -> { replaceTypeElement(occurrence, typeArgumentsText) } is KtSuperTypeCallEntry -> { occurrence.calleeExpression.typeReference?.typeElement?.let { replaceTypeElement(it, typeArgumentsText) } } is KtCallElement -> { val qualifiedExpression = occurrence.parent as? KtQualifiedExpression val callExpression = if (qualifiedExpression != null && qualifiedExpression.selectorExpression == occurrence) { qualifiedExpression.replaced(occurrence) } else occurrence val typeArgumentList = callExpression.typeArgumentList if (arguments.isNotEmpty()) { val newTypeArgumentList = psiFactory.createTypeArguments(typeArgumentsText) typeArgumentList?.replace(newTypeArgumentList) ?: callExpression.addAfter( newTypeArgumentList, callExpression.calleeExpression ) } else { typeArgumentList?.delete() } callExpression.calleeExpression?.replace(psiFactory.createExpression(aliasName)) } is KtExpression -> occurrence.replace(psiFactory.createExpression(aliasName)) } } val rangesWithReplacers = ArrayList<Pair<KotlinPsiRange, () -> Unit>>() val originalTypePsi = typeAliasDescriptor.underlyingType.constructor.declarationDescriptor?.let { DescriptorToSourceUtilsIde.getAnyDeclaration(typeAlias.project, it) } if (originalTypePsi != null) { for (reference in ReferencesSearch.search(originalTypePsi, LocalSearchScope(typeAlias.parent))) { val element = reference.element as? KtSimpleNameExpression ?: continue if ((element.textRange.intersects(aliasRange))) continue val arguments: List<KtTypeElement> val occurrence: KtElement val callElement = element.getParentOfTypeAndBranch<KtCallElement> { calleeExpression } if (callElement != null) { occurrence = callElement arguments = callElement.typeArguments.mapNotNull { it.typeReference?.typeElement } } else { val userType = element.getParentOfTypeAndBranch<KtUserType> { referenceExpression } if (userType != null) { occurrence = userType arguments = userType.typeArgumentsAsTypes.mapNotNull { it.typeElement } } else continue } if (arguments.size != typeAliasDescriptor.declaredTypeParameters.size) continue if (TypeUtils.isNullableType(typeAliasDescriptor.underlyingType) && occurrence is KtUserType && occurrence.parent !is KtNullableType ) continue rangesWithReplacers += occurrence.toRange() to { replaceOccurrence(occurrence, arguments) } } } typeAlias .getTypeReference() ?.typeElement .toRange() .match(typeAlias.parent, unifier) .asSequence() .filter { !(it.range.textRange.intersects(aliasRange)) } .mapNotNullTo(rangesWithReplacers) { match -> val occurrence = match.range.elements.singleOrNull() as? KtTypeElement ?: return@mapNotNullTo null val arguments = unifierParameters.mapNotNull { (match.substitution[it] as? KtTypeReference)?.typeElement } if (arguments.size != unifierParameters.size) return@mapNotNullTo null match.range to { replaceOccurrence(occurrence, arguments) } } return rangesWithReplacers.toMap() } private var KtTypeReference.typeParameterInfo: TypeParameter? by CopyablePsiUserDataProperty(Key.create("TYPE_PARAMETER_INFO")) fun IntroduceTypeAliasDescriptor.generateTypeAlias(previewOnly: Boolean = false): KtTypeAlias { val originalElement = originalData.originalTypeElement val psiFactory = KtPsiFactory(originalElement) for (typeParameter in typeParameters) for (it in typeParameter.typeReferenceInfos) { it.reference.typeParameterInfo = typeParameter } val typeParameterNames = typeParameters.map { it.name } val typeAlias = if (originalElement is KtTypeElement) { psiFactory.createTypeAlias(name, typeParameterNames, originalElement) } else { psiFactory.createTypeAlias(name, typeParameterNames, originalElement.text) } if (visibility != null && visibility != DEFAULT_VISIBILITY_KEYWORD) { typeAlias.addModifier(visibility) } for (typeParameter in typeParameters) for (it in typeParameter.typeReferenceInfos) { it.reference.typeParameterInfo = null } fun replaceUsage() { val aliasInstanceText = if (typeParameters.isNotEmpty()) { "$name<${typeParameters.joinToString { it.typeReferenceInfos.first().reference.text }}>" } else { name } when (originalElement) { is KtTypeElement -> originalElement.replace(psiFactory.createType(aliasInstanceText).typeElement!!) is KtExpression -> originalElement.replace(psiFactory.createExpression(aliasInstanceText)) } } fun introduceTypeParameters() { typeAlias.getTypeReference()!!.forEachDescendantOfType<KtTypeReference> { val typeParameter = it.typeParameterInfo ?: return@forEachDescendantOfType val typeParameterReference = psiFactory.createType(typeParameter.name) it.replace(typeParameterReference) } } return if (previewOnly) { introduceTypeParameters() typeAlias } else { replaceUsage() introduceTypeParameters() insertDeclaration(typeAlias, originalData.targetSibling) } }
apache-2.0
bb03047f012618eb3295c8e29a4dba36
48.020548
172
0.724796
5.569261
false
false
false
false
NineWorlds/serenity-android
serenity-app/src/main/kotlin/us/nineworlds/serenity/ui/video/player/ExoplayerPresenter.kt
1
6685
package us.nineworlds.serenity.ui.video.player import android.view.View import com.birbit.android.jobqueue.JobManager import com.google.android.exoplayer2.Player import com.google.android.exoplayer2.ui.PlayerControlView import moxy.InjectViewState import moxy.MvpPresenter import moxy.viewstate.strategy.SkipStrategy import moxy.viewstate.strategy.StateStrategyType import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode.MAIN import toothpick.Toothpick import us.nineworlds.serenity.common.android.mediacodec.MediaCodecInfoUtil import us.nineworlds.serenity.common.annotations.InjectionConstants import us.nineworlds.serenity.common.annotations.OpenForTesting import us.nineworlds.serenity.common.rest.SerenityClient import us.nineworlds.serenity.core.logger.Logger import us.nineworlds.serenity.core.model.VideoContentInfo import us.nineworlds.serenity.core.util.AndroidHelper import us.nineworlds.serenity.events.video.OnScreenDisplayEvent import us.nineworlds.serenity.injection.ForVideoQueue import us.nineworlds.serenity.jobs.video.StartPlaybackJob import us.nineworlds.serenity.jobs.video.StopPlaybackJob import us.nineworlds.serenity.jobs.video.UpdatePlaybackPostionJob import us.nineworlds.serenity.jobs.video.WatchedStatusJob import us.nineworlds.serenity.ui.video.player.ExoplayerContract.ExoplayerPresenter import us.nineworlds.serenity.ui.video.player.ExoplayerContract.ExoplayerView import java.util.LinkedList import javax.inject.Inject @OpenForTesting @InjectViewState @StateStrategyType(SkipStrategy::class) class ExoplayerPresenter : MvpPresenter<ExoplayerView>(), ExoplayerPresenter, PlayerControlView.VisibilityListener, Player.EventListener { @Inject lateinit var logger: Logger @field:[Inject ForVideoQueue] internal lateinit var videoQueue: LinkedList<VideoContentInfo> @Inject internal lateinit var serenityClient: SerenityClient @Inject internal lateinit var eventBus: EventBus @Inject internal lateinit var jobManager: JobManager @Inject internal lateinit var androidHelper: AndroidHelper internal lateinit var video: VideoContentInfo private var onScreenControllerShowing: Boolean = false override fun attachView(view: ExoplayerView?) { Toothpick.inject(this, Toothpick.openScope(InjectionConstants.APPLICATION_SCOPE)) super.attachView(view) eventBus.register(this) } override fun detachView(view: ExoplayerView?) { super.detachView(view) eventBus.unregister(this) } override fun updateWatchedStatus() { jobManager.addJobInBackground(WatchedStatusJob(video.id())) } override fun onSeekProcessed() = Unit override fun onPositionDiscontinuity(reason: Int) = Unit override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) = Unit override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) { if (Player.STATE_ENDED == playbackState) { stopPlaying(video.resumeOffset.toLong()) viewState.playbackEnded() return } } override fun onLoadingChanged(isLoading: Boolean) = Unit override fun onRepeatModeChanged(repeatMode: Int) = Unit override fun videoId(): String = video.id() override fun stopPlaying(currentPosition: Long) { jobManager.addJobInBackground(StopPlaybackJob(video.id(), currentPosition)) } override fun startPlaying() { jobManager.addJobInBackground(StartPlaybackJob(video.id())) } override fun onVisibilityChange(visibility: Int) { if (visibility == View.GONE) { logger.debug("Controller View was hidden") onScreenControllerShowing = false } if (visibility == View.VISIBLE) { logger.debug("Controller View was shown") onScreenControllerShowing = true } } override fun isHudShowing(): Boolean = onScreenControllerShowing @Subscribe(threadMode = MAIN) fun onOnScreenDisplayEvent(event: OnScreenDisplayEvent) { if (event.isShowing) { viewState.hideController() } else { viewState.showController() } } override fun updateServerPlaybackPosition(currentPostion: Long) { video.resumeOffset = currentPostion.toInt() jobManager.addJobInBackground(UpdatePlaybackPostionJob(video)) } override fun playBackFromVideoQueue(autoResume: Boolean) { if (videoQueue.isEmpty()) { return } this.video = videoQueue.poll() if (!autoResume && video.isPartiallyWatched) { viewState.showResumeDialog(video) return } playVideo() } override fun playVideo() { val videoUrl: String = transcoderUrl() viewState.initializePlayer(videoUrl, video.resumeOffset) } internal fun isDirectPlaySupportedForContainer(video: VideoContentInfo): Boolean { val mediaCodecInfoUtil = MediaCodecInfoUtil() video.container?.let { video.container = if (video.container.contains("mp4")) { "mp4" } else { video.container } val isVideoContainerSupported = mediaCodecInfoUtil.isExoPlayerContainerSupported("video/${video.container.substringBefore(",")}") var isAudioCodecSupported = selectCodec(mediaCodecInfoUtil.findCorrectAudioMimeType("audio/${video.audioCodec}")) val isVideoSupported = selectCodec(mediaCodecInfoUtil.findCorrectVideoMimeType("video/${video.videoCodec}")) isAudioCodecSupported = if (androidHelper.isNvidiaShield || androidHelper.isBravia) { when (video.audioCodec.toLowerCase()) { "eac3", "ac3", "dts", "truehd" -> true else -> isAudioCodecSupported } } else { isAudioCodecSupported } logger.debug("Audio Codec: ${video.audioCodec} support returned $isAudioCodecSupported") logger.debug("Video Codec: ${video.videoCodec} support returned $isVideoSupported") logger.debug("Video Container: ${video.container} support returned $isVideoContainerSupported") if (isVideoSupported && isAudioCodecSupported && isVideoContainerSupported!!) { return true } } return false } private fun transcoderUrl(): String { logger.debug("ExoPlayerPresenter: Container: ${video.container} Audio: ${video.audioCodec}") if (isDirectPlaySupportedForContainer(video)) { logger.debug("ExoPlayerPresenter: Direct playing ${video.directPlayUrl}") return video.directPlayUrl } val transcodingUrl = serenityClient.createTranscodeUrl(video.id(), video.resumeOffset) logger.debug("ExoPlayerPresenter: Transcoding Url: $transcodingUrl") return transcodingUrl } private fun selectCodec(mimeType: String): Boolean = MediaCodecInfoUtil().isCodecSupported(mimeType) }
mit
b9bc52c6b05777375b1f8f5265eb0456
31.77451
105
0.759312
4.597662
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressDialog.kt
5
10554
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.progress.util import com.intellij.ide.ui.laf.darcula.ui.DarculaProgressBarUI import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.progress.impl.ProgressState import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.DialogWrapperPeer import com.intellij.openapi.ui.impl.GlassPaneDialogWrapperPeer import com.intellij.openapi.ui.impl.GlassPaneDialogWrapperPeer.GlasspanePeerUnavailableException import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.WindowManager import com.intellij.ui.PopupBorder import com.intellij.util.Alarm import com.intellij.util.SingleAlarm import com.intellij.util.ui.EdtInvocationManager import org.jetbrains.annotations.Nls import java.awt.Component import java.awt.Window import java.awt.event.ActionListener import java.awt.event.KeyEvent import javax.swing.* import javax.swing.border.Border class ProgressDialog(private val myProgressWindow: ProgressWindow, private val myShouldShowBackground: Boolean, cancelText: @Nls String?, private val myParentWindow: Window?) : Disposable { companion object { const val UPDATE_INTERVAL = 50 //msec. 20 frames per second. } private var myLastTimeDrawn: Long = -1 private val myUpdateAlarm = SingleAlarm(this::update, 500, this) private var myWasShown = false private val myStartMillis = System.currentTimeMillis() private val ui = ProgressDialogUI() private val myRepaintRunnable = Runnable { ui.updateTitle(myProgressWindow.title) ui.updateProgress(ProgressState( text = myProgressWindow.text, details = myProgressWindow.text2, fraction = if (myProgressWindow.isIndeterminate) -1.0 else myProgressWindow.fraction, )) val progressBar = ui.progressBar if (progressBar.isShowing && progressBar.isIndeterminate && isWriteActionProgress()) { val progressBarUI = progressBar.ui if (progressBarUI is DarculaProgressBarUI) { progressBarUI.updateIndeterminateAnimationIndex(myStartMillis) } } myLastTimeDrawn = System.currentTimeMillis() synchronized(this@ProgressDialog) { myRepaintedFlag = true } } private var myRepaintedFlag = true // guarded by this private var myPopup: DialogWrapper? = null private val myDisableCancelAlarm = SingleAlarm( this::setCancelButtonDisabledInEDT, 500, null, Alarm.ThreadToUse.SWING_THREAD, ModalityState.any() ) private val myEnableCancelAlarm = SingleAlarm( this::setCancelButtonEnabledInEDT, 500, null, Alarm.ThreadToUse.SWING_THREAD, ModalityState.any() ) init { ui.progressBar.isIndeterminate = myProgressWindow.isIndeterminate val cancelButton = ui.cancelButton if (cancelText != null) { cancelButton.text = cancelText } if (myProgressWindow.myShouldShowCancel) { cancelButton.addActionListener { myProgressWindow.cancel() } val cancelFunction = ActionListener { if (cancelButton.isEnabled) { myProgressWindow.cancel() } } cancelButton.registerKeyboardAction( cancelFunction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ) } else { cancelButton.isVisible = false } val backgroundButton = ui.backgroundButton if (myShouldShowBackground) { backgroundButton.addActionListener { myProgressWindow.background() } } else { backgroundButton.isVisible = false } } override fun dispose() { Disposer.dispose(ui) myEnableCancelAlarm.cancelAllRequests() myDisableCancelAlarm.cancelAllRequests() } val panel: JPanel get() = ui.panel fun getRepaintRunnable(): Runnable = myRepaintRunnable fun getPopup(): DialogWrapper? = myPopup fun cancel() { enableCancelButtonIfNeeded(false) } private fun setCancelButtonEnabledInEDT() { ui.cancelButton.isEnabled = true } private fun setCancelButtonDisabledInEDT() { ui.cancelButton.isEnabled = false } fun enableCancelButtonIfNeeded(enable: Boolean) { if (myProgressWindow.myShouldShowCancel && !myUpdateAlarm.isDisposed) { (if (enable) myEnableCancelAlarm else myDisableCancelAlarm).request() } } @Synchronized fun update() { if (myRepaintedFlag) { if (System.currentTimeMillis() > myLastTimeDrawn + UPDATE_INTERVAL) { myRepaintedFlag = false EdtInvocationManager.invokeLaterIfNeeded(myRepaintRunnable) } else { // later to avoid concurrent dispose/addRequest if (!myUpdateAlarm.isDisposed && myUpdateAlarm.isEmpty) { EdtInvocationManager.invokeLaterIfNeeded { if (!myUpdateAlarm.isDisposed) { myUpdateAlarm.request(myProgressWindow.modalityState) } } } } } } @Synchronized fun background() { if (myShouldShowBackground) { ui.backgroundButton.isEnabled = false } hide() } fun hide() { ApplicationManager.getApplication().invokeLater(this::hideImmediately, ModalityState.any()) } fun hideImmediately() { if (myPopup != null) { myPopup!!.close(DialogWrapper.CANCEL_EXIT_CODE) myPopup = null } } fun show() { if (myWasShown) { return } myWasShown = true if (ApplicationManager.getApplication().isHeadlessEnvironment || myParentWindow == null) { return } if (myPopup != null) { myPopup!!.close(DialogWrapper.CANCEL_EXIT_CODE) } val popup = createDialog(myParentWindow) myPopup = popup Disposer.register(popup.disposable) { myProgressWindow.exitModality() } popup.show() // 'Light' popup is shown in glass pane, glass pane is 'activating' (becomes visible) in 'invokeLater' call // (see IdeGlassPaneImp.addImpl), requesting focus to cancel button until that time has no effect, as it's not showing. SwingUtilities.invokeLater { if (myPopup != null && !myPopup!!.isDisposed) { val window = SwingUtilities.getWindowAncestor(ui.cancelButton) if (window != null) { val originalFocusOwner = window.mostRecentFocusOwner if (originalFocusOwner != null) { Disposer.register(myPopup!!.disposable) { originalFocusOwner.requestFocusInWindow() } } } ui.cancelButton.requestFocusInWindow() myRepaintRunnable.run() } } } private fun isWriteActionProgress(): Boolean { return myProgressWindow is PotemkinProgress } private fun createDialog(window: Window): DialogWrapper { if (Registry.`is`("ide.modal.progress.wrapper.refactoring")) { return createDialogWrapper( panel = panel, cancelAction = { if (myProgressWindow.myShouldShowCancel) { myProgressWindow.cancel() } }, window = window, writeAction = isWriteActionProgress(), project = myProgressWindow.myProject, ) } return createDialogPrevious(window).also { setupProgressDialog(it, isWriteActionProgress()) } } private fun createDialogPrevious(window: Window): MyDialogWrapper { if (System.getProperty("vintage.progress") != null || isWriteActionProgress()) { if (window.isShowing) { return object : MyDialogWrapper(window) { override fun useLightPopup(): Boolean { return false } } } return object : MyDialogWrapper(myProgressWindow.myProject) { override fun useLightPopup(): Boolean { return false } } } if (window.isShowing) { return MyDialogWrapper(window) } return MyDialogWrapper(myProgressWindow.myProject) } private open inner class MyDialogWrapper : DialogWrapper { constructor(project: Project?) : super(project, false) { init() } constructor(parent: Component) : super(parent, false) { init() } override fun doCancelAction() { if (myProgressWindow.myShouldShowCancel) { myProgressWindow.cancel() } } override fun createPeer(parent: Component, canBeParent: Boolean): DialogWrapperPeer { return if (useLightPopup()) { try { GlassPaneDialogWrapperPeer(this, parent) } catch (e: GlasspanePeerUnavailableException) { super.createPeer(parent, canBeParent) } } else { super.createPeer(parent, canBeParent) } } override fun createPeer(owner: Window, canBeParent: Boolean, applicationModalIfPossible: Boolean): DialogWrapperPeer { return if (useLightPopup()) { try { GlassPaneDialogWrapperPeer(this) } catch (e: GlasspanePeerUnavailableException) { super.createPeer(WindowManager.getInstance().suggestParentWindow(myProgressWindow.myProject), canBeParent, applicationModalIfPossible) } } else { super.createPeer(WindowManager.getInstance().suggestParentWindow(myProgressWindow.myProject), canBeParent, applicationModalIfPossible) } } protected open fun useLightPopup(): Boolean { return true } override fun createPeer(project: Project?, canBeParent: Boolean): DialogWrapperPeer { return if (System.getProperty("vintage.progress") == null) { try { GlassPaneDialogWrapperPeer(project, this) } catch (e: GlasspanePeerUnavailableException) { super.createPeer(project, canBeParent) } } else { super.createPeer(project, canBeParent) } } override fun init() { super.init() setUndecorated(true) rootPane.windowDecorationStyle = JRootPane.NONE panel.border = PopupBorder.Factory.create(true, true) } override fun isProgressDialog(): Boolean { return true } override fun createCenterPanel(): JComponent { return panel } override fun createSouthPanel(): JComponent? { return null } override fun createContentPaneBorder(): Border? { return null } } }
apache-2.0
652946cee5ba98df3a4f819ec3e01f7c
29.50578
123
0.681258
4.924872
false
false
false
false
jwren/intellij-community
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/gradle/statistics/KotlinGradleFUSLogger.kt
1
12124
// 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.gradle.statistics import com.intellij.ide.highlighter.ProjectFileType import com.intellij.ide.util.PropertiesComponent import com.intellij.internal.statistic.eventLog.EventLogConfiguration import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.io.FileUtil import com.intellij.util.PathUtilRt import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.text.trimMiddle import org.jetbrains.kotlin.idea.statistics.FUSEventGroups import org.jetbrains.kotlin.idea.statistics.GradleStatisticsEvents import org.jetbrains.kotlin.idea.statistics.KotlinFUSLogger import org.jetbrains.kotlin.statistics.BuildSessionLogger import org.jetbrains.kotlin.statistics.BuildSessionLogger.Companion.STATISTICS_FOLDER_NAME import org.jetbrains.kotlin.statistics.fileloggers.MetricsContainer import org.jetbrains.kotlin.statistics.metrics.BooleanMetrics import org.jetbrains.kotlin.statistics.metrics.NumericalMetrics import org.jetbrains.kotlin.statistics.metrics.StringMetrics import java.io.File import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import kotlin.io.path.Path import kotlin.io.path.exists class KotlinGradleFUSLogger : StartupActivity.DumbAware, Runnable { override fun runActivity(project: Project) { AppExecutorUtil.getAppScheduledExecutorService() .scheduleWithFixedDelay(this, EXECUTION_DELAY_MIN, EXECUTION_DELAY_MIN, TimeUnit.MINUTES) } override fun run() { reportStatistics() } companion object { private val IDE_STRING_ANONYMIZERS = lazy { mapOf( StringMetrics.PROJECT_PATH to { path: String -> // This code duplicated logics of StatisticsUtil.getProjectId, which could not be directly reused: // 1. the path of gradle project may not have corresponding project // 2. the projectId should be stable and independent on IDE version val presentableUrl = FileUtil.toSystemIndependentName(path) val name = PathUtilRt.getFileName(presentableUrl).toLowerCase(Locale.US).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION) val locationHash = Integer.toHexString((presentableUrl).hashCode()) val projectHash = "${name.trimMiddle(name.length.coerceAtMost(254 - locationHash.length), useEllipsisSymbol = false)}.$locationHash" EventLogConfiguration.getInstance().anonymize(projectHash) }) } private fun String.anonymizeIdeString(metric: StringMetrics) = if (metric.anonymization.anonymizeOnIdeSize()) IDE_STRING_ANONYMIZERS.value[metric]?.invoke(this) else this /** * Maximum amount of directories which were reported as gradle user dirs * These directories should be monitored for reported gradle statistics. */ const val MAXIMUM_USER_DIRS = 10 /** * Delay between sequential checks of gradle statistics */ const val EXECUTION_DELAY_MIN = 60L /** * Property name used for persisting gradle user dirs */ private const val GRADLE_USER_DIRS_PROPERTY_NAME = "kotlin-gradle-user-dirs" private val isRunning = AtomicBoolean(false) private fun MetricsContainer.log(event: GradleStatisticsEvents, vararg metrics: Any) { val data = HashMap<String, String>() fun putIfNotNull(key: String, value: String?) { if (value != null) { data[key.toLowerCase()] = value } } for (metric in metrics) { when (metric) { is BooleanMetrics -> putIfNotNull(metric.name, this.getMetric(metric)?.toStringRepresentation()) is StringMetrics -> putIfNotNull( metric.name, this.getMetric(metric)?.toStringRepresentation()?.anonymizeIdeString(metric) ) is NumericalMetrics -> putIfNotNull(metric.name, this.getMetric(metric)?.toStringRepresentation()) is Pair<*, *> -> putIfNotNull(metric.first.toString(), metric.second?.toString()) } } if (data.size > 0) { KotlinFUSLogger.log(FUSEventGroups.GradlePerformance, event.name, data) } } private fun processMetricsContainer(container: MetricsContainer, previous: MetricsContainer?) { container.log( GradleStatisticsEvents.Environment, NumericalMetrics.CPU_NUMBER_OF_CORES, StringMetrics.GRADLE_VERSION, NumericalMetrics.ARTIFACTS_DOWNLOAD_SPEED, StringMetrics.IDES_INSTALLED, BooleanMetrics.EXECUTED_FROM_IDEA, StringMetrics.PROJECT_PATH ) container.log( GradleStatisticsEvents.Kapt, BooleanMetrics.ENABLED_KAPT, BooleanMetrics.ENABLED_DAGGER, BooleanMetrics.ENABLED_DATABINDING ) container.log( GradleStatisticsEvents.CompilerPlugins, BooleanMetrics.ENABLED_COMPILER_PLUGIN_ALL_OPEN, BooleanMetrics.ENABLED_COMPILER_PLUGIN_NO_ARG, BooleanMetrics.ENABLED_COMPILER_PLUGIN_JPA_SUPPORT, BooleanMetrics.ENABLED_COMPILER_PLUGIN_SAM_WITH_RECEIVER, BooleanMetrics.JVM_COMPILER_IR_MODE, StringMetrics.JVM_DEFAULTS, StringMetrics.USE_OLD_BACKEND ) container.log( GradleStatisticsEvents.JS, BooleanMetrics.JS_GENERATE_EXTERNALS, StringMetrics.JS_GENERATE_EXECUTABLE_DEFAULT, StringMetrics.JS_TARGET_MODE, BooleanMetrics.JS_SOURCE_MAP, StringMetrics.JS_PROPERTY_LAZY_INITIALIZATION, StringMetrics.JS_OUTPUT_GRANULARITY, BooleanMetrics.JS_KLIB_INCREMENTAL, BooleanMetrics.JS_IR_INCREMENTAL, ) container.log( GradleStatisticsEvents.MPP, StringMetrics.MPP_PLATFORMS, BooleanMetrics.ENABLED_HMPP, StringMetrics.JS_COMPILER_MODE ) container.log( GradleStatisticsEvents.Libraries, StringMetrics.LIBRARY_SPRING_VERSION, StringMetrics.LIBRARY_VAADIN_VERSION, StringMetrics.LIBRARY_GWT_VERSION, StringMetrics.LIBRARY_HIBERNATE_VERSION ) container.log( GradleStatisticsEvents.GradleConfiguration, NumericalMetrics.GRADLE_DAEMON_HEAP_SIZE, NumericalMetrics.GRADLE_BUILD_NUMBER_IN_CURRENT_DAEMON, NumericalMetrics.CONFIGURATION_API_COUNT, NumericalMetrics.CONFIGURATION_IMPLEMENTATION_COUNT, NumericalMetrics.CONFIGURATION_COMPILE_COUNT, NumericalMetrics.CONFIGURATION_RUNTIME_COUNT, NumericalMetrics.GRADLE_NUMBER_OF_TASKS, NumericalMetrics.GRADLE_NUMBER_OF_UNCONFIGURED_TASKS, NumericalMetrics.GRADLE_NUMBER_OF_INCREMENTAL_TASKS ) container.log( GradleStatisticsEvents.ComponentVersions, StringMetrics.KOTLIN_COMPILER_VERSION, StringMetrics.KOTLIN_STDLIB_VERSION, StringMetrics.KOTLIN_REFLECT_VERSION, StringMetrics.KOTLIN_COROUTINES_VERSION, StringMetrics.KOTLIN_SERIALIZATION_VERSION, StringMetrics.ANDROID_GRADLE_PLUGIN_VERSION ) container.log( GradleStatisticsEvents.KotlinFeatures, StringMetrics.KOTLIN_LANGUAGE_VERSION, StringMetrics.KOTLIN_API_VERSION, BooleanMetrics.BUILD_SRC_EXISTS, NumericalMetrics.BUILD_SRC_COUNT, BooleanMetrics.GRADLE_BUILD_CACHE_USED, BooleanMetrics.GRADLE_WORKER_API_USED, BooleanMetrics.KOTLIN_OFFICIAL_CODESTYLE, BooleanMetrics.KOTLIN_PROGRESSIVE_MODE, BooleanMetrics.KOTLIN_KTS_USED ) container.log( GradleStatisticsEvents.GradlePerformance, NumericalMetrics.GRADLE_BUILD_DURATION, NumericalMetrics.GRADLE_EXECUTION_DURATION, NumericalMetrics.NUMBER_OF_SUBPROJECTS, NumericalMetrics.STATISTICS_VISIT_ALL_PROJECTS_OVERHEAD, NumericalMetrics.STATISTICS_COLLECT_METRICS_OVERHEAD ) val finishTime = container.getMetric(NumericalMetrics.BUILD_FINISH_TIME)?.getValue() val prevFinishTime = previous?.getMetric(NumericalMetrics.BUILD_FINISH_TIME)?.getValue() val betweenBuilds = if (finishTime != null && prevFinishTime != null) finishTime - prevFinishTime else null container.log( GradleStatisticsEvents.UseScenarios, Pair("time_between_builds", betweenBuilds), BooleanMetrics.DEBUGGER_ENABLED, BooleanMetrics.COMPILATION_STARTED, BooleanMetrics.TESTS_EXECUTED, BooleanMetrics.MAVEN_PUBLISH_EXECUTED, BooleanMetrics.BUILD_FAILED ) } fun reportStatistics() { if (isRunning.compareAndSet(false, true)) { try { for (gradleUserHome in gradleUserDirs) { BuildSessionLogger.listProfileFiles(File(gradleUserHome, STATISTICS_FOLDER_NAME))?.forEach { statisticFile -> var fileWasRead = true try { var previousEvent: MetricsContainer? = null fileWasRead = MetricsContainer.readFromFile(statisticFile) { metricContainer -> processMetricsContainer(metricContainer, previousEvent) previousEvent = metricContainer } } catch (e: Exception) { Logger.getInstance(KotlinFUSLogger::class.java) .info("Failed to process file ${statisticFile.absolutePath}: ${e.message}", e) } finally { if (fileWasRead && !statisticFile.delete()) { Logger.getInstance(KotlinFUSLogger::class.java) .warn("[FUS] Failed to delete file ${statisticFile.absolutePath}") } } } } } finally { isRunning.set(false) } } } private var gradleUserDirs: List<String> set(value) = PropertiesComponent.getInstance().setList( GRADLE_USER_DIRS_PROPERTY_NAME, value ) get() = PropertiesComponent.getInstance().getList(GRADLE_USER_DIRS_PROPERTY_NAME) ?: emptyList() fun populateGradleUserDir(path: String) { val currentState = gradleUserDirs if (path in currentState) return val result = ArrayList<String>() result.add(path) result.addAll(currentState) gradleUserDirs = result.filter { filePath -> Path(filePath).exists() }.take(MAXIMUM_USER_DIRS) } } }
apache-2.0
83095fb2e324e9033aa852daab174a7e
44.238806
138
0.604503
5.673374
false
false
false
false
androidx/androidx
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/LayerMatrixCache.android.kt
3
3402
/* * 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.ui.platform import android.graphics.Matrix as AndroidMatrix import androidx.compose.ui.graphics.Matrix import androidx.compose.ui.graphics.setFrom /** * Helper class to cache a [Matrix] and inverse [Matrix], allowing the instance to be reused until * the Layer's properties have changed, causing it to call [invalidate]. * * This allows us to avoid repeated calls to [AndroidMatrix.getValues], which calls * an expensive native method (nGetValues). If we know the matrix hasn't changed, we can just * re-use it without needing to read and update values. */ internal class LayerMatrixCache<T>( private val getMatrix: (target: T, matrix: AndroidMatrix) -> Unit ) { private var androidMatrixCache: AndroidMatrix? = null private var previousAndroidMatrix: AndroidMatrix? = null private var matrixCache: Matrix? = null private var inverseMatrixCache: Matrix? = null private var isDirty = true private var isInverseDirty = true private var isInverseValid = true /** * Ensures that the internal matrix will be updated next time [calculateMatrix] or * [calculateInverseMatrix] is called - this should be called when something that will * change the matrix calculation has happened. */ fun invalidate() { isDirty = true isInverseDirty = true } /** * Returns the cached [Matrix], updating it if required (if [invalidate] was previously called). */ fun calculateMatrix(target: T): Matrix { val matrix = matrixCache ?: Matrix().also { matrixCache = it } if (!isDirty) { return matrix } val cachedMatrix = androidMatrixCache ?: AndroidMatrix().also { androidMatrixCache = it } getMatrix(target, cachedMatrix) val prevMatrix = previousAndroidMatrix if (prevMatrix == null || cachedMatrix != prevMatrix) { matrix.setFrom(cachedMatrix) androidMatrixCache = prevMatrix previousAndroidMatrix = cachedMatrix } isDirty = false return matrix } /** * Returns the cached inverse [Matrix], updating it if required (if [invalidate] was previously * called). This returns `null` if the inverse matrix isn't valid. This can happen, for example, * when scaling is 0. */ fun calculateInverseMatrix(target: T): Matrix? { val matrix = inverseMatrixCache ?: Matrix().also { inverseMatrixCache = it } if (isInverseDirty) { val normalMatrix = calculateMatrix(target) isInverseValid = normalMatrix.invertTo(matrix) isInverseDirty = false } return if (isInverseValid) matrix else null } }
apache-2.0
619d1ec25babc36a3c33a75299c39d84
34.072165
100
0.674309
4.692414
false
false
false
false
taigua/exercism
kotlin/gigasecond/src/test/kotlin/GigasecondTest.kt
1
1265
import org.junit.Test import java.time.LocalDate import java.time.LocalDateTime import java.time.Month import kotlin.test.assertEquals class GigasecondTest { @Test fun modernTime() { val gigaSecond = Gigasecond(LocalDate.of(2011, Month.APRIL, 25)) assertEquals(LocalDateTime.of(2043, Month.JANUARY, 1, 1, 46, 40), gigaSecond.date) } @Test fun afterEpochTime() { val gigaSecond = Gigasecond(LocalDate.of(1977, Month.JUNE, 13)) assertEquals(LocalDateTime.of(2009, Month.FEBRUARY, 19, 1, 46, 40), gigaSecond.date) } @Test fun beforeEpochTime() { val gigaSecond = Gigasecond(LocalDate.of(1959, Month.JULY, 19)) assertEquals(LocalDateTime.of(1991, Month.MARCH, 27, 1, 46, 40), gigaSecond.date) } @Test fun withFullTimeSpecified() { val gigaSecond = Gigasecond(LocalDateTime.of(2015, Month.JANUARY, 24, 22, 0, 0)) assertEquals(LocalDateTime.of(2046, Month.OCTOBER, 2, 23, 46, 40), gigaSecond.date) } @Test fun withFullTimeSpecifiedAndDayRollover() { val gigaSecond = Gigasecond(LocalDateTime.of(2015, Month.JANUARY, 24, 23, 59, 59)) assertEquals(LocalDateTime.of(2046, Month.OCTOBER, 3, 1, 46, 39), gigaSecond.date) } }
mit
1753ee5b116bef11330258f4fe16f00c
28.418605
92
0.672727
3.709677
false
true
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/overrideImplement/FakeOverrideToStringInTrait.kt
5
522
interface <lineMarker descr="Is implemented by B C Click or press ... to navigate">A</lineMarker> { override fun <lineMarker descr="<html><body>Is overridden in <br>&nbsp;&nbsp;&nbsp;&nbsp;C</body></html>"><lineMarker descr="Overrides function in 'Any'">toString</lineMarker></lineMarker>() = "A" } abstract class <lineMarker descr="Is subclassed by C Click or press ... to navigate">B</lineMarker> : A class C : B() { override fun <lineMarker descr="Overrides function in 'A'">toString</lineMarker>() = "B" }
apache-2.0
ee425da0011613fc4da186d7baf823fd
57
200
0.697318
3.895522
false
false
false
false
GunoH/intellij-community
java/java-tests/testSrc/com/intellij/java/psi/formatter/java/JavaFormatterTest.kt
7
151500
// 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.java.psi.formatter.java import com.intellij.application.options.CodeStyle import com.intellij.ide.highlighter.JavaFileType import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.roots.LanguageLevelProjectExtension import com.intellij.openapi.util.TextRange import com.intellij.pom.java.LanguageLevel import com.intellij.psi.JavaCodeFragmentFactory import com.intellij.psi.PsiElement import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.codeStyle.CommonCodeStyleSettings import com.intellij.util.IncorrectOperationException /** * **Note:** this class is too huge and hard to use. It's tests are intended to be split in multiple more fine-grained * java formatting test classes. */ class JavaFormatterTest : AbstractJavaFormatterTest() { fun testPaymentManager() { settings.KEEP_LINE_BREAKS = false doTest("paymentManager.java", "paymentManager_after.java") } fun testForEach() { doTest("ForEach.java", "ForEach_after.java") } fun testDoubleCast() { doTest("DoubleCast.java", "DoubleCast_after.java") } fun test1() { myTextRange = TextRange(35, 46) doTest("1.java", "1_after.java") } fun testLabel1() { indentOptions.LABEL_INDENT_SIZE = 0 indentOptions.LABEL_INDENT_ABSOLUTE = true doTest("Label.java", "Label_after1.java") } fun testTryCatch() { myTextRange = TextRange(38, 72) doTest("TryCatch.java", "TryCatch_after.java") } fun testNullMethodParameter() { settings.CALL_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_ALWAYS settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true doTest("NullMethodParameter.java", "NullMethodParameter_after.java") } fun test_DoNot_JoinLines_If_KeepLineBreaksIsOn() { settings.KEEP_LINE_BREAKS = true settings.METHOD_ANNOTATION_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP doTextTest( "public class Test<Param> {\n" + " @SuppressWarnings(\"unchecked\")\n" + " void executeParallel(Param... params) {\n" + " }\n" + "}", "public class Test<Param> {\n" + " @SuppressWarnings(\"unchecked\")\n" + " void executeParallel(Param... params) {\n" + " }\n" + "}" ) } fun test_DoNot_JoinLines_If_KeepLineBreaksIsOn_WithMultipleAnnotations() { settings.KEEP_LINE_BREAKS = true settings.METHOD_ANNOTATION_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP doTextTest( "public class Test<Param> {\n" + " @Override @SuppressWarnings(\"unchecked\")\n" + " void executeParallel(Param... params) {\n" + " }\n" + "}", "public class Test<Param> {\n" + " @Override @SuppressWarnings(\"unchecked\")\n" + " void executeParallel(Param... params) {\n" + " }\n" + "}" ) } fun test_format_only_selected_range() { myTextRange = TextRange(18, 19) doTextTest( "public class X {\n" + " public int a = 2;\n" + "}", "public class X {\n" + " public int a = 2;\n" + "}" ) } fun testNew() { indentOptions.CONTINUATION_INDENT_SIZE = 8 doTest("New.java", "New_after.java") } fun testJavaDoc() { settings.BLANK_LINES_AROUND_FIELD = 1 doTest("JavaDoc.java", "JavaDoc_after.java") } fun testBreakInsideIf() { doTest("BreakInsideIf.java", "BreakInsideIf_after.java") } fun testAssert() { LanguageLevelProjectExtension.getInstance(project).languageLevel = LanguageLevel.HIGHEST doTest() } fun testCastInsideElse() { indentOptions.CONTINUATION_INDENT_SIZE = 2 indentOptions.INDENT_SIZE = 2 indentOptions.LABEL_INDENT_SIZE = 0 indentOptions.TAB_SIZE = 8 settings.SPACE_WITHIN_CAST_PARENTHESES = false settings.SPACE_AFTER_TYPE_CAST = true settings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION = true doTest() } fun testAlignMultiLine() { settings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION = true settings.ALIGN_MULTILINE_BINARY_OPERATION = true doTest() } fun testInnerClassAsParameter() { doTest() } fun testSynchronizedBlock() { settings.apply { SPACE_BEFORE_SYNCHRONIZED_PARENTHESES = false SPACE_WITHIN_SYNCHRONIZED_PARENTHESES = false SPACE_BEFORE_SYNCHRONIZED_LBRACE = false } doTest() } fun testMethodCallInAssignment() { val settings = settings settings.rootSettings.getIndentOptions(JavaFileType.INSTANCE).CONTINUATION_INDENT_SIZE = 8 doTest() } fun testAnonymousInnerClasses() { doTest() } fun testAnonymousInner2() { doTest() } fun testWrapAssertion() { doTest() } fun testIfElse() { settings.apply { IF_BRACE_FORCE = CommonCodeStyleSettings.DO_NOT_FORCE FOR_BRACE_FORCE = CommonCodeStyleSettings.FORCE_BRACES_IF_MULTILINE WHILE_BRACE_FORCE = CommonCodeStyleSettings.FORCE_BRACES_IF_MULTILINE DOWHILE_BRACE_FORCE = CommonCodeStyleSettings.FORCE_BRACES_IF_MULTILINE ELSE_ON_NEW_LINE = true SPECIAL_ELSE_IF_TREATMENT = false WHILE_ON_NEW_LINE = true CATCH_ON_NEW_LINE = true FINALLY_ON_NEW_LINE = true ALIGN_MULTILINE_BINARY_OPERATION = true ALIGN_MULTILINE_TERNARY_OPERATION = true ALIGN_MULTILINE_ASSIGNMENT = true ALIGN_MULTILINE_EXTENDS_LIST = true ALIGN_MULTILINE_THROWS_LIST = true ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION = true ALIGN_MULTILINE_FOR = true ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true ALIGN_MULTILINE_PARAMETERS = true KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = true WHILE_ON_NEW_LINE = true BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE SPACE_WITHIN_BRACES = true } doTest() } fun testIfBraces() { settings.apply { IF_BRACE_FORCE = CommonCodeStyleSettings.FORCE_BRACES_ALWAYS BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE KEEP_LINE_BREAKS = false } doTest() } fun testTernaryExpression() { settings.ALIGN_MULTILINE_TERNARY_OPERATION = true doTest() settings.ALIGN_MULTILINE_TERNARY_OPERATION = false doTest("TernaryExpression.java", "TernaryExpression_DoNotAlign_after.java") } fun testAlignAssignment() { settings.apply { ALIGN_MULTILINE_ASSIGNMENT = true ALIGN_MULTILINE_BINARY_OPERATION = true } doTest() } fun testAlignFor() { settings.apply { ALIGN_MULTILINE_BINARY_OPERATION = true ALIGN_MULTILINE_FOR = true } doTest() } fun testSwitch() { doTest() } fun testContinue() { doTest() } fun testIf() { settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE doTest() settings.BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE doTest("If.java", "If.java") settings.BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE settings.KEEP_LINE_BREAKS = false doTest("If_after.java", "If.java") } fun test2() { settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true doTest() } fun testBlocks() { settings.KEEP_LINE_BREAKS = false doTest() } @Throws(IncorrectOperationException::class) fun testBinaryOperation() { val text = "class Foo {\n" + " void foo () {\n" + " xxx = aaa + bbb \n" + " + ccc + eee + ddd;\n" + " }\n" + "}" settings.apply { ALIGN_MULTILINE_BINARY_OPERATION = true ALIGN_MULTILINE_ASSIGNMENT = true } doTextTest(text, "class Foo {\n" + " void foo() {\n" + " xxx = aaa + bbb\n" + " + ccc + eee + ddd;\n" + " }\n" + "}") settings.apply { ALIGN_MULTILINE_BINARY_OPERATION = true ALIGN_MULTILINE_ASSIGNMENT = false } doTextTest(text, "class Foo {\n" + " void foo() {\n" + " xxx = aaa + bbb\n" + " + ccc + eee + ddd;\n" + " }\n" + "}") settings.apply { ALIGN_MULTILINE_BINARY_OPERATION = false ALIGN_MULTILINE_ASSIGNMENT = true } doTextTest(text, "class Foo {\n" + " void foo() {\n" + " xxx = aaa + bbb\n" + " + ccc + eee + ddd;\n" + " }\n" + "}") settings.apply { ALIGN_MULTILINE_ASSIGNMENT = false ALIGN_MULTILINE_BINARY_OPERATION = false } doTextTest(text, "class Foo {\n" + " void foo() {\n" + " xxx = aaa + bbb\n" + " + ccc + eee + ddd;\n" + " }\n" + "}") doTextTest(text, "class Foo {\n" + " void foo() {\n" + " xxx = aaa + bbb\n" + " + ccc + eee + ddd;\n" + " }\n" + "}") settings.ALIGN_MULTILINE_BINARY_OPERATION = true doTextTest("class Foo {\n" + " void foo () {\n" + " xxx = aaa + bbb \n" + " - ccc + eee + ddd;\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " xxx = aaa + bbb\n" + " - ccc + eee + ddd;\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo () {\n" + " xxx = aaa + bbb \n" + " * ccc + eee + ddd;\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " xxx = aaa + bbb\n" + " * ccc + eee + ddd;\n" + " }\n" + "}") } fun testWhile() { doTextTest("class A{\n" + "void a(){\n" + "do x++ while (b);\n" + "}\n}", "class A {\n" + " void a() {\n" + " do x++ while (b);\n" + " }\n" + "}") } fun testFor() { doTextTest("class A{\n" + "void b(){\n" + "for (c) {\n" + "d();\n" + "}\n" + "}\n" + "}", "class A {\n" + " void b() {\n" + " for (c) {\n" + " d();\n" + " }\n" + " }\n" + "}") } fun testClassComment() { val before = "/**\n" + "* @author smbd\n" + "* @param <T> some param\n" + "* @since 1.9\n" + "*/\n" + "class Test<T>{}" val after = "/**\n" + " * @param <T> some param\n" + " * @author smbd\n" + " * @since 1.9\n" + " */\n" + "class Test<T> {\n" + "}" doTextTest(before, after) } fun testStringBinaryOperation() { settings.apply { ALIGN_MULTILINE_ASSIGNMENT = false ALIGN_MULTILINE_BINARY_OPERATION = false } doTextTest("class Foo {\n" + " void foo () {\n" + "String s = \"abc\" +\n" + "\"def\";" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " String s = \"abc\" +\n" + " \"def\";\n" + " }\n" + "}") } fun test3() { doTest() } fun test4() { myLineRange = TextRange(2, 8) doTest() } fun testBraces() { val text = "class Foo {\n" + "void foo () {\n" + "if (a) {\n" + "int i = 0;\n" + "}\n" + "}\n" + "}" settings.apply { BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE METHOD_BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE } doTextTest(text, "class Foo {\n" + " void foo() {\n" + " if (a) {\n" + " int i = 0;\n" + " }\n" + " }\n" + "}") settings.apply { BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE METHOD_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE } doTextTest(text, "class Foo {\n" + " void foo()\n" + " {\n" + " if (a)\n" + " {\n" + " int i = 0;\n" + " }\n" + " }\n" + "}") settings.apply { BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED METHOD_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED } doTextTest(text, "class Foo {\n" + " void foo()\n" + " {\n" + " if (a)\n" + " {\n" + " int i = 0;\n" + " }\n" + " }\n" + "}") settings.apply { METHOD_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE } doTextTest(text, "class Foo {\n" + " void foo()\n" + " {\n" + " if (a) {\n" + " int i = 0;\n" + " }\n" + " }\n" + "}") settings.apply { METHOD_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED2 BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED2 } doTextTest(text, "class Foo {\n" + " void foo()\n" + " {\n" + " if (a)\n" + " {\n" + " int i = 0;\n" + " }\n" + " }\n" + "}") settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE doTextTest("class Foo {\n" + " static{\n" + "foo();\n" + "}" + "}", "class Foo {\n" + " static\n" + " {\n" + " foo();\n" + " }\n" + "}") } fun testExtendsList() { settings.ALIGN_MULTILINE_EXTENDS_LIST = true doTextTest("class A extends B, \n" + "C {}", "class A extends B,\n" + " C {\n}") } fun testBlockWithoutBraces() { doTextTest("class A {\n" + "void foo(){\n" + "if(a)\n" + "return;\n" + "}\n" + "}", "class A {\n" + " void foo() {\n" + " if (a)\n" + " return;\n" + " }\n" + "}") } fun testNestedCalls() { doTextTest("class A {\n" + "void foo(){\n" + "foo(\nfoo(\nfoo()\n)\n);\n" + "}\n" + "}", "class A {\n" + " void foo() {\n" + " foo(\n" + " foo(\n" + " foo()\n" + " )\n" + " );\n" + " }\n" + "}") } fun testSpacesAroundMethod() { doTextTest("class Foo {\n" + " abstract void a();\n" + " {\n" + " a();\n" + " }\n" + "}", "class Foo {\n" + " abstract void a();\n" + "\n" + " {\n" + " a();\n" + " }\n" + "}") } fun testSpaceInIf() { doTextTest("class foo {\n" + " {\n" + " if (a) {\n" + " if(a) {\n" + "\n" + " }\n" + " }\n" + " }\n" + "}", "class foo {\n" + " {\n" + " if (a) {\n" + " if (a) {\n" + "\n" + " }\n" + " }\n" + " }\n" + "}") } fun testIf2() { doTextTest( "public class Test {\n" + " public boolean equals(Object o) {\n" + " if(this == o)return true;\n" + " }\n" + "}", "public class Test {\n" + " public boolean equals(Object o) {\n" + " if (this == o) return true;\n" + " }\n" + "}") } fun testSpaceAroundField() { settings.BLANK_LINES_AROUND_FIELD = 1 doTextTest("class Foo {\n" + " boolean a;\n" + " {\n" + " if (a) {\n" + " } else {\n" + "\n" + " }\n" + " a = 2;\n" + " }\n" + "}", "class Foo {\n" + " boolean a;\n" + "\n" + " {\n" + " if (a) {\n" + " } else {\n" + "\n" + " }\n" + " a = 2;\n" + " }\n" + "}") } fun testArray() { settings.apply { SPACE_WITHIN_ARRAY_INITIALIZER_BRACES = true SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE = true } doTextTest("class a {\n" + " void f() {\n" + " final int[] i = new int[]{0};\n" + " }\n" + "}", "class a {\n" + " void f() {\n" + " final int[] i = new int[] { 0 };\n" + " }\n" + "}") } fun testEmptyArray() { settings.apply { SPACE_WITHIN_ARRAY_INITIALIZER_BRACES = true SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE = true SPACE_WITHIN_EMPTY_ARRAY_INITIALIZER_BRACES = false } doTextTest("class a {\n" + " void f() {\n" + " final int[] i = new int[]{ };\n" + " }\n" + "}", "class a {\n" + " void f() {\n" + " final int[] i = new int[] {};\n" + " }\n" + "}") } fun testEmptyArrayIsntWrapped() { settings.apply { ARRAY_INITIALIZER_LBRACE_ON_NEXT_LINE = true ARRAY_INITIALIZER_RBRACE_ON_NEXT_LINE = true SPACE_WITHIN_EMPTY_ARRAY_INITIALIZER_BRACES = true } doTextTest("class a {\n" + " void f() {\n" + " final int[] i = new int[]{ };\n" + " }\n" + "}", "class a {\n" + " void f() {\n" + " final int[] i = new int[]{ };\n" + " }\n" + "}") } fun testTwoJavaDocs() { doTextTest("""/** * */ class Test { /** */ public void foo(); }""", """/** * */ class Test { /** * */ public void foo(); }""") } fun testJavaDocLinksWithParameterNames() { // See IDEADEV-8332 doTextTest("/**\n" + "* @return if ( x1 == x1 ) then return {@link #cmp(String y1,int y2)}\n" + "* otherwise return {@link #cmp(int x1,int x2)}\n" + "*/\n" + "class X {\n" + "}\n", "/**\n" + " * @return if ( x1 == x1 ) then return {@link #cmp(String y1, int y2)}\n" + " * otherwise return {@link #cmp(int x1, int x2)}\n" + " */\n" + "class X {\n" + "}\n") } fun testIncompleteField() { doTextTest("public class Test {\n" + " String s =;\n" + "}", "public class Test {\n" + " String s = ;\n" + "}") } fun testIf3() { settings.KEEP_CONTROL_STATEMENT_IN_ONE_LINE = false doTextTest("public abstract class A {\n" + " abstract void f(boolean b);\n" + "\n" + " A IMPL = new A() {\n" + " void f(boolean b) {\n" + " if (b)\n" + " f(true); else {\n" + " f(false);\n" + " f(false);\n" + " }\n" + " for (int i = 0; i < 5; i++) f(true);\n" + " }\n" + " };\n" + "}", "public abstract class A {\n" + " abstract void f(boolean b);\n" + "\n" + " A IMPL = new A() {\n" + " void f(boolean b) {\n" + " if (b)\n" + " f(true);\n" + " else {\n" + " f(false);\n" + " f(false);\n" + " }\n" + " for (int i = 0; i < 5; i++)\n" + " f(true);\n" + " }\n" + " };\n" + "}") } fun testDocComment() { doTextTest("public class TestClass {\n" + "/**\n" + "* \n" + "*/\n" + " public void f1() {\n" + " }\n" + "}", "public class TestClass {\n" + " /**\n" + " *\n" + " */\n" + " public void f1() {\n" + " }\n" + "}") } fun testDocComment2() { settings.KEEP_SIMPLE_METHODS_IN_ONE_LINE = true doTextTest("class Test {\n" + "/**\n" + "*\n" + "* @param a\n" + "* @param param\n" + "* @param ddd\n" + "*/\n" + " public void foo(int a, String param, double ddd) {}\n" + "}", "class Test {\n" + " /**\n" + " * @param a\n" + " * @param param\n" + " * @param ddd\n" + " */\n" + " public void foo(int a, String param, double ddd) {}\n" + "}") } fun testSpaceBeforeFieldName() { doTextTest("class A{\n" + "public A myA ;\n" + "}", "class A {\n" + " public A myA;\n" + "}") } fun testClass() { doTextTest(" class A {\n" + " Logger LOG;\n" + " class C {}\n" + "\n" + " public void b() {\n" + " }\n" + "\n" + " int f;\n" + " }", "class A {\n" + " Logger LOG;\n" + "\n" + " class C {\n" + " }\n" + "\n" + " public void b() {\n" + " }\n" + "\n" + " int f;\n" + "}") } fun testDoNotIndentCaseFromSwitch() { settings.INDENT_CASE_FROM_SWITCH = false doTextTest("class A {\n" + "void foo() {\n" + "switch(a){\n" + "case 1: \n" + "break;\n" + "}\n" + "}\n" + "}", "class A {\n" + " void foo() {\n" + " switch (a) {\n" + " case 1:\n" + " break;\n" + " }\n" + " }\n" + "}") } fun testClass2() { settings.KEEP_FIRST_COLUMN_COMMENT = false doTextTest("class A {\n" + "// comment before\n" + "protected Object a;// comment after\n" + "}", "class A {\n" + " // comment before\n" + " protected Object a;// comment after\n" + "}") } fun testSplitLiteral() { doTextTest("class A {\n" + "void foo() {\n" + " String s = \"abc\" +\n" + " \"def\";\n" + "}\n" + "}", "class A {\n" + " void foo() {\n" + " String s = \"abc\" +\n" + " \"def\";\n" + " }\n" + "}") } fun testParametersAlignment() { settings.apply { ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true RIGHT_MARGIN = 140 } doTest() } fun testConditionalExpression() { settings.apply { SPACE_BEFORE_QUEST = true SPACE_AFTER_QUEST = false SPACE_BEFORE_COLON = true SPACE_AFTER_COLON = false } doTextTest("class Foo{\n" + " void foo(){\n" + " return name != null ? 1 : 2 ;" + "}\n" + "}", "class Foo {\n" + " void foo() {\n" + " return name != null ?1 :2;\n" + " }\n" + "}") } fun testMethodCallChain() { doTextTest("class Foo{\n" + " void foo(){\n" + " configuration = new Configuration() \n" + " .setProperty(\"hibernate.dialect\", \n" + " \"au.com.sensis.wsearch.db.CustomHSQLDBDialect\");\n" + "}\n" + "}", "class Foo {\n" + " void foo() {\n" + " configuration = new Configuration()\n" + " .setProperty(\"hibernate.dialect\",\n" + " \"au.com.sensis.wsearch.db.CustomHSQLDBDialect\");\n" + " }\n" + "}") doTextTest("class Foo{\n" + " void foo(){\n" + " configuration = new Configuration(). \n" + " setProperty(\"hibernate.dialect\", \n" + " \"au.com.sensis.wsearch.db.CustomHSQLDBDialect\");\n" + "}\n" + "}", "class Foo {\n" + " void foo() {\n" + " configuration = new Configuration().\n" + " setProperty(\"hibernate.dialect\",\n" + " \"au.com.sensis.wsearch.db.CustomHSQLDBDialect\");\n" + " }\n" + "}") doTextTest("class Foo{\n" + " void foo(){\n" + " configuration = new Configuration() \n" + " .setProperty(\"hibernate.dialect\", \n" + " \"au.com.sensis.wsearch.db.CustomHSQLDBDialect\") \n" + " .setProperty(\"hibernate.connection.url\", \n" + " \"jdbc:hsqldb:mem:testdb\") \n" + " .setProperty(\"hibernate.connection.driver_class\", \n" + " \"org.hsqldb.jdbcDriver\") \n" + " .setProperty(\"hibernate.connection.username\", \"sa\") \n" + " .setProperty(\"hibernate.connection.password\", \"\") \n" + " .setProperty(\"hibernate.show_sql\", \"false\") \n" + " .setProperty(\"hibernate.order_updates\", \"true\") \n" + " .setProperty(\"hibernate.hbm2ddl.auto\", \"update\"); " + "}\n" + "}", "class Foo {\n" + " void foo() {\n" + " configuration = new Configuration()\n" + " .setProperty(\"hibernate.dialect\",\n" + " \"au.com.sensis.wsearch.db.CustomHSQLDBDialect\")\n" + " .setProperty(\"hibernate.connection.url\",\n" + " \"jdbc:hsqldb:mem:testdb\")\n" + " .setProperty(\"hibernate.connection.driver_class\",\n" + " \"org.hsqldb.jdbcDriver\")\n" + " .setProperty(\"hibernate.connection.username\", \"sa\")\n" + " .setProperty(\"hibernate.connection.password\", \"\")\n" + " .setProperty(\"hibernate.show_sql\", \"false\")\n" + " .setProperty(\"hibernate.order_updates\", \"true\")\n" + " .setProperty(\"hibernate.hbm2ddl.auto\", \"update\");\n" + " }\n" + "}") } fun testComment1() { doTextTest( "class Foo {\n" + " public boolean mErrorFlage;\n" + "\n" + " /**\n" + " * Reference to New Member Message Source\n" + " */\n" + " private NewMemberMessageSource newMemberMessageSource;" + "\n" + "}", "class Foo {\n" + " public boolean mErrorFlage;\n" + "\n" + " /**\n" + " * Reference to New Member Message Source\n" + " */\n" + " private NewMemberMessageSource newMemberMessageSource;" + "\n" + "}") } fun testElseAfterComment() { doTextTest("public class Foo {\n" + " public int foo() {\n" + " if (a) {\n" + " return;\n" + " }//comment\n" + " else {\n" + " }\n" + " }\n" + "}", "public class Foo {\n" + " public int foo() {\n" + " if (a) {\n" + " return;\n" + " }//comment\n" + " else {\n" + " }\n" + " }\n" + "}") } fun testLBraceAfterComment() { settings.KEEP_LINE_BREAKS = false doTextTest("public class Foo {\n" + " public int foo() {\n" + " if (a) \n" + " //comment\n" + "{\n" + " return;\n" + " }\n" + " }\n" + "}", "public class Foo {\n" + " public int foo() {\n" + " if (a)\n" + " //comment\n" + " {\n" + " return;\n" + " }\n" + " }\n" + "}") } fun testSpaces() { val settings = settings settings.SPACE_WITHIN_FOR_PARENTHESES = true settings.SPACE_WITHIN_IF_PARENTHESES = true settings.SPACE_WITHIN_METHOD_PARENTHESES = true settings.SPACE_WITHIN_METHOD_CALL_PARENTHESES = true settings.SPACE_BEFORE_METHOD_PARENTHESES = true settings.SPACE_BEFORE_METHOD_CALL_PARENTHESES = true doTest() } fun testSpacesBeforeLBrace() { val settings = settings settings.SPACE_BEFORE_CLASS_LBRACE = true settings.SPACE_BEFORE_METHOD_LBRACE = true settings.SPACE_BEFORE_IF_LBRACE = true settings.SPACE_BEFORE_ELSE_LBRACE = true settings.SPACE_BEFORE_WHILE_LBRACE = true settings.SPACE_BEFORE_FOR_LBRACE = true settings.SPACE_BEFORE_DO_LBRACE = true settings.SPACE_BEFORE_SWITCH_LBRACE = true settings.SPACE_BEFORE_TRY_LBRACE = true settings.SPACE_BEFORE_CATCH_LBRACE = true settings.SPACE_BEFORE_FINALLY_LBRACE = true settings.SPACE_BEFORE_SYNCHRONIZED_LBRACE = true settings.SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE = true doTest() settings.SPACE_BEFORE_CLASS_LBRACE = false settings.SPACE_BEFORE_METHOD_LBRACE = false settings.SPACE_BEFORE_IF_LBRACE = false settings.SPACE_BEFORE_ELSE_LBRACE = false settings.SPACE_BEFORE_WHILE_LBRACE = false settings.SPACE_BEFORE_FOR_LBRACE = false settings.SPACE_BEFORE_DO_LBRACE = false settings.SPACE_BEFORE_SWITCH_LBRACE = false settings.SPACE_BEFORE_TRY_LBRACE = false settings.SPACE_BEFORE_CATCH_LBRACE = false settings.SPACE_BEFORE_FINALLY_LBRACE = false settings.SPACE_BEFORE_SYNCHRONIZED_LBRACE = false settings.SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE = false doTest("SpacesBeforeLBrace.java", "SpacesBeforeLBrace.java") } fun testCommentBeforeField() { val settings = settings settings.KEEP_LINE_BREAKS = false settings.KEEP_FIRST_COLUMN_COMMENT = false settings.KEEP_CONTROL_STATEMENT_IN_ONE_LINE = false settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = false settings.KEEP_SIMPLE_METHODS_IN_ONE_LINE = false doTextTest("class Foo{\n" + " //Foo a\n" + " Foo a; \n" + "}", "class Foo {\n" + " //Foo a\n" + " Foo a;\n" + "}") } fun testLabel() { val settings = settings settings.rootSettings.getIndentOptions(JavaFileType.INSTANCE).LABEL_INDENT_ABSOLUTE = true settings.SPECIAL_ELSE_IF_TREATMENT = true settings.FOR_BRACE_FORCE = CommonCodeStyleSettings.FORCE_BRACES_ALWAYS myTextRange = TextRange(59, 121) doTextTest("public class Foo {\n" + " public void foo() {\n" + "label2:\n" + " for (int i = 0; i < 5; i++)\n" + " {doSomething(i);\n" + " }\n" + " }\n" + "}", "public class Foo {\n" + " public void foo() {\n" + "label2:\n" + " for (int i = 0; i < 5; i++) {\n" + " doSomething(i);\n" + " }\n" + " }\n" + "}") } fun testElseOnNewLine() { doTextTest("class Foo{\n" + "void foo() {\n" + "if (a)\n" + "return;\n" + "else\n" + "return;\n" + "}\n" + "}", "class Foo {\n" + " void foo() {\n" + " if (a)\n" + " return;\n" + " else\n" + " return;\n" + " }\n" + "}") } fun testTwoClasses() { doTextTest("class A {}\n" + "class B {}", "class A {\n" + "}\n" + "\n" + "class B {\n" + "}") } fun testBraceOnNewLineIfWrapped() { settings.BINARY_OPERATION_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED settings.RIGHT_MARGIN = 35 settings.ALIGN_MULTILINE_BINARY_OPERATION = true doTextTest("class Foo {\n" + " void foo(){\n" + " if (veryLongCondition || veryVeryVeryVeryLongCondition) {\n" + " foo();\n" + " }\n" + " if (a) {\n" + " }" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " if (veryLongCondition ||\n" + " veryVeryVeryVeryLongCondition)\n" + " {\n" + " foo();\n" + " }\n" + " if (a) {\n" + " }\n" + " }\n" + "}") } fun testFirstArgumentWrapping() { settings.RIGHT_MARGIN = 20 settings.CALL_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED doTextTest("class Foo {\n" + " void foo() {\n" + " fooFooFooFoo(1);" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " fooFooFooFoo(\n" + " 1);\n" + " }\n" + "}") settings.CALL_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM doTextTest("class Foo {\n" + " void foo() {\n" + " fooFooFooFoo(1,2);" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " fooFooFooFoo(\n" + " 1,\n" + " 2);\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo() {\n" + " fooFooFoo(1,2);" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " fooFooFoo(1,\n" + " 2);\n" + " }\n" + "}") } fun testSpacesInsideWhile() { settings.SPACE_WITHIN_WHILE_PARENTHESES = true doTextTest("class Foo{\n" + " void foo() {\n" + " while(x != y) {\n" + " }\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " while ( x != y ) {\n" + " }\n" + " }\n" + "}") } fun testAssertStatementWrapping() { settings.ASSERT_STATEMENT_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.BINARY_OPERATION_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP settings.RIGHT_MARGIN = 40 val facade = javaFacade val effectiveLanguageLevel = LanguageLevelProjectExtension.getInstance(facade.project).languageLevel try { LanguageLevelProjectExtension.getInstance(facade.project).languageLevel = LanguageLevel.JDK_1_5 settings.ASSERT_STATEMENT_COLON_ON_NEXT_LINE = false doTextTest("class Foo {\n" + " void foo() {\n" + " assert methodWithVeryVeryLongName() : foo;\n" + " assert i + j + k + l + n + m <= 2 : \"assert description\";\n" + " }\n" + "}\n", "class Foo {\n" + " void foo() {\n" + " assert methodWithVeryVeryLongName() :\n" + " foo;\n" + " assert i + j + k + l + n + m <= 2 :\n" + " \"assert description\";\n" + " }\n" + "}\n") settings.ASSERT_STATEMENT_COLON_ON_NEXT_LINE = true doTextTest("class Foo {\n" + " void foo() {\n" + " assert methodWithVeryVeryLongName() : foo;\n" + " assert i + j + k + l + n + m <= 2 : \"assert description\";\n" + " }\n" + "}\n", "class Foo {\n" + " void foo() {\n" + " assert methodWithVeryVeryLongName()\n" + " : foo;\n" + " assert i + j + k + l + n + m <= 2\n" + " : \"assert description\";\n" + " }\n" + "}\n") } finally { LanguageLevelProjectExtension.getInstance(facade.project).languageLevel = effectiveLanguageLevel } } fun testAssertStatementWrapping2() { settings.BINARY_OPERATION_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP settings.ASSERT_STATEMENT_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.RIGHT_MARGIN = 37 val options = settings.rootSettings.getIndentOptions(JavaFileType.INSTANCE) options.INDENT_SIZE = 2 options.CONTINUATION_INDENT_SIZE = 2 settings.ASSERT_STATEMENT_COLON_ON_NEXT_LINE = true val facade = javaFacade val effectiveLanguageLevel = LanguageLevelProjectExtension.getInstance(facade.project).languageLevel LanguageLevelProjectExtension.getInstance(facade.project).languageLevel = LanguageLevel.JDK_1_5 try { doTextTest( "class Foo {\n" + " void foo() {\n" + " assert i + j + k + l + n + m <= 2 : \"assert description\";" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " assert i + j + k + l + n + m <= 2\n" + " : \"assert description\";\n" + " }\n" + "}") settings.ASSERT_STATEMENT_COLON_ON_NEXT_LINE = false doTextTest( "class Foo {\n" + " void foo() {\n" + " assert i + j + k + l + n + m <= 2 : \"assert description\";" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " assert\n" + " i + j + k + l + n + m <= 2 :\n" + " \"assert description\";\n" + " }\n" + "}") } finally { LanguageLevelProjectExtension.getInstance(facade.project).languageLevel = effectiveLanguageLevel } } fun test() { settings.rootSettings.getIndentOptions(JavaFileType.INSTANCE).INDENT_SIZE = 2 settings.rootSettings.getIndentOptions(JavaFileType.INSTANCE).CONTINUATION_INDENT_SIZE = 2 settings.RIGHT_MARGIN = 37 settings.ALIGN_MULTILINE_EXTENDS_LIST = true settings.EXTENDS_KEYWORD_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.EXTENDS_LIST_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.ASSERT_STATEMENT_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.ASSERT_STATEMENT_COLON_ON_NEXT_LINE = false settings.ALIGN_MULTILINE_BINARY_OPERATION = true val facade = javaFacade val effectiveLanguageLevel = LanguageLevelProjectExtension.getInstance(facade.project).languageLevel LanguageLevelProjectExtension.getInstance(facade.project).languageLevel = LanguageLevel.JDK_1_5 try { doTextTest("public class ThisIsASampleClass extends C1 implements I1, I2, I3, I4, I5 {\n" + " public void longerMethod() {\n" + " assert i + j + k + l + n+ m <= 2 : \"assert description\";" + " }\n" + "}", "public class ThisIsASampleClass\n" + " extends C1\n" + " implements I1, I2, I3, I4, I5 {\n" + " public void longerMethod() {\n" + " assert\n" + " i + j + k + l + n + m <= 2 :\n" + " \"assert description\";\n" + " }\n" + "}") } finally { LanguageLevelProjectExtension.getInstance(facade.project).languageLevel = effectiveLanguageLevel } } fun testLBrace() { settings.METHOD_BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE settings.RIGHT_MARGIN = 14 doTextTest("class Foo {\n" + " void foo() {\n" + " \n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + "\n" + " }\n" + "}") } fun testJavaDocLeadingAsterisksAreDisabled() { javaSettings.JD_LEADING_ASTERISKS_ARE_ENABLED = false doTextTest("class Foo {\n" + " /**\n" + " @param i\n" + " @param j\n" + " */\n" + " void foo(int i, int j) {\n" + " }\n" + "}", "class Foo {\n" + " /**\n" + " @param i\n" + " @param j\n" + " */\n" + " void foo(int i, int j) {\n" + " }\n" + "}") } fun testBinaryExpression() { settings.ALIGN_MULTILINE_BINARY_OPERATION = true doTextTest("class Foo {\n" + " void foo() {\n" + " if (event.isConsumed() &&\n" + "condition2) {\n" + " return;\n" + " }\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " if (event.isConsumed() &&\n" + " condition2) {\n" + " return;\n" + " }\n" + " }\n" + "}") } fun testCaseBraces() { doTextTest("class Foo{\n" + " void foo() {\n" + " switch (a) {\n" + " case 0: {\n" + " }\n" + " }\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " switch (a) {\n" + " case 0: {\n" + " }\n" + " }\n" + " }\n" + "}") } fun testFormatCodeFragment() { val factory = JavaCodeFragmentFactory.getInstance(project) val fragment = factory.createCodeBlockCodeFragment("a=1;int b=2;", null, true) val result = arrayOfNulls<PsiElement>(1) CommandProcessor.getInstance().executeCommand(project, { WriteCommandAction.runWriteCommandAction(null) { try { result[0] = CodeStyleManager.getInstance(project).reformat(fragment) } catch (e: IncorrectOperationException) { fail(e.localizedMessage) } } }, null, null) assertEquals("a = 1;\n" + "int b = 2;", result[0]!!.text) } fun testNewLineAfterJavaDocs() { val before = "/** @noinspection InstanceVariableNamingConvention*/class Foo{\n" + "/** @noinspection InstanceVariableNamingConvention*/int myFoo;\n" + "/** @noinspection InstanceVariableNamingConvention*/ void foo(){}}" val after = "/**\n" + " * @noinspection InstanceVariableNamingConvention\n" + " */\n" + "class Foo {\n" + " /**\n" + " * @noinspection InstanceVariableNamingConvention\n" + " */\n" + " int myFoo;\n" + "\n" + " /**\n" + " * @noinspection InstanceVariableNamingConvention\n" + " */\n" + " void foo() {\n" + " }\n" + "}" doTextTest(before, after) } fun testArrayInitializerWrapping() { settings.ARRAY_INITIALIZER_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION = false settings.RIGHT_MARGIN = 37 doTextTest("class Foo{\n" + " public int[] i = new int[]{1,2,3,4,5,6,7,8,9};\n" + " void foo() {\n" + " foo(new int[]{1,2,3,4,5,6,7,8,9});\n" + " }" + "}", "class Foo {\n" + " public int[] i = new int[]{1, 2,\n" + " 3, 4, 5, 6, 7, 8, 9};\n" + "\n" + " void foo() {\n" + " foo(new int[]{1, 2, 3, 4, 5,\n" + " 6, 7, 8, 9});\n" + " }\n" + "}") settings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION = true doTextTest("class Foo{\n" + " public int[] i = new int[]{1,2,3,4,5,6,7,8,9};\n" + " void foo() {\n" + " foo(new int[]{1,2,3,4,5,6,7,8,9});\n" + " }" + "}", "class Foo {\n" + " public int[] i = new int[]{1, 2,\n" + " 3, 4,\n" + " 5, 6,\n" + " 7, 8,\n" + " 9};\n" + "\n" + " void foo() {\n" + " foo(new int[]{1, 2, 3, 4, 5,\n" + " 6, 7, 8, 9});\n" + " }\n" + "}") } fun testJavaDocIndentation() { settings.rootSettings.getIndentOptions(JavaFileType.INSTANCE).INDENT_SIZE = 2 settings.rootSettings.getIndentOptions(JavaFileType.INSTANCE).CONTINUATION_INDENT_SIZE = 2 settings.rootSettings.getIndentOptions(JavaFileType.INSTANCE).TAB_SIZE = 4 javaSettings.ENABLE_JAVADOC_FORMATTING = false doTextTest("public interface PsiParser {\n" + " /**\n" + " * Parses the contents of the specified PSI builder and returns an AST tree with the\n" + " * specified type of root element. The PSI builder contents is the entire file\n" + " * or (if chameleon tokens are used) the text of a chameleon token which needs to\n" + " * be reparsed.\n" + " * @param root the type of the root element in the AST tree.\n" + " * @param builder the builder which is used to retrieve the original file tokens and build the AST tree.\n" + " * @return the root of the resulting AST tree.\n" + " */\n" + " ASTNode parse(IElementType root, PsiBuilder builder);\n" + "}", "public interface PsiParser {\n" + " /**\n" + " * Parses the contents of the specified PSI builder and returns an AST tree with the\n" + " * specified type of root element. The PSI builder contents is the entire file\n" + " * or (if chameleon tokens are used) the text of a chameleon token which needs to\n" + " * be reparsed.\n" + " * @param root the type of the root element in the AST tree.\n" + " * @param builder the builder which is used to retrieve the original file tokens and build the AST tree.\n" + " * @return the root of the resulting AST tree.\n" + " */\n" + " ASTNode parse(IElementType root, PsiBuilder builder);\n" + "}") } fun testRemoveLineBreak() { settings.KEEP_LINE_BREAKS = true settings.CLASS_BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE settings.METHOD_BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE settings.BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE doTextTest("class A\n" + "{\n" + "}", "class A {\n" + "}") doTextTest("class A {\n" + " void foo()\n" + " {\n" + " }\n" + "}", "class A {\n" + " void foo() {\n" + " }\n" + "}") doTextTest("class A {\n" + " void foo()\n" + " {\n" + " if (a)\n" + " {\n" + " }\n" + " }\n" + "}", "class A {\n" + " void foo() {\n" + " if (a) {\n" + " }\n" + " }\n" + "}") } fun testBlankLines() { settings.KEEP_BLANK_LINES_IN_DECLARATIONS = 0 settings.KEEP_BLANK_LINES_IN_CODE = 0 settings.KEEP_BLANK_LINES_BEFORE_RBRACE = 0 settings.BLANK_LINES_AFTER_CLASS_HEADER = 0 settings.BLANK_LINES_AFTER_IMPORTS = 0 settings.BLANK_LINES_AFTER_PACKAGE = 0 settings.BLANK_LINES_AROUND_CLASS = 0 settings.BLANK_LINES_AROUND_FIELD = 0 settings.BLANK_LINES_AROUND_METHOD = 0 settings.BLANK_LINES_BEFORE_IMPORTS = 0 settings.BLANK_LINES_BEFORE_PACKAGE = 0 settings.BLANK_LINES_AROUND_FIELD_IN_INTERFACE = 2 settings.BLANK_LINES_AROUND_METHOD_IN_INTERFACE = 3 doTextTest("/*\n" + " * This is a sample file.\n" + " */\n" + "package com.intellij.samples;\n" + "\n" + "import com.intellij.idea.Main;\n" + "\n" + "import javax.swing.*;\n" + "import java.util.Vector;\n" + "\n" + "public class Foo {\n" + " private int field1;\n" + " private int field2;\n" + "\n" + " public void foo1() {\n" + "\n" + " }\n" + "\n" + " public void foo2() {\n" + "\n" + " }\n" + "\n" + "}", "/*\n" + " * This is a sample file.\n" + " */\n" + "package com.intellij.samples;\n" + "import com.intellij.idea.Main;\n" + "\n" + "import javax.swing.*;\n" + "import java.util.Vector;\n" + "public class Foo {\n" + " private int field1;\n" + " private int field2;\n" + " public void foo1() {\n" + " }\n" + " public void foo2() {\n" + " }\n" + "}") doTextTest("interface Foo {\n" + " int field1;\n" + " int field2;\n" + "\n" + " void foo1();\n" + "\n" + " void foo2();\n" + "\n" + "}", "interface Foo {\n" + " int field1;\n" + "\n" + "\n" + " int field2;\n" + "\n" + "\n" + "\n" + " void foo1();\n" + "\n" + "\n" + "\n" + " void foo2();\n" + "}") } fun testStaticBlockBraces() { settings.BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE doTextTest("class Foo {\n" + " static {\n" + " //comment\n" + " i = foo();\n" + " }\n" + "}", "class Foo {\n" + " static {\n" + " //comment\n" + " i = foo();\n" + " }\n" + "}") settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED doTextTest("class Foo {\n" + " static {\n" + " //comment\n" + " i = foo();\n" + " }\n" + "}", "class Foo {\n" + " static {\n" + " //comment\n" + " i = foo();\n" + " }\n" + "}") settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE doTextTest("class Foo {\n" + " static {\n" + " //comment\n" + " i = foo();\n" + " }\n" + "}", "class Foo {\n" + " static\n" + " {\n" + " //comment\n" + " i = foo();\n" + " }\n" + "}") settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED doTextTest("class Foo {\n" + " static {\n" + " //comment\n" + " i = foo();\n" + " }\n" + "}", "class Foo {\n" + " static\n" + " {\n" + " //comment\n" + " i = foo();\n" + " }\n" + "}") settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED2 doTextTest("class Foo {\n" + " static {\n" + " //comment\n" + " i = foo();\n" + " }\n" + "}", "class Foo {\n" + " static\n" + " {\n" + " //comment\n" + " i = foo();\n" + " }\n" + "}") } fun testBraces2() { settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED doTextTest("class Foo {\n" + " void foo() {\n" + " if (clientSocket == null)\n" + " {\n" + " return false;\n" + " }" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " if (clientSocket == null) {\n" + " return false;\n" + " }\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo() {\n" + " for (int i = 0; i < 10; i++)\n" + " {\n" + " return false;\n" + " }" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " for (int i = 0; i < 10; i++) {\n" + " return false;\n" + " }\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo() {\n" + " for (Object i : collection)\n" + " {\n" + " return false;\n" + " }" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " for (Object i : collection) {\n" + " return false;\n" + " }\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo() {\n" + " while (i >0)\n" + " {\n" + " return false;\n" + " }" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " while (i > 0) {\n" + " return false;\n" + " }\n" + " }\n" + "}") settings.METHOD_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED doTextTest("class Foo{\n" + " /**\n" + " *\n" + " */\n" + " void foo() {\n" + " }\n" + "}", "class Foo {\n" + " /**\n" + " *\n" + " */\n" + " void foo() {\n" + " }\n" + "}") settings.CLASS_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED doTextTest("/**\n" + " *\n" + " */\n" + "class Foo\n{\n" + "}", "/**\n" + " *\n" + " */\n" + "class Foo {\n" + "}") doTextTest("/**\n" + " *\n" + " */\n" + "class Foo\n extends B\n{\n" + "}", "/**\n" + " *\n" + " */\n" + "class Foo\n extends B\n" + "{\n" + "}") doTextTest("/**\n" + " *\n" + " */\n" + "class Foo\n permits B\n{\n" + "}", "/**\n" + " *\n" + " */\n" + "class Foo\n permits B\n" + "{\n" + "}") } fun testSynchronized() { settings.BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE doTextTest("class Foo {\n" + " void foo() {\n" + "synchronized (this) {foo();\n" + "}\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " synchronized (this) {\n" + " foo();\n" + " }\n" + " }\n" + "}") settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE doTextTest("class Foo {\n" + " void foo() {\n" + "synchronized (this) {foo();\n" + "}\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " synchronized (this)\n" + " {\n" + " foo();\n" + " }\n" + " }\n" + "}") settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED doTextTest("class Foo {\n" + " void foo() {\n" + "synchronized (this) {foo();\n" + "}\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " synchronized (this)\n" + " {\n" + " foo();\n" + " }\n" + " }\n" + "}") settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED2 doTextTest("class Foo {\n" + " void foo() {\n" + "synchronized (this) {\n" + "foo();\n" + "}\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " synchronized (this)\n" + " {\n" + " foo();\n" + " }\n" + " }\n" + "}") } fun testNextLineShiftedForBlockStatement() { settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED doTextTest("class Foo {\n" + " void foo() {\n" + " if (a)\n" + " foo();\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " if (a)\n" + " foo();\n" + " }\n" + "}") } fun testFieldWithJavadocAndAnnotation() { doTextTest("class Foo {\n" + " /**\n" + " * java doc\n" + " */\n" + " @NoInspection\n" + " String field;\n" + "}", "class Foo {\n" + " /**\n" + " * java doc\n" + " */\n" + " @NoInspection\n" + " String field;\n" + "}") } fun testLongCallChainAfterElse() { settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE settings.KEEP_CONTROL_STATEMENT_IN_ONE_LINE = true settings.KEEP_SIMPLE_METHODS_IN_ONE_LINE = true settings.ELSE_ON_NEW_LINE = false settings.RIGHT_MARGIN = 110 settings.KEEP_LINE_BREAKS = false doTextTest("class Foo {\n" + " void foo() {\n" + " if (types.length > 1) // returns multiple columns\n" + " {\n" + " } else\n" + " result.add(initializeObject(os, types[0], initializeCollections, initializeAssociations, initializeChildren));" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " if (types.length > 1) // returns multiple columns\n" + " {\n" + " } else\n" + " result.add(initializeObject(os, types[0], initializeCollections, initializeAssociations, initializeChildren));\n" + " }\n" + "}") } fun testSpacesIncode() { val facade = javaFacade val level = LanguageLevelProjectExtension.getInstance(facade.project).languageLevel LanguageLevelProjectExtension.getInstance(facade.project).languageLevel = LanguageLevel.JDK_1_5 try { doTextTest("class C<Y, X> {\n" + "}", "class C<Y, X> {\n" + "}") settings.SPACE_BEFORE_METHOD_LBRACE = true settings.KEEP_SIMPLE_METHODS_IN_ONE_LINE = true doTextTest("enum En {\n" + " A(10) {},\n" + " B(10) {},\n" + " C(10);\n" + "\n" + " En(int i) { }\n" + "}", "enum En {\n" + " A(10) {},\n" + " B(10) {},\n" + " C(10);\n" + "\n" + " En(int i) {}\n" + "}") doTextTest("class C {\n" + " void foo (Map<?, String> s) {\n" + " Set<? extends Map<?, String>.Entry<?, String>> temp = s.entries();\n" + " }\n" + "}", "class C {\n" + " void foo(Map<?, String> s) {\n" + " Set<? extends Map<?, String>.Entry<?, String>> temp = s.entries();\n" + " }\n" + "}") doTextTest("class B {\n" + " public final A<String> myDelegate = new A<String>();\n" + "\n" + " public List<? extends String> method1() {\n" + " return myDelegate.method1();\n" + " }\n" + "\n" + " public String method2(String t) {\n" + " return myDelegate.method2(t);\n" + " }\n" + "}", "class B {\n" + " public final A<String> myDelegate = new A<String>();\n" + "\n" + " public List<? extends String> method1() {\n" + " return myDelegate.method1();\n" + " }\n" + "\n" + " public String method2(String t) {\n" + " return myDelegate.method2(t);\n" + " }\n" + "}") } finally { LanguageLevelProjectExtension.getInstance(facade.project).languageLevel = level } } ///IDEA-7761 fun testKeepBlankLineInCodeBeforeComment() { settings.KEEP_BLANK_LINES_IN_CODE = 1 settings.KEEP_BLANK_LINES_IN_DECLARATIONS = 0 settings.KEEP_FIRST_COLUMN_COMMENT = false doTextTest("public class ReformatProblem {\n" + "\n" + " //comment in declaration\n" + " public static void main(String[] args) {\n" + " for (String arg : args) {\n" + " \n" + " // a first system out\n" + " System.out.println(\"\");\n" + " \n" + " // another system out\n" + " System.out.println(\"arg = \" + arg);\n" + " }\n" + " }\n" + "}", "public class ReformatProblem {\n" + " //comment in declaration\n" + " public static void main(String[] args) {\n" + " for (String arg : args) {\n" + "\n" + " // a first system out\n" + " System.out.println(\"\");\n" + "\n" + " // another system out\n" + " System.out.println(\"arg = \" + arg);\n" + " }\n" + " }\n" + "}") settings.KEEP_BLANK_LINES_IN_CODE = 0 settings.KEEP_BLANK_LINES_IN_DECLARATIONS = 1 settings.KEEP_FIRST_COLUMN_COMMENT = false doTextTest("public class ReformatProblem {\n" + "\n" + " //comment in declaration\n" + " public static void main(String[] args) {\n" + " for (String arg : args) {\n" + " \n" + " // a first system out\n" + " System.out.println(\"\");\n" + " \n" + " // another system out\n" + " System.out.println(\"arg = \" + arg);\n" + " }\n" + " }\n" + "}", "public class ReformatProblem {\n" + "\n" + " //comment in declaration\n" + " public static void main(String[] args) {\n" + " for (String arg : args) {\n" + " // a first system out\n" + " System.out.println(\"\");\n" + " // another system out\n" + " System.out.println(\"arg = \" + arg);\n" + " }\n" + " }\n" + "}") } fun testSpaceBeforeTryBrace() { settings.SPACE_BEFORE_TRY_LBRACE = false settings.SPACE_BEFORE_FINALLY_LBRACE = true doTextTest("class Foo{\n" + " void foo() {\n" + " try {\n" + " } finally {\n" + " }\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " try{\n" + " } finally {\n" + " }\n" + " }\n" + "}") settings.SPACE_BEFORE_TRY_LBRACE = true settings.SPACE_BEFORE_FINALLY_LBRACE = false doTextTest("class Foo{\n" + " void foo() {\n" + " try {\n" + " } finally {\n" + " }\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " try {\n" + " } finally{\n" + " }\n" + " }\n" + "}") } fun testFormatComments() { javaSettings.ENABLE_JAVADOC_FORMATTING = true doTextTest("public class Test {\n" + "\n" + " /**\n" + " * The s property.\n" + " */\n" + " private String s;\n" + "}", "public class Test {\n" + "\n" + " /**\n" + " * The s property.\n" + " */\n" + " private String s;\n" + "}") } @Throws(IncorrectOperationException::class) fun testDoNotWrapLBrace() { settings.BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE settings.RIGHT_MARGIN = 66 doTextTest("public class Test {\n" + " void foo(){\n" + " if (veryLongIdentifier1 == 1 && veryLongIdentifier2 == 2) {\n" + " doSmth();\n" + " }\n" + " }\n" + "}", "public class Test {\n" + " void foo() {\n" + " if (veryLongIdentifier1 == 1 && veryLongIdentifier2 == 2) {\n" + " doSmth();\n" + " }\n" + " }\n" + "}") } @Throws(IncorrectOperationException::class) fun testNewLinesAroundArrayInitializer() { settings.ARRAY_INITIALIZER_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.ARRAY_INITIALIZER_LBRACE_ON_NEXT_LINE = true settings.ARRAY_INITIALIZER_RBRACE_ON_NEXT_LINE = true settings.RIGHT_MARGIN = 40 doTextTest("class Foo {\n" + " int[] a = new int[]{1,2,0x0052,0x0053,0x0054,0x0054,0x0054};\n" + "}", "class Foo {\n" + " int[] a = new int[]{\n" + " 1, 2, 0x0052, 0x0053,\n" + " 0x0054, 0x0054, 0x0054\n" + " };\n" + "}") } @Throws(IncorrectOperationException::class) fun testSpaceAfterCommaInEnum() { settings.SPACE_AFTER_COMMA = true val facade = javaFacade val effectiveLanguageLevel = LanguageLevelProjectExtension.getInstance(facade.project).languageLevel try { LanguageLevelProjectExtension.getInstance(facade.project).languageLevel = LanguageLevel.JDK_1_5 doTextTest("public enum StringExDirection {\n" + "\n" + " RIGHT_TO_LEFT, LEFT_TO_RIGHT\n" + "\n" + "}", "public enum StringExDirection {\n" + "\n" + " RIGHT_TO_LEFT, LEFT_TO_RIGHT\n" + "\n" + "}") } finally { LanguageLevelProjectExtension.getInstance(facade.project).languageLevel = effectiveLanguageLevel } } fun testWrapBetweenCommaAndSemicolon() { doTextTest(""" enum Foo { VALUE_A, VALUE_B,; Foo() { // whatever } } """.trimIndent(), """ enum Foo { VALUE_A, VALUE_B, ; Foo() { // whatever } } """.trimIndent()) } @Throws(IncorrectOperationException::class) fun testRemoveBraceBeforeInstanceOf() { doTextTest("class ReformatInstanceOf {\n" + " void foo(Object string) {\n" + " if (string.toString() instanceof String) {} // reformat me\n" + " }\n" + "}", "class ReformatInstanceOf {\n" + " void foo(Object string) {\n" + " if (string.toString() instanceof String) {\n" + " } // reformat me\n" + " }\n" + "}") } @Throws(IncorrectOperationException::class) fun testAnnotationBeforePackageLocalConstructor() { doTextTest("class Foo {\n" + " @MyAnnotation Foo() {\n" + " }\n" + "}", "class Foo {\n" + " @MyAnnotation\n" + " Foo() {\n" + " }\n" + "}") } fun testLongAnnotationsAreNotWrapped() { settings.ARRAY_INITIALIZER_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED doTest() } fun testWrapExtendsList() { settings.RIGHT_MARGIN = 50 settings.EXTENDS_LIST_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM settings.EXTENDS_KEYWORD_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED doTextTest("class ColtreDataProvider extends DataProvider, AgentEventListener, ParameterDataEventListener {\n}", "class ColtreDataProvider extends DataProvider,\n" + " AgentEventListener,\n" + " ParameterDataEventListener {\n}") } fun testWrapLongExpression() { settings.RIGHT_MARGIN = 80 settings.BINARY_OPERATION_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.ALIGN_MULTILINE_BINARY_OPERATION = true doTextTest("class Foo {\n" + " void foo () {\n" + " return (interval1.getEndIndex() >= interval2.getStartIndex() && interval3.getStartIndex() <= interval4.getEndIndex()) || (interval5.getEndIndex() >= interval6.getStartIndex() && interval7.getStartIndex() <= interval8.getEndIndex());" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " return (interval1.getEndIndex() >= interval2.getStartIndex() &&\n" + " interval3.getStartIndex() <= interval4.getEndIndex()) ||\n" + " (interval5.getEndIndex() >= interval6.getStartIndex() &&\n" + " interval7.getStartIndex() <= interval8.getEndIndex());\n" + " }\n" + "}") } fun testDoNotWrapCallChainIfParametersWrapped() { settings.RIGHT_MARGIN = 87 settings.CALL_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.METHOD_CALL_CHAIN_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true //getSettings().PREFER_PARAMETERS_WRAP = true; doMethodTest( //9 30 70 80 86 "descriptors = manager.createProblemDescriptor(parameter1, parameter2, parameterparameterpar3,parameter4);", "descriptors = manager.createProblemDescriptor(parameter1, parameter2,\n" + " parameterparameterpar3,\n" + " parameter4);" ) } fun testAlignTernaryOperation() { settings.ALIGN_MULTILINE_TERNARY_OPERATION = true doMethodTest("String s = x == 0 ? \"hello\" :\n" + " x == 5 ? \"something else\" :\n" + " x > 0 ? \"bla, bla\" :\n" + " \"\";", "String s = x == 0 ? \"hello\" :\n" + " x == 5 ? \"something else\" :\n" + " x > 0 ? \"bla, bla\" :\n" + " \"\";") settings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE = true doMethodTest("int someVariable = a ?\n" + "x :\n" + "y;", "int someVariable = a ?\n" + " x :\n" + " y;") } fun testRightMargin_2() { settings.RIGHT_MARGIN = 65 settings.ASSIGNMENT_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE = true settings.KEEP_LINE_BREAKS = false doClassTest( "public static final Map<LongType, LongType> longVariableName =\n" + "variableValue;", "public static final Map<LongType, LongType> longVariableName\n" + " = variableValue;") } fun testRightMargin_3() { settings.RIGHT_MARGIN = 65 settings.ASSIGNMENT_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE = false settings.KEEP_LINE_BREAKS = false doClassTest( "public static final Map<LongType, LongType> longVariableName =\n" + "variableValue;", "public static final Map<LongType, LongType>\n" + " longVariableName = variableValue;") } fun testDoNotRemoveLineBreaksBetweenComments() { settings.KEEP_LINE_BREAKS = false settings.KEEP_FIRST_COLUMN_COMMENT = false doTextTest( "public class Foo {\n" + " //here is a comment\n" + " //line 2 of comment\n" + " public void myMethod() {\n" + " //a comment\n" + " //... another comment\n" + " }\n" + "\n" + "//save for later\n" + "// public void incompleteMethod() {\n" + "// int blah = 0;\n" + "// callSomeMethod();\n" + "// callSomeOtherMethod();\n" + "// doSomethingElse();\n" + "// }\n" + "\n" + "//comment at first line\n" + "}", "public class Foo {\n" + " //here is a comment\n" + " //line 2 of comment\n" + " public void myMethod() {\n" + " //a comment\n" + " //... another comment\n" + " }\n" + "\n" + " //save for later\n" + " // public void incompleteMethod() {\n" + " // int blah = 0;\n" + " // callSomeMethod();\n" + " // callSomeOtherMethod();\n" + " // doSomethingElse();\n" + " // }\n" + "\n" + " //comment at first line\n" + "}") } fun testWrapParamsOnEveryItem() { val codeStyleSettings = CodeStyle.getSettings(project) val javaSettings = codeStyleSettings.getCommonSettings(JavaLanguage.INSTANCE) val oldMargin = javaSettings.RIGHT_MARGIN val oldKeep = javaSettings.KEEP_LINE_BREAKS val oldWrap = javaSettings.METHOD_PARAMETERS_WRAP try { codeStyleSettings.setRightMargin(JavaLanguage.INSTANCE, 80) javaSettings.KEEP_LINE_BREAKS = false javaSettings.METHOD_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM doClassTest( "public void foo(String p1,\n" + " String p2,\n" + " String p3,\n" + " String p4,\n" + " String p5,\n" + " String p6,\n" + " String p7) {\n" + " //To change body of implemented methods use File | Settings | File Templates.\n" + "}", "public void foo(String p1,\n" + " String p2,\n" + " String p3,\n" + " String p4,\n" + " String p5,\n" + " String p6,\n" + " String p7) {\n" + " //To change body of implemented methods use File | Settings | File Templates.\n" + "}") } finally { codeStyleSettings.setRightMargin(JavaLanguage.INSTANCE, oldMargin) javaSettings.KEEP_LINE_BREAKS = oldKeep javaSettings.METHOD_PARAMETERS_WRAP = oldWrap } } fun testCommentAfterDeclaration() { val codeStyleSettings = CodeStyle.getSettings(project) val javaSettings = codeStyleSettings.getCommonSettings(JavaLanguage.INSTANCE) val oldWrap = javaSettings.ASSIGNMENT_WRAP try { codeStyleSettings.defaultRightMargin = 20 javaSettings.ASSIGNMENT_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED doMethodTest( "int i=0; //comment comment", "int i =\n" + " 0; //comment comment" ) } finally { javaSettings.ASSIGNMENT_WRAP = oldWrap } } // ------------------------------------------------ // Tickets-implied tests // ------------------------------------------------ fun testSCR915() { settings.SPACE_AROUND_ADDITIVE_OPERATORS = false doTest("SCR915.java", "SCR915_after.java") } fun testSCR429() { val settings = settings settings.KEEP_BLANK_LINES_IN_CODE = 2 settings.KEEP_BLANK_LINES_BEFORE_RBRACE = 2 settings.KEEP_BLANK_LINES_IN_DECLARATIONS = 2 doTest() } fun testSCR548() { val settings = settings settings.rootSettings.getIndentOptions(JavaFileType.INSTANCE).INDENT_SIZE = 4 settings.rootSettings.getIndentOptions(JavaFileType.INSTANCE).CONTINUATION_INDENT_SIZE = 2 doTest() } fun testIDEA_16151() { doClassTest("@ValidateNestedProperties({\n" + "@Validate(field=\"name\", required=true, maxlength=Trip.NAME),\n" + "@Validate(field=\"name\", required=true, maxlength=Trip.NAME)\n" + "})" + "public Trip getTrip() {\n" + "}", "@ValidateNestedProperties({\n" + " @Validate(field = \"name\", required = true, maxlength = Trip.NAME),\n" + " @Validate(field = \"name\", required = true, maxlength = Trip.NAME)\n" + "})\n" + "public Trip getTrip() {\n" + "}") } fun testIDEA_14324() { settings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION = true doClassTest( "@Ann1({ @Ann2,\n" + " @Ann3})\n" + "public AuthorAddress getAddress() {\n" + " return address;\n" + "}", "@Ann1({@Ann2,\n" + " @Ann3})\n" + "public AuthorAddress getAddress() {\n" + " return address;\n" + "}") doClassTest("@AttributeOverrides({ @AttributeOverride(name = \"address\", column = @Column(name = \"ADDR\")),\n" + " @AttributeOverride(name = \"country\", column = @Column(name = \"NATION\")) })\n" + "public AuthorAddress getAddress() {\n" + " return address;\n" + "}", "@AttributeOverrides({@AttributeOverride(name = \"address\", column = @Column(name = \"ADDR\")),\n" + " @AttributeOverride(name = \"country\", column = @Column(name = \"NATION\"))})\n" + "public AuthorAddress getAddress() {\n" + " return address;\n" + "}" ) } fun testSCR260() { val settings = settings settings.IF_BRACE_FORCE = CommonCodeStyleSettings.FORCE_BRACES_ALWAYS settings.BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE settings.KEEP_LINE_BREAKS = false doTest() } fun testSCR114() { val settings = settings settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE settings.CATCH_ON_NEW_LINE = true doTest() } fun testSCR259() { myTextRange = TextRange(36, 60) val settings = settings settings.IF_BRACE_FORCE = CommonCodeStyleSettings.FORCE_BRACES_ALWAYS settings.KEEP_LINE_BREAKS = false doTest() } fun testSCR279() { val settings = settings settings.ALIGN_MULTILINE_BINARY_OPERATION = true doTest() } fun testSCR395() { val settings = settings settings.METHOD_BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE doTest() } fun testSCR11799() { val settings = settings settings.rootSettings.getIndentOptions(JavaFileType.INSTANCE).CONTINUATION_INDENT_SIZE = 4 settings.CLASS_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE settings.METHOD_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE doTest() } fun testSCR501() { val settings = settings settings.KEEP_FIRST_COLUMN_COMMENT = true doTest() } fun testSCR879() { val settings = settings settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE doTest() } fun testSCR547() { doTextTest("class Foo { \n" + " Object[] objs = { \n" + " new Object() { \n" + " public String toString() { \n" + " return \"x\"; \n" + " } \n" + " } \n" + " }; \n" + "}", "class Foo {\n" + " Object[] objs = {\n" + " new Object() {\n" + " public String toString() {\n" + " return \"x\";\n" + " }\n" + " }\n" + " };\n" + "}") } fun testSCR479() { val settings = settings settings.RIGHT_MARGIN = 80 settings.TERNARY_OPERATION_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED doTextTest("public class Foo {\n" + " public static void main(String[] args) {\n" + " if (name != null ? !name.equals(that.name) : that.name != null)\n" + " return false;\n" + " }\n" + "}", "public class Foo {\n" + " public static void main(String[] args) {\n" + " if (name != null ? !name.equals(that.name) : that.name != null)\n" + " return false;\n" + " }\n" + "}") } fun testSCR190() { val settings = settings settings.KEEP_LINE_BREAKS = false doTextTest("public class EntityObject \n" + "{ \n" + " private Integer id; \n" + "\n" + " public Integer getId() \n" + " { \n" + " return id; \n" + " } \n" + "\n" + " public void setId(Integer id) \n" + " { \n" + " this.id = id; \n" + " } \n" + "}", "public class EntityObject {\n" + " private Integer id;\n" + "\n" + " public Integer getId() {\n" + " return id;\n" + " }\n" + "\n" + " public void setId(Integer id) {\n" + " this.id = id;\n" + " }\n" + "}") } fun testSCR1535() { val settings = settings settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE settings.CLASS_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE settings.METHOD_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE doTextTest("public class Foo {\n" + " public int foo() {\n" + " if (a) {\n" + " return;\n" + " }\n" + " }\n" + "}", "public class Foo\n" + "{\n" + " public int foo()\n" + " {\n" + " if (a)\n" + " {\n" + " return;\n" + " }\n" + " }\n" + "}") } fun testSCR970() { val settings = settings settings.THROWS_KEYWORD_WRAP = CommonCodeStyleSettings.WRAP_ALWAYS settings.THROWS_LIST_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.METHOD_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED doTest() } fun testSCR1486() { doTextTest("public class Test {\n" + " private BigDecimal\n" + "}", "public class Test {\n" + " private BigDecimal\n" + "}") doTextTest("public class Test {\n" + " @NotNull private BigDecimal\n" + "}", "public class Test {\n" + " @NotNull\n" + " private BigDecimal\n" + "}") } fun test1607() { settings.RIGHT_MARGIN = 30 settings.METHOD_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE settings.KEEP_SIMPLE_METHODS_IN_ONE_LINE = true settings.ALIGN_MULTILINE_PARAMETERS = true settings.METHOD_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED doTextTest("class TEst {\n" + "void foo(A a,B b){ /* compiled code */ }\n" + "}", "class TEst {\n" + " void foo(A a, B b)\n" + " { /* compiled code */ }\n" + "}") } fun testSCR1615() { settings.CLASS_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED settings.METHOD_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED doTextTest( "public class ZZZZ \n" + " { \n" + " public ZZZZ() \n" + " { \n" + " if (a){\n" + "foo();}\n" + " } \n" + " }", "public class ZZZZ\n" + " {\n" + " public ZZZZ()\n" + " {\n" + " if (a)\n" + " {\n" + " foo();\n" + " }\n" + " }\n" + " }") } fun testSCR1047() { doTextTest("class Foo{\n" + " void foo(){\n" + " String field1, field2;\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " String field1, field2;\n" + " }\n" + "}") } fun testSCR524() { settings.METHOD_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED settings.KEEP_SIMPLE_METHODS_IN_ONE_LINE = true settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = false doTextTest("class Foo {\n" + " void foo() { return;}" + "}", "class Foo {\n" + " void foo() {return;}\n" + "}") settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED2 settings.KEEP_SIMPLE_METHODS_IN_ONE_LINE = false settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = true settings.METHOD_BRACE_STYLE = CommonCodeStyleSettings.END_OF_LINE settings.CASE_STATEMENT_ON_NEW_LINE = false doTextTest("class Foo{\n" + "void foo() {\n" + "if(a) {return;}\n" + "for(a = 0; a < 10; a++) {return;}\n" + "switch(a) {case 1: return;}\n" + "do{return;} while (a);\n" + "while(a){return;}\n" + "try{return;} catch(Ex e){return;} finally{return;}\n" + "}\n" + "}", "class Foo {\n" + " void foo() {\n" + " if (a) {return;}\n" + " for (a = 0; a < 10; a++) {return;}\n" + " switch (a) {case 1: return;}\n" + " do {return;} while (a);\n" + " while (a) {return;}\n" + " try {return;} catch (Ex e) {return;} finally {return;}\n" + " }\n" + "}") } fun testSCR3062() { settings.KEEP_LINE_BREAKS = false settings.METHOD_CALL_CHAIN_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.CALL_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true settings.RIGHT_MARGIN = 80 settings.PREFER_PARAMETERS_WRAP = true doTextTest( "public class Foo { \n" + " public static void main() { \n" + " foo.foobelize().foobelize().foobelize().bar(\"The quick brown\", \n" + " \"fox jumped over\", \n" + " \"the lazy\", \"dog\"); \n" + " } \n" + "}", "public class Foo {\n" + " public static void main() {\n" + " foo.foobelize().foobelize().foobelize().bar(\"The quick brown\",\n" + " \"fox jumped over\",\n" + " \"the lazy\", \"dog\");\n" + " }\n" + "}") settings.PREFER_PARAMETERS_WRAP = false doTextTest( "public class Foo { \n" + " public static void main() { \n" + " foo.foobelize().foobelize().foobelize().bar(\"The quick brown\", \n" + " \"fox jumped over\", \n" + " \"the lazy\", \"dog\"); \n" + " } \n" + "}", "public class Foo {\n" + " public static void main() {\n" + " foo.foobelize().foobelize().foobelize()\n" + " .bar(\"The quick brown\", \"fox jumped over\", \"the lazy\", \"dog\");\n" + " }\n" + "}") } fun testSCR1658() { doTextTest("/** \n" + " * @author\tMike\n" + " */\n" + "public class Foo {\n" + "}", "/**\n" + " * @author Mike\n" + " */\n" + "public class Foo {\n" + "}") } fun testSCR1699() { doTextTest("class Test {\n" + " Test(String t1 , String t2) {\n" + " }\n" + "}", "class Test {\n" + " Test(String t1, String t2) {\n" + " }\n" + "}") } fun testSCR1700() { doTextTest("class Test {\n" + " Test(String t1 , String t2) {\n" + " }\n" + "}", "class Test {\n" + " Test(String t1, String t2) {\n" + " }\n" + "}") } fun testSCR1701() { settings.SPACE_WITHIN_METHOD_CALL_PARENTHESES = true settings.SPACE_WITHIN_METHOD_PARENTHESES = false settings.CALL_PARAMETERS_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP settings.CALL_PARAMETERS_LPAREN_ON_NEXT_LINE = true settings.CALL_PARAMETERS_RPAREN_ON_NEXT_LINE = true doTextTest("class Foo {\n" + " void foo() {\n" + " foo(a,b);" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " foo( a, b );\n" + " }\n" + "}") } fun testSCR1703() { settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE doTextTest("class Foo{\n" + " void foo() {\n" + " for (Object o : localizations) {\n" + " //do something \n" + " }\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " for (Object o : localizations)\n" + " {\n" + " //do something \n" + " }\n" + " }\n" + "}") } fun testSCR1804() { settings.ALIGN_MULTILINE_ASSIGNMENT = true doTextTest( "class Foo {\n" + " void foo() {\n" + " int i;\n" + " i = \n" + " 1 + 2;\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " int i;\n" + " i =\n" + " 1 + 2;\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo() {\n" + " i = j =\n" + " k = l = 1 + 2;\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " i = j =\n" + " k = l = 1 + 2;\n" + " }\n" + "}") } fun testSCR1795() { settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED doTextTest("public class Test {\n" + " public static void main(String[] args) {\n" + " do {\n" + " // ...\n" + " } while (true);\n" + " }\n" + "}", "public class Test {\n" + " public static void main(String[] args) {\n" + " do {\n" + " // ...\n" + " } while (true);\n" + " }\n" + "}") } fun testSCR1936() { settings.BLANK_LINES_AFTER_CLASS_HEADER = 4 doTextTest("/**\n" + " * Foo - test class\n" + " */\n" + "class Foo{\n" + "}", "/**\n" + " * Foo - test class\n" + " */\n" + "class Foo {\n" + "\n" + "\n" + "\n" + "\n" + "}") doTextTest("/**\n" + " * Foo - test class\n" + " */\n" + "class Foo{\n" + " int myFoo;\n" + "}", "/**\n" + " * Foo - test class\n" + " */\n" + "class Foo {\n" + "\n" + "\n" + "\n" + "\n" + " int myFoo;\n" + "}") } fun test1980() { settings.RIGHT_MARGIN = 144 settings.TERNARY_OPERATION_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM settings.METHOD_CALL_CHAIN_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.ALIGN_MULTILINE_TERNARY_OPERATION = true settings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE = true doTextTest("class Foo{\n" + " void foo() {\n" + "final VirtualFile moduleRoot = moduleRelativePath.equals(\"\") ? projectRootDirAfter : projectRootDirAfter.findFileByRelativePath(moduleRelativePath);\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " final VirtualFile moduleRoot = moduleRelativePath.equals(\"\")\n" + " ? projectRootDirAfter\n" + " : projectRootDirAfter.findFileByRelativePath(moduleRelativePath);\n" + " }\n" + "}") } fun testSCR2089() { doTextTest("class Test { \n" + " void test(int i) { \n" + " switch (i) { \n" + " case 1: { \n" + " int x = 0; \n" + " System.out.println(x); \n" + " } \n" + " break; \n" + " case 2: { \n" + " int y = 0; \n" + " System.out.println(y); \n" + " } \n" + " break; \n" + " } \n" + " } \n" + "}", "class Test {\n" + " void test(int i) {\n" + " switch (i) {\n" + " case 1: {\n" + " int x = 0;\n" + " System.out.println(x);\n" + " }\n" + " break;\n" + " case 2: {\n" + " int y = 0;\n" + " System.out.println(y);\n" + " }\n" + " break;\n" + " }\n" + " }\n" + "}") } fun testSCR2132() { settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED settings.ELSE_ON_NEW_LINE = true doTextTest("class Foo {\n" + " void foo() {\n" + " if (!rightPanel.isAncestorOf(validationPanel)) \n" + " {\n" + " splitPane.setDividerLocation(1.0);\n" + " }\n" + " else\n" + " {\n" + " splitPane.setDividerLocation(0.7);\n" + " }" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " if (!rightPanel.isAncestorOf(validationPanel)) {\n" + " splitPane.setDividerLocation(1.0);\n" + " }\n" + " else {\n" + " splitPane.setDividerLocation(0.7);\n" + " }\n" + " }\n" + "}") } fun testIDEADEV1047() { doTextTest("class Foo{\n" + "String field1\n" + ",\n" + "field2\n" + ";" + "}", "class Foo {\n" + " String field1,\n" + " field2;\n" + "}") doTextTest("class Foo{\n" + "void foo() {\n" + " String var1\n" + ",\n" + "var2\n" + ";\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " String var1,\n" + " var2;\n" + " }\n" + "}") } fun testIDEADEV1047_2() { doTextTest( "class Foo{\n" + "String field1\n" + ",\n" + "field2\n" + "; String field3;}", "class Foo {\n" + " String field1,\n" + " field2;\n" + " String field3;\n" + "}" ) } fun testSCR2241() { settings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED settings.SPECIAL_ELSE_IF_TREATMENT = true settings.ELSE_ON_NEW_LINE = true doTextTest("class Foo {\n" + " void foo() {\n" + " if (a)\n" + " {\n" + " }\n" + " else\n" + " {\n" + " }\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " if (a)\n" + " {\n" + " }\n" + " else\n" + " {\n" + " }\n" + " }\n" + "}") } @Throws(IncorrectOperationException::class) fun testSCRIDEA_4783() { settings.ASSIGNMENT_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.METHOD_CALL_CHAIN_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED settings.RIGHT_MARGIN = 80 doTextTest("class Foo{\n" + " void foo() {\n" + " final CommandRouterProtocolHandler protocolHandler = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " final CommandRouterProtocolHandler protocolHandler =\n" + " (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" + " }\n" + "}") doTextTest("class Foo{\n" + " void foo() {\n" + " protocolHandlerCommandRouterProtocolHandler = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " protocolHandlerCommandRouterProtocolHandler =\n" + " (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" + " }\n" + "}") doTextTest("class Foo{\n" + " final CommandRouterProtocolHandler protocolHandler = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" + "}", "class Foo {\n" + " final CommandRouterProtocolHandler protocolHandler =\n" + " (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" + "}") settings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE = true doTextTest("class Foo{\n" + " void foo() {\n" + " final CommandRouterProtocolHandler protocolHandler = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " final CommandRouterProtocolHandler protocolHandler\n" + " = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" + " }\n" + "}") doTextTest("class Foo{\n" + " void foo() {\n" + " protocolHandlerCommandRouterProtocolHandler = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " protocolHandlerCommandRouterProtocolHandler\n" + " = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" + " }\n" + "}") doTextTest("class Foo{\n" + " final CommandRouterProtocolHandler protocolHandler = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" + "}", "class Foo {\n" + " final CommandRouterProtocolHandler protocolHandler\n" + " = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" + "}") } @Throws(IncorrectOperationException::class) fun testSCRIDEADEV_2292() { settings.KEEP_CONTROL_STATEMENT_IN_ONE_LINE = false settings.WHILE_ON_NEW_LINE = true val facade = javaFacade val stored = LanguageLevelProjectExtension.getInstance(facade.project).languageLevel LanguageLevelProjectExtension.getInstance(facade.project).languageLevel = LanguageLevel.JDK_1_5 try { doTextTest("class Foo {\n" + " void foo() {\n" + " if (a) foo();\n" + " else bar();\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " if (a)\n" + " foo();\n" + " else\n" + " bar();\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo() {\n" + " for (int i = 0; i < 10; i++) foo();\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " for (int i = 0; i < 10; i++)\n" + " foo();\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo() {\n" + " for (int var : vars) foo();\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " for (int var : vars)\n" + " foo();\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo() {\n" + " do foo(); while (true);\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " do\n" + " foo();\n" + " while (true);\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo() {\n" + " while(true) foo();\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " while (true)\n" + " foo();\n" + " }\n" + "}") settings.KEEP_CONTROL_STATEMENT_IN_ONE_LINE = true settings.WHILE_ON_NEW_LINE = false doTextTest("class Foo {\n" + " void foo() {\n" + " if (a) foo();\n" + " else bar();\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " if (a) foo();\n" + " else bar();\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo() {\n" + " for (int i = 0; i < 10; i++) foo();\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " for (int i = 0; i < 10; i++) foo();\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo() {\n" + " for (int var : vars) foo();\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " for (int var : vars) foo();\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo() {\n" + " do foo(); while (true);\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " do foo(); while (true);\n" + " }\n" + "}") doTextTest("class Foo {\n" + " void foo() {\n" + " while(true) foo();\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " while (true) foo();\n" + " }\n" + "}") settings.RIGHT_MARGIN = 17 doTextTest("class Foo {\n" + " void foo() {\n" + " if (a) foo();\n" + " else bar();\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " if (a)\n" + " foo();\n" + " else\n" + " bar();\n" + " }\n" + "}") settings.RIGHT_MARGIN = 30 doTextTest("class Foo {\n" + " void foo() {\n" + " for (int i = 0; i < 10; i++) foo();\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " for (int i = 0; i < 10; i++)\n" + " foo();\n" + " }\n" + "}") settings.RIGHT_MARGIN = 32 doTextTest("class Foo {\n" + " void foo() {\n" + " for (int var : vars) foo();\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " for (int var : vars)\n" + " foo();\n" + " }\n" + "}") settings.RIGHT_MARGIN = 12 doTextTest("class Foo {\n" + " void foo() {\n" + " do foo(); while (true);\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " do\n" + " foo();\n" + " while (true);\n" + " }\n" + "}") settings.RIGHT_MARGIN = 23 doTextTest("class Foo {\n" + " void foo() {\n" + " while(true) foo();\n" + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + " while (true)\n" + " foo();\n" + " }\n" + "}") } finally { LanguageLevelProjectExtension.getInstance(facade.project).languageLevel = stored } } fun testSCR3115() { val indentOptions = settings.rootSettings.getIndentOptions(JavaFileType.INSTANCE) indentOptions.USE_TAB_CHARACTER = true indentOptions.SMART_TABS = true settings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION = true doTextTest("class Foo {\n" + "\tpublic void test(String[] args) {\n" + "\t\tfoo(new String[] {\n" + "\t\t\t\t\"1\",\n" + "\t\t \"2\",\n" + "\t\t \"3\"});\n" + "\t}\n" + "}", "class Foo {\n" + "\tpublic void test(String[] args) {\n" + "\t\tfoo(new String[]{\n" + "\t\t\t\t\"1\",\n" + "\t\t\t\t\"2\",\n" + "\t\t\t\t\"3\"});\n" + "\t}\n" + "}") } fun testIDEADEV_6239() { javaSettings.ENABLE_JAVADOC_FORMATTING = true doTextTest("public class Test {\n" + "\n" + " /**\n" + " * The s property.\n" + " *\n" + " * @deprecated don't use it\n" + " */\n" + " private String s;\n" + "}", "public class Test {\n" + "\n" + " /**\n" + " * The s property.\n" + " *\n" + " * @deprecated don't use it\n" + " */\n" + " private String s;\n" + "}") } @Throws(IncorrectOperationException::class) fun testIDEADEV_8755() { settings.KEEP_LINE_BREAKS = false doTextTest("class Foo {\n" + "void foo(){\n" + "System\n" + ".out\n" + ".println(\"Sleeping \" \n" + "+ thinkAboutItTime\n" + "+ \" seconds !\");" + "}\n" + "}", "class Foo {\n" + " void foo() {\n" + " System.out.println(\"Sleeping \" + thinkAboutItTime + \" seconds !\");\n" + " }\n" + "}") } @Throws(IncorrectOperationException::class) fun testIDEADEV_24168() { doTextTest( "class Foo {\n" + "@AnExampleMethod\n" + "public String\n" + "getMeAString()\n" + "throws AnException\n" + "{\n" + "\n" + "}\n" + "}", "class Foo {\n" + " @AnExampleMethod\n" + " public String\n" + " getMeAString()\n" + " throws AnException {\n" + "\n" + " }\n" + "}") } @Throws(IncorrectOperationException::class) fun testIDEADEV_2541() { myTextRange = TextRange(0, 15) doTextTest("/** @param q */\nclass Foo {\n}", "/**\n" + " * @param q\n" + " */\n" + "class Foo {\n" + "}") } @Throws(IncorrectOperationException::class) fun testIDEADEV_6434() { settings.ALIGN_MULTILINE_BINARY_OPERATION = true settings.ALIGN_MULTILINE_ASSIGNMENT = true doTextTest("class Foo {\n" + "void foo(){\n" + "return (interval1.getEndIndex() >= interval2.getStartIndex() &&\n" + " interval1.getStartIndex() <= interval2.getEndIndex()) ||\n" + " (interval2.getEndIndex() >= interval1.getStartIndex() &&\n" + " interval2.getStartIndex() <= interval1.getEndIndex());\n" + "}\n" + "}", "class Foo {\n" + " void foo() {\n" + " return (interval1.getEndIndex() >= interval2.getStartIndex() &&\n" + " interval1.getStartIndex() <= interval2.getEndIndex()) ||\n" + " (interval2.getEndIndex() >= interval1.getStartIndex() &&\n" + " interval2.getStartIndex() <= interval1.getEndIndex());\n" + " }\n" + "}") } @Throws(IncorrectOperationException::class) fun testIDEADEV_12836() { settings.SPECIAL_ELSE_IF_TREATMENT = true settings.RIGHT_MARGIN = 80 doTextTest("class Foo {\n" + "void foo(){\n" + "if (true){\n" + "} else if (\" \" != null) {\n" + "}\n" + "}\n" + "}", "class Foo {\n" + " void foo() {\n" + " if (true) {\n" + " } else if (\" \" != null) {\n" + " }\n" + " }\n" + "}") } /* public void testIDEADEV_26871() throws IncorrectOperationException { getSettings().getIndentOptions(JavaFileType.INSTANCE).CONTINUATION_INDENT_SIZE = 4; doTextTest("class Foo {\n" + "public void foo() {\n" + " BigDecimal1.ONE1\n" + " .add2(BigDecimal2.ONE2\n" + " .add3(BigDecimal3.ONE3\n" + " .add4(BigDecimal4.ONE4\n" + " .add5(BigDecimal5.ONE5))))\n" + "}\n" + "}", "class Foo {\n" + " public void foo() {\n" + " BigDecimal1.ONE1\n" + " .add2(BigDecimal2.ONE2\n" + " .add3(BigDecimal3.ONE3\n" + " .add4(BigDecimal4.ONE4\n" + " .add5(BigDecimal5.ONE5))))\n" + " }\n" + "}"); } */ @Throws(IncorrectOperationException::class) fun test23551() { doTextTest("public class Wrapping {\n" + " public static void sample() {\n" + " System.out.println(\".\" + File.separator + \"..\" + File.separator + \"some-directory-name\" + File.separator + \"more-file-name\");\n" + " }\n" + "}", "public class Wrapping {\n" + " public static void sample() {\n" + " System.out.println(\".\" + File.separator + \"..\" + File.separator + \"some-directory-name\" + File.separator + \"more-file-name\");\n" + " }\n" + "}") } /* public void testIDEADEV_26871_2() throws IncorrectOperationException { getSettings().getIndentOptions(JavaFileType.INSTANCE).CONTINUATION_INDENT_SIZE = 4; doTextTest("class Foo {\n" + "public void foo() {\n" + " BigDecimal1\n" + " .add2(BigDecimal2\n" + " .add3(BigDecimal3\n" + " .add4(BigDecimal4\n" + " .add5(BigDecimal5))))\n" + "}\n" + "}", "class Foo {\n" + " public void foo() {\n" + " BigDecimal1.ONE1\n" + " .add2(BigDecimal2.ONE2\n" + " .add3(BigDecimal3.ONE3\n" + " .add4(BigDecimal4.ONE4\n" + " .add5(BigDecimal5.ONE5))))\n" + " }\n" + "}"); } */ @Throws(IncorrectOperationException::class) fun testIDEADEV_23551() { settings.BINARY_OPERATION_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM settings.RIGHT_MARGIN = 60 doTextTest("public class Wrapping {\n" + "public static void sample() {\n" + "System.out.println(\".\" + File.separator + \"..\" + File.separator + \"some-directory-name\" + File.separator + \"more-file-name\");\n" + "}\n" + "}", "public class Wrapping {\n" + " public static void sample() {\n" + " System.out.println(\".\" +\n" + " File.separator +\n" + " \"..\" +\n" + " File.separator +\n" + " \"some-directory-name\" +\n" + " File.separator +\n" + " \"more-file-name\");\n" + " }\n" + "}") } @Throws(IncorrectOperationException::class) fun testIDEADEV_22967() { settings.METHOD_ANNOTATION_WRAP = CommonCodeStyleSettings.WRAP_ALWAYS doTextTest("public interface TestInterface {\n" + "\n" + " void empty();\n" + "\n" + " @Deprecated\n" + " void annotated();\n" + "\n" + " <T> void parametrized(T data);\n" + "\n" + " @Deprecated\n" + " <T> void parametrizedAnnotated(T data);\n" + "\n" + " @Deprecated\n" + " public <T> void publicParametrizedAnnotated(T data);\n" + "\n" + "}", "public interface TestInterface {\n" + "\n" + " void empty();\n" + "\n" + " @Deprecated\n" + " void annotated();\n" + "\n" + " <T> void parametrized(T data);\n" + "\n" + " @Deprecated\n" + " <T> void parametrizedAnnotated(T data);\n" + "\n" + " @Deprecated\n" + " public <T> void publicParametrizedAnnotated(T data);\n" + "\n" + "}") } @Throws(IncorrectOperationException::class) fun testIDEADEV_22967_2() { settings.METHOD_ANNOTATION_WRAP = CommonCodeStyleSettings.WRAP_ALWAYS doTextTest("public interface TestInterface {\n" + " @Deprecated\n" + " <T> void parametrizedAnnotated(T data);\n" + "}", "public interface TestInterface {\n" + " @Deprecated\n" + " <T> void parametrizedAnnotated(T data);\n" + "}") } fun testIDEA_54406() { doTextTest("public class Test1 {\n" + "void func() {\n" + "new Thread(new Runnable() {\n" + "public void run() {\n" + " // ...\n" + "}\n" + "}\n" + ")\n" + ";\n" + "}\n" + "}", "public class Test1 {\n" + " void func() {\n" + " new Thread(new Runnable() {\n" + " public void run() {\n" + " // ...\n" + " }\n" + " }\n" + " )\n" + " ;\n" + " }\n" + "}") } fun testCommaInMethodDeclParamsList() { settings.SPACE_AFTER_COMMA = true var before = "public class Test {\n" + " public static void act( int a , int b , int c , int d) {\n" + " act(1,2,3,4);\n" + " }\n" + "}\n" var after = "public class Test {\n" + " public static void act(int a, int b, int c, int d) {\n" + " act(1, 2, 3, 4);\n" + " }\n" + "}\n" doTextTest(before, after) settings.SPACE_AFTER_COMMA = false before = "public class Test {\n" + " public static void act( int a , int b , int c , int d) {\n" + " act(1 , 2 , 3 , 4);\n" + " }\n" + "}\n" after = "public class Test {\n" + " public static void act(int a,int b,int c,int d) {\n" + " act(1,2,3,4);\n" + " }\n" + "}\n" doTextTest(before, after) } fun testFormatterOnOffTags() { settings.rootSettings.FORMATTER_TAGS_ENABLED = true settings.IF_BRACE_FORCE = CommonCodeStyleSettings.FORCE_BRACES_ALWAYS doTest() } fun testFormatterOnOffTagsWithRegexp() { val settings = settings.rootSettings settings.FORMATTER_TAGS_ENABLED = true settings.FORMATTER_TAGS_ACCEPT_REGEXP = true settings.FORMATTER_OFF_TAG = "not.*format" settings.FORMATTER_ON_TAG = "end.*fragment" doTest() } fun testDoNotIndentNotSelectedStatement_AfterSelectedOne() { myTextRange = TextRange(0, 73) doTextTest( "class Test {\n" + " public static void main(String[] args) {\n" + " int a = 3;\n" + " System.out.println(\"AAA\");\n" + " }\n" + "}", "class Test {\n" + " public static void main(String[] args) {\n" + " int a = 3;\n" + " System.out.println(\"AAA\");\n" + " }\n" + "}" ) myTextRange = TextRange(0, 67) doTextTest( " import java.lang.Override;\n" + " import java.lang.Exception;\n" + " \n" + " class Foo {\n" + "}", "import java.lang.Override;\n" + "import java.lang.Exception;\n" + " \n" + " class Foo {\n" + "}" ) } fun testDetectableIndentOptions() { val original = "public class Main {\n" + "\tpublic void main() {\n" + "try {\n" + "\t\t\tSystem.out.println();\n" + "\t} catch (java.lang.Exception exception) {\n" + "\t\t\texception.printStackTrace();\n" + "\t}\n" + "}\n" + "}" // Enabled but full reformat (no detection) doTestWithDetectableIndentOptions( original, "public class Main {\n" + " public void main() {\n" + " try {\n" + " System.out.println();\n" + " } catch (java.lang.Exception exception) {\n" + " exception.printStackTrace();\n" + " }\n" + " }\n" + "}" ) // Reformat with a smaller text range (detection is on) myTextRange = TextRange(1, original.length) doTestWithDetectableIndentOptions( original, "public class Main {\n" + "\tpublic void main() {\n" + "\t\ttry {\n" + "\t\t\tSystem.out.println();\n" + "\t\t} catch (java.lang.Exception exception) {\n" + "\t\t\texception.printStackTrace();\n" + "\t\t}\n" + "\t}\n" + "}" ) } fun testKeepIndentsOnEmptyLines() { val indentOptions = settings.indentOptions assertNotNull(indentOptions) val original = "public class Main {\n" + " public int x;\n" + " \n" + " public int y;\n" + "\n" + " public void foo(boolean a, int x, int y, int z) {\n" + " do {\n" + " \n" + " if (x > 0) {\n" + " \n" + " } else if (x < 0) {\n" + " \n" + " int r;\n" + " }\n" + " }\n" + " while (y > 0);\n" + " }\n" + "}" indentOptions!!.KEEP_INDENTS_ON_EMPTY_LINES = false doTextTest( original, "public class Main {\n" + " public int x;\n" + "\n" + " public int y;\n" + "\n" + " public void foo(boolean a, int x, int y, int z) {\n" + " do {\n" + "\n" + " if (x > 0) {\n" + "\n" + " } else if (x < 0) {\n" + "\n" + " int r;\n" + " }\n" + " }\n" + " while (y > 0);\n" + " }\n" + "}" ) indentOptions.KEEP_INDENTS_ON_EMPTY_LINES = true doTextTest( original, "public class Main {\n" + " public int x;\n" + " \n" + " public int y;\n" + " \n" + " public void foo(boolean a, int x, int y, int z) {\n" + " do {\n" + " \n" + " if (x > 0) {\n" + " \n" + " } else if (x < 0) {\n" + " \n" + " int r;\n" + " }\n" + " }\n" + " while (y > 0);\n" + " }\n" + "}" ) } fun testIdea114862() { settings.rootSettings.FORMATTER_TAGS_ENABLED = true val indentOptions = settings.indentOptions assertNotNull(indentOptions) indentOptions!!.USE_TAB_CHARACTER = true doTextTest( "// @formatter:off \n" + "public class Test {\n" + " String foo;\n" + " String bar;\n" + "}", "// @formatter:off \n" + "public class Test {\n" + " String foo;\n" + " String bar;\n" + "}" ) } fun testIdea184461() { settings.rootSettings.FORMATTER_TAGS_ENABLED = true val indentOptions = settings.indentOptions assertNotNull(indentOptions) indentOptions!!.USE_TAB_CHARACTER = true doTextTest( "public class Test {\n" + "/* @formatter:off */\n" + " String foo;\n" + " String bar;\n" + "/* @formatter:on */\n\n" + " String abc;\n" + "}", "public class Test {\n" + "\t/* @formatter:off */\n" + " String foo;\n" + " String bar;\n" + "/* @formatter:on */\n\n" + "\tString abc;\n" + "}" ) } fun testReformatCodeWithErrorElementsWithoutAssertions() { doTextTest("class RedTest { \n\n\n\n\n\n\n\n " + "String [ ] [ ] test = { { \n\n\n\n\n { \"\"} \n\n\n\n\n }; " + "String [ ] [ ] test = { { \n\n\n\n\n { \"\"} \n\n\n\n\n }; " + " \n\n\n\n\n\n\n\n } ", "class RedTest {\n\n\n" + " String[][] test = {{\n\n\n" + " {\"\"}\n\n\n" + " };\n" + " String[][] test = {{\n\n\n" + " {\"\"}\n\n\n" + " };\n\n\n" + "} ") } fun testReformatPackageAnnotation() { doTextTest( "@ParametersAreNonnullByDefault package com.example;", "@ParametersAreNonnullByDefault\n" + "package com.example;" ) doTextTest( " @ParametersAreNonnullByDefault\n" + "package com.example;", "@ParametersAreNonnullByDefault\n" + "package com.example;" ) } fun testFinal_OnTheEndOfLine() { doMethodTest( "@SuppressWarnings(\"unchecked\") final\n" + "List<String> list = new ArrayList<String>();\n" + "new Runnable() {\n" + " @Override\n" + " public void run() {\n" + " list.clear();\n" + " }\n" + "};", "@SuppressWarnings(\"unchecked\") final List<String> list = new ArrayList<String>();\n" + "new Runnable() {\n" + " @Override\n" + " public void run() {\n" + " list.clear();\n" + " }\n" + "};" ) } fun testKeepTypeAnnotationNearType() { doTextTest( "import java.lang.annotation.ElementType;\n" + "import java.lang.annotation.Retention;\n" + "import java.lang.annotation.RetentionPolicy;\n" + "import java.lang.annotation.Target;\n" + "\n" + "@Target(value=ElementType.TYPE_USE)\n" + "@Retention(value= RetentionPolicy.RUNTIME)\n" + "public @interface X {}\n" + "class Q {\n" + " @Override\n" + " public @X List<Object> objects() {\n" + " return null;\n" + " }\n" + "}", "import java.lang.annotation.ElementType;\n" + "import java.lang.annotation.Retention;\n" + "import java.lang.annotation.RetentionPolicy;\n" + "import java.lang.annotation.Target;\n" + "\n" + "@Target(value = ElementType.TYPE_USE)\n" + "@Retention(value = RetentionPolicy.RUNTIME)\n" + "public @interface X {\n" + "}\n" + "\n" + "class Q {\n" + " @Override\n" + " public @X List<Object> objects() {\n" + " return null;\n" + " }\n" + "}" ) } fun testKeepSimpleSwitchInOneLine() { settings.CASE_STATEMENT_ON_NEW_LINE = false doMethodTest( "switch (b) {\n" + "case 1: case 2: break;\n" + "}", "switch (b) {\n" + " case 1: case 2: break;\n" + "}") } fun testExpandSwitch() { settings.CASE_STATEMENT_ON_NEW_LINE = false doMethodTest( "switch (b) {\n" + "case 1: { println(1); } case 2: break;\n" + "}", "switch (b) {\n" + " case 1: {\n" + " println(1);\n" + " }\n" + " case 2: break;\n" + "}") } fun testKeepBreakOnSameLine() { settings.CASE_STATEMENT_ON_NEW_LINE = false doMethodTest( "switch (b) {\n" + "case 1: case 2:\n" + "\n\n\n\n\n\n" + "break;\n" + "}", "switch (b) {\n" + " case 1: case 2:\n\n\n" + " break;\n" + "}") } fun testAnnotationAndFinalInsideParamList() { doClassTest( "public class Test {\n" + " void test(@Nullable final String childFallbackProvider) {\n" + " }\n" + "}", "public class Test {\n" + " void test(@Nullable final String childFallbackProvider) {\n" + " }\n" + "}" ) } fun testPreserveRbraceOnItsLine() { doClassTest( "class SomeTest {\n" + " @Test\n" + "}", "class SomeTest {\n" + " @Test\n" + "}" ) } fun testFormatCStyleCommentWithAsterisks() { doMethodTest( " for (Object o : new Object[]{}) {\n" + "/*\n" + " *\t\n" + " \t\t\t\t\t */\n" + " }\n", "for (Object o : new Object[]{}) {\n" + " /*\n" + " *\n" + " */\n" + "}\n" ) } fun testIdea183193() { doTextTest( "package de.tarent.bugreport;\n" + "\n" + " /*-\n" + " * This is supposed\n" + " * to be a copyright comment\n" + " * and thus not wrapped.\n" + " */\n" + "\n" + " /*\n" + " * This is supposed\n" + " * to be wrapped.\n" + " */\n" + "\n" + "/**\n" + " * This is JavaDoc.\n" + " */\n" + "public class IndentBugReport {\n" + "}", "package de.tarent.bugreport;\n" + "\n" + "/*-\n" + " * This is supposed\n" + " * to be a copyright comment\n" + " * and thus not wrapped.\n" + " */\n" + "\n" + "/*\n" + " * This is supposed\n" + " * to be wrapped.\n" + " */\n" + "\n" + "/**\n" + " * This is JavaDoc.\n" + " */\n" + "public class IndentBugReport {\n" + "}" ) } /** * See IDEA-98552, IDEA-175560 */ fun testParenthesesIndentation() { doTextTest( """ package com.company; import java.util.Arrays; import java.util.List; class Test { void foo(boolean bool1, boolean bool2) { List<String> list = Arrays.asList( "a", "b", "c" ); // IDEA-98552 for ( String s : list ) { System.out.println(s); } // IDEA-175560 if (bool1 && bool2 ) { // Indented at continuation indent level // do stuff } } } """, """ package com.company; import java.util.Arrays; import java.util.List; class Test { void foo(boolean bool1, boolean bool2) { List<String> list = Arrays.asList( "a", "b", "c" ); // IDEA-98552 for ( String s : list ) { System.out.println(s); } // IDEA-175560 if (bool1 && bool2 ) { // Indented at continuation indent level // do stuff } } } """ ) } fun testBlankLinesBeforeClassEnd () { settings.BLANK_LINES_BEFORE_CLASS_END = 2 doTextTest( """ public class Test { private int field1; private int field2; { field1 = 2; } public void test() { new Runnable() { public void run() { } }; } } """, """ public class Test { private int field1; private int field2; { field1 = 2; } public void test() { new Runnable() { public void run() { } }; } } """ ) } fun testBlankLinesBeforeClassEnd_afterField () { settings.BLANK_LINES_BEFORE_CLASS_END = 2 doTextTest( """ public class Test { private int field1; private int field2; } """, """ public class Test { private int field1; private int field2; } """ ) } fun testBlankLinesBeforeClassEnd_afterInnerClass () { settings.BLANK_LINES_BEFORE_CLASS_END = 2 doTextTest( """ public class Test { private class InnerTest { private int f; } } """, """ public class Test { private class InnerTest { private int f; } } """ ) } fun testSpacing() { doTextTest( "enum A{\n" + " B,\n" + " /** or like this */C();\n" + "}", "enum A {\n" + " B,\n" + " /**\n" + " * or like this\n" + " */\n" + " C();\n" + "}" ) } fun testIdea192024() { settings.apply{ RIGHT_MARGIN = 30 } doTextTest( """ public class Main { public static void main(String[] args) { int longCountVar = 0; do { System.out.println("Test"); longCountVar ++; } while(longCountVar <= 1000); } }""".trimIndent(), """ public class Main { public static void main(String[] args) { int longCountVar = 0; do { System.out.println("Test"); longCountVar++; } while (longCountVar <= 1000); } }""".trimIndent() ) } fun testIdeaIDEA203464() { settings.apply{ ENUM_CONSTANTS_WRAP = CommonCodeStyleSettings.WRAP_ALWAYS KEEP_LINE_BREAKS = false } doTextTest( """ /** * javadoc */ public enum EnumApplyChannel { C; public String method() { return null; } }""".trimIndent(), """ /** * javadoc */ public enum EnumApplyChannel { C; public String method() { return null; } }""".trimIndent() ) } fun testIdeaIDEA198408() { settings.apply{ ENUM_CONSTANTS_WRAP = CommonCodeStyleSettings.WRAP_ALWAYS KEEP_LINE_BREAKS = false } doTextTest( """ /** JavaDoc */ public enum LevelCode {HIGH(3), MEDIUM(2), LOW(1); private final int levelCode; LevelCode(int levelCode) { this.levelCode = levelCode; } }""".trimIndent(), """ /** * JavaDoc */ public enum LevelCode { HIGH(3), MEDIUM(2), LOW(1); private final int levelCode; LevelCode(int levelCode) { this.levelCode = levelCode; } }""".trimIndent() ) } fun testIdea195707() { settings.apply { CASE_STATEMENT_ON_NEW_LINE = true KEEP_MULTIPLE_EXPRESSIONS_IN_ONE_LINE = true } doTextTest( """ public enum RotationDirection { CLOCKWISE, COUNTERCLOCKWISE; public RotationDirection inverse() { switch(this) { case CLOCKWISE: return COUNTERCLOCKWISE; case COUNTERCLOCKWISE: return CLOCKWISE; } throw new IllegalArgumentException("Unknown " + getClass().getSimpleName() + ": " + this); } } """.trimIndent(), """ public enum RotationDirection { CLOCKWISE, COUNTERCLOCKWISE; public RotationDirection inverse() { switch (this) { case CLOCKWISE: return COUNTERCLOCKWISE; case COUNTERCLOCKWISE: return CLOCKWISE; } throw new IllegalArgumentException("Unknown " + getClass().getSimpleName() + ": " + this); } } """.trimIndent() ) } fun testIdea195707_1() { settings.apply { CASE_STATEMENT_ON_NEW_LINE = false KEEP_MULTIPLE_EXPRESSIONS_IN_ONE_LINE = true } doTextTest( """ public enum RotationDirection { CLOCKWISE, COUNTERCLOCKWISE; public RotationDirection inverse() { switch(this) { case CLOCKWISE: return COUNTERCLOCKWISE; case COUNTERCLOCKWISE: return CLOCKWISE; } throw new IllegalArgumentException("Unknown " + getClass().getSimpleName() + ": " + this); } } """.trimIndent(), """ public enum RotationDirection { CLOCKWISE, COUNTERCLOCKWISE; public RotationDirection inverse() { switch (this) { case CLOCKWISE: return COUNTERCLOCKWISE; case COUNTERCLOCKWISE: return CLOCKWISE; } throw new IllegalArgumentException("Unknown " + getClass().getSimpleName() + ": " + this); } } """.trimIndent() ) } fun testFormatterTagsDisabled() { settings.rootSettings.apply { FORMATTER_TAGS_ENABLED = false } doTextTest( """ package com.company; public class TestOne { // @formatter:off public void test (int x) { } // @formatter:on } """.trimIndent(), """ package com.company; public class TestOne { // @formatter:off public void test(int x) { } // @formatter:on } """.trimIndent() ) } fun testRecordHeaderLparenOnNewLine() { javaSettings.apply { NEW_LINE_AFTER_LPAREN_IN_RECORD_HEADER = true } doTextTest(""" record A(String s ) {} """.trimIndent(), """ record A( String s ) { } """.trimIndent()) } fun testRecordHeaderLparenNotOnNewLine() { javaSettings.apply { NEW_LINE_AFTER_LPAREN_IN_RECORD_HEADER = false } settings.KEEP_LINE_BREAKS = false doTextTest(""" record A(String s ) {} """.trimIndent(), """ record A(String s) { } """.trimIndent()) } fun testRecordHeaderRparenOnNewLine() { javaSettings.apply { RPAREN_ON_NEW_LINE_IN_RECORD_HEADER = true } doTextTest(""" record A(String s, String a) {} """.trimIndent(), """ record A(String s, String a ) { } """.trimIndent()) } fun testRecordHeaderRparenNotOnNewLine() { javaSettings.apply { RPAREN_ON_NEW_LINE_IN_RECORD_HEADER = false } settings.KEEP_LINE_BREAKS = false doTextTest(""" record A( String s, String a ) { } """.trimIndent(), """ record A(String s, String a) { } """.trimIndent()) } fun testRecordHeaderMultilineAlign() { javaSettings.apply { NEW_LINE_AFTER_LPAREN_IN_RECORD_HEADER = false ALIGN_MULTILINE_RECORDS = true } doTextTest(""" record A(String s, String a ) {} """.trimIndent(), """ record A(String s, String a ) { } """.trimIndent()) } fun testRecordHeaderNotMultilineAlign() { javaSettings.apply { NEW_LINE_AFTER_LPAREN_IN_RECORD_HEADER = false ALIGN_MULTILINE_RECORDS = false } doTextTest(""" record A(String s, String a ) {} """.trimIndent(), """ record A(String s, String a ) { } """.trimIndent()) } fun testInstanceofPatternWithGeneric() { doTextTest(""" class A{ void foo(Object x) { if (x instanceof List<String> a) {} } } """.trimIndent(), """ class A { void foo(Object x) { if (x instanceof List<String> a) { } } } """.trimIndent()) } fun testIdea154076() { doTextTest(""" public class Test { @SuppressWarnings("any") String suppressed = null; @SuppressWarnings("any") // comment String commented = null; void f() { @SuppressWarnings("any") String suppressed = null; @SuppressWarnings("any") // comment String commented = null; } }""".trimIndent(), """ public class Test { @SuppressWarnings("any") String suppressed = null; @SuppressWarnings("any") // comment String commented = null; void f() { @SuppressWarnings("any") String suppressed = null; @SuppressWarnings("any") // comment String commented = null; } }""".trimIndent() ) } fun testPermitsList() { settings.ALIGN_MULTILINE_EXTENDS_LIST = true doTextTest("sealed class A permits B, \n" + "C {}", "sealed class A permits B,\n" + " C {\n}") } fun testWrapPermitsList() { settings.RIGHT_MARGIN = 50 settings.EXTENDS_LIST_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM settings.EXTENDS_KEYWORD_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED doTextTest("sealed class ColtreDataProvider permits Provider, AgentEventListener, ParameterDataEventListener {\n}", "sealed class ColtreDataProvider permits Provider,\n" + " AgentEventListener,\n" + " ParameterDataEventListener {\n}") } fun testPermitsListWithPrecedingGeneric() { doTextTest(""" sealed class Simple permits B { } final class B extends Simple { } """.trimIndent(), """ sealed class Simple permits B { } final class B extends Simple { } """.trimIndent()) } fun testIdea250114() { doTextTest(""" @Deprecated // Comment class Test { } """.trimIndent(), """ @Deprecated // Comment class Test { } """.trimIndent()) } fun testIdea252167() { doTextTest(""" @Ann record R(String str) { } """.trimIndent(), """ @Ann record R(String str) { } """.trimIndent()) } fun testIdea153525() { settings.LAMBDA_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED doTextTest( """ public class Test { void foo () { bar (event ->{for (Listener l : listeners) { notify (); } }); } } """.trimIndent(), """ public class Test { void foo() { bar(event -> { for (Listener l : listeners) { notify(); } }); } } """.trimIndent() ) } }
apache-2.0
594c36ade114f99e04b8a24de8f31d2a
35.781015
259
0.405848
4.289233
false
true
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/search/declarationsSearch/overridersSearchUtils.kt
1
7306
// 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.search.declarationsSearch import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.FunctionalExpressionSearch import com.intellij.psi.search.searches.OverridingMethodsSearch import com.intellij.util.Processor import com.intellij.util.containers.ContainerUtil import org.jetbrains.kotlin.asJava.classes.KtFakeLightMethod import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.isOverridable import org.jetbrains.kotlin.idea.base.util.excludeKotlinSources import org.jetbrains.kotlin.idea.base.util.useScope import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.getDeepestSuperDeclarations import org.jetbrains.kotlin.idea.core.getDirectlyOverriddenDeclarations import org.jetbrains.kotlin.idea.refactoring.resolveToExpectedDescriptorIfPossible import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.idea.util.getTypeSubstitution import org.jetbrains.kotlin.idea.util.toSubstitutor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.util.findCallableMemberBySignature fun forEachKotlinOverride( ktClass: KtClass, members: List<KtNamedDeclaration>, scope: SearchScope, searchDeeply: Boolean, processor: (superMember: PsiElement, overridingMember: PsiElement) -> Boolean ): Boolean { val baseClassDescriptor = runReadAction { ktClass.unsafeResolveToDescriptor() as ClassDescriptor } val baseDescriptors = runReadAction { members.mapNotNull { it.unsafeResolveToDescriptor() as? CallableMemberDescriptor }.filter { it.isOverridable } } if (baseDescriptors.isEmpty()) return true HierarchySearchRequest(ktClass, scope, searchDeeply).searchInheritors().forEach(Processor { psiClass -> val inheritor = psiClass.unwrapped as? KtClassOrObject ?: return@Processor true runReadAction { val inheritorDescriptor = inheritor.unsafeResolveToDescriptor() as ClassDescriptor val substitutor = getTypeSubstitution(baseClassDescriptor.defaultType, inheritorDescriptor.defaultType)?.toSubstitutor() ?: return@runReadAction true baseDescriptors.asSequence() .mapNotNull { baseDescriptor -> val superMember = baseDescriptor.source.getPsi()!! val overridingDescriptor = (baseDescriptor.substitute(substitutor) as? CallableMemberDescriptor)?.let { memberDescriptor -> inheritorDescriptor.findCallableMemberBySignature(memberDescriptor) } overridingDescriptor?.source?.getPsi()?.let { overridingMember -> superMember to overridingMember } } .all { (superMember, overridingMember) -> processor(superMember, overridingMember) } } }) return true } fun PsiMethod.forEachImplementation( scope: SearchScope = runReadAction { useScope() }, processor: (PsiElement) -> Boolean ): Boolean = forEachOverridingMethod(scope, processor) && FunctionalExpressionSearch.search( this, scope.excludeKotlinSources(project) ).forEach(Processor { processor(it) }) fun PsiMethod.forEachOverridingMethod( scope: SearchScope = runReadAction { useScope() }, processor: (PsiMethod) -> Boolean ): Boolean { if (this !is KtFakeLightMethod) { if (!OverridingMethodsSearch.search( /* method = */ this, /* scope = */ runReadAction { scope.excludeKotlinSources(project) }, /* checkDeep = */ true, ).forEach(Processor { processor(it) }) ) return false } val ktMember = this.unwrapped as? KtNamedDeclaration ?: return true val ktClass = runReadAction { ktMember.containingClassOrObject as? KtClass } ?: return true return forEachKotlinOverride(ktClass, listOf(ktMember), scope, searchDeeply = true) { _, overrider -> val lightMethods = runReadAction { overrider.toPossiblyFakeLightMethods().distinctBy { it.unwrapped } } lightMethods.all { processor(it) } } } fun findDeepestSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> { return when (val element = method.unwrapped) { is PsiMethod -> element.findDeepestSuperMethods().toList() is KtCallableDeclaration -> { val descriptor = element.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return emptyList() descriptor.getDeepestSuperDeclarations(false).mapNotNull { it.source.getPsi() ?: DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, it) } } else -> emptyList() } } fun findSuperDescriptors(declaration: KtDeclaration, descriptor: DeclarationDescriptor): Sequence<DeclarationDescriptor> { val sequenceOfExpectedDescriptor = declaration.takeIf { it.hasActualModifier() } ?.resolveToExpectedDescriptorIfPossible() ?.let { sequenceOf(it) } .orEmpty() val superDescriptors = findSuperDescriptors(descriptor) return if (superDescriptors == null) sequenceOfExpectedDescriptor else superDescriptors + sequenceOfExpectedDescriptor } private fun findSuperDescriptors(descriptor: DeclarationDescriptor): Sequence<DeclarationDescriptor>? { val superDescriptors: Collection<DeclarationDescriptor> = when (descriptor) { is ClassDescriptor -> { val supertypes = descriptor.typeConstructor.supertypes val superclasses = supertypes.mapNotNull { type -> type.constructor.declarationDescriptor as? ClassDescriptor } ContainerUtil.removeDuplicates(superclasses) superclasses } is CallableMemberDescriptor -> descriptor.getDirectlyOverriddenDeclarations() else -> return null } return superDescriptors.asSequence().filterNot { it is ClassDescriptor && KotlinBuiltIns.isAny(it) } } fun findSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> { return when (val element = method.unwrapped) { is PsiMethod -> element.findSuperMethods().toList() is KtCallableDeclaration -> { val descriptor = element.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return emptyList() descriptor.getDirectlyOverriddenDeclarations().mapNotNull { it.source.getPsi() ?: DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, it) } } else -> emptyList() } }
apache-2.0
9dbd86d067b7e12e5991f3c883c2cdc0
44.949686
136
0.733644
5.611367
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/InternalAbi.kt
2
3639
/* * Copyright 2010-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.kotlin.backend.konan import org.jetbrains.kotlin.backend.common.ir.addChild import org.jetbrains.kotlin.backend.konan.descriptors.synthesizedName import org.jetbrains.kotlin.backend.konan.llvm.llvmSymbolOrigin import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.impl.IrModuleFragmentImpl import org.jetbrains.kotlin.ir.util.NaiveSourceBasedFileEntryImpl import org.jetbrains.kotlin.ir.util.addFile import org.jetbrains.kotlin.ir.util.fqNameForIrSerialization import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name /** * Sometimes we need to reference symbols that are not declared in metadata. * For example, symbol might be declared during lowering. * In case of compiler caches, this means that it is not accessible as Lazy IR * and we have to explicitly add an external declaration. */ internal class InternalAbi(private val context: Context) { /** * Files that stores all internal ABI declarations. * We use per-module files so that global initializer will be stored * in the appropriate modules. * * We have to store such declarations in top-level to avoid mangling that * makes referencing harder. * A bit better solution is to add files with proper packages, but it is impossible * during FileLowering (hello, ConcurrentModificationException). */ private lateinit var internalAbiFiles: Map<ModuleDescriptor, IrFile> /** * Representation of ABI files from external modules. */ private val externalAbiFiles = mutableMapOf<ModuleDescriptor, IrFile>() fun init(modules: List<IrModuleFragment>) { internalAbiFiles = modules.associate { it.descriptor to createAbiFile(it) } } private fun createAbiFile(module: IrModuleFragment): IrFile = module.addFile(NaiveSourceBasedFileEntryImpl("internal"), FqName("kotlin.native.caches.abi")) /** * Adds external [function] from [module] to a list of external references. */ fun reference(function: IrFunction, module: ModuleDescriptor) { assert(function.isExternal) { "Function that represents external ABI should be marked as external" } context.llvmImports.add(module.llvmSymbolOrigin) externalAbiFiles.getOrPut(module) { createAbiFile(IrModuleFragmentImpl(module, context.irBuiltIns)) }.addChild(function) } /** * Adds [function] to a list of [module]'s publicly available symbols. */ fun declare(function: IrFunction, module: ModuleDescriptor) { internalAbiFiles.getValue(module).addChild(function) } companion object { /** * Allows to distinguish external declarations to internal ABI. */ val INTERNAL_ABI_ORIGIN = object : IrDeclarationOriginImpl("INTERNAL_ABI") {} fun getCompanionObjectAccessorName(companion: IrClass): Name = getMangledNameFor("globalAccessor", companion) fun getEnumValuesAccessorName(enum: IrClass): Name = getMangledNameFor("getValues", enum) /** * Generate name for declaration that will be a part of internal ABI. */ private fun getMangledNameFor(declarationName: String, parent: IrDeclarationParent): Name { val prefix = parent.fqNameForIrSerialization return "$prefix.$declarationName".synthesizedName } } }
apache-2.0
c88fcd6eb60ff4631fb477bfd9fa9051
40.363636
108
0.721627
4.713731
false
false
false
false
jwren/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/kdoc/IdeKDocLinkResolutionService.kt
1
6969
// 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.kdoc import com.intellij.openapi.project.Project import com.intellij.psi.impl.java.stubs.index.JavaMethodNameIndex import com.intellij.psi.impl.java.stubs.index.JavaShortClassNameIndex import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMethodDescriptor import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.stubindex.* import org.jetbrains.kotlin.incremental.components.LookupLocation import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.isChildOf import org.jetbrains.kotlin.name.isOneSegmentFQN import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.utils.Printer class IdeKDocLinkResolutionService(val project: Project) : KDocLinkResolutionService { override fun resolveKDocLink( context: BindingContext, fromDescriptor: DeclarationDescriptor, resolutionFacade: ResolutionFacade, qualifiedName: List<String> ): Collection<DeclarationDescriptor> { val scope = KotlinSourceFilterScope.projectAndLibrariesSources(GlobalSearchScope.projectScope(project), project) val shortName = qualifiedName.lastOrNull() ?: return emptyList() val targetFqName = FqName.fromSegments(qualifiedName) val functions = KotlinFunctionShortNameIndex.get(shortName, project, scope).asSequence() val classes = KotlinClassShortNameIndex.get(shortName, project, scope).asSequence() val descriptors = (functions + classes).filter { it.fqName == targetFqName } .map { it.unsafeResolveToDescriptor(BodyResolveMode.PARTIAL) } // TODO Filter out not visible due dependencies config descriptors .toList() if (descriptors.isNotEmpty()) return descriptors val javaClasses = JavaShortClassNameIndex.getInstance().get(shortName, project, scope).asSequence() .filter { it.getKotlinFqName() == targetFqName } .mapNotNull { it.getJavaClassDescriptor() } .toList() if (javaClasses.isNotEmpty()) { return javaClasses } val javaFunctions = JavaMethodNameIndex.getInstance().get(shortName, project, scope).asSequence() .filter { it.getKotlinFqName() == targetFqName } .mapNotNull { it.getJavaMethodDescriptor() } .toList() if (javaFunctions.isNotEmpty()) { return javaFunctions } if (!targetFqName.isRoot && PackageIndexUtil.packageExists(targetFqName, scope)) return listOf(GlobalSyntheticPackageViewDescriptor(targetFqName, project, scope)) return emptyList() } } private fun shouldNotBeCalled(): Nothing = throw UnsupportedOperationException("Synthetic PVD for KDoc link resolution") private class GlobalSyntheticPackageViewDescriptor( override val fqName: FqName, private val project: Project, private val scope: GlobalSearchScope ) : PackageViewDescriptor { override fun getContainingDeclaration(): PackageViewDescriptor? = if (fqName.isOneSegmentFQN()) null else GlobalSyntheticPackageViewDescriptor(fqName.parent(), project, scope) override val memberScope: MemberScope = object : MemberScope { override fun getContributedVariables(name: Name, location: LookupLocation): Collection<PropertyDescriptor> = shouldNotBeCalled() override fun getContributedFunctions(name: Name, location: LookupLocation): Collection<SimpleFunctionDescriptor> = shouldNotBeCalled() override fun getFunctionNames(): Set<Name> = shouldNotBeCalled() override fun getVariableNames(): Set<Name> = shouldNotBeCalled() override fun getClassifierNames(): Set<Name> = shouldNotBeCalled() override fun getContributedClassifier(name: Name, location: LookupLocation): ClassifierDescriptor? = shouldNotBeCalled() override fun printScopeStructure(p: Printer) { p.printIndent() p.print("GlobalSyntheticPackageViewDescriptorMemberScope (INDEX)") } fun getClassesByNameFilter(nameFilter: (Name) -> Boolean) = KotlinFullClassNameIndex .getAllKeys(project) .asSequence() .filter { it.startsWith(fqName.asString()) } .map(::FqName) .filter { it.isChildOf(fqName) } .filter { nameFilter(it.shortName()) } .flatMap { KotlinFullClassNameIndex.get(it.asString(), project, scope).asSequence() } .map { it.resolveToDescriptorIfAny() } fun getFunctionsByNameFilter(nameFilter: (Name) -> Boolean) = KotlinTopLevelFunctionFqnNameIndex .getAllKeys(project) .asSequence() .filter { it.startsWith(fqName.asString()) } .map(::FqName) .filter { it.isChildOf(fqName) } .filter { nameFilter(it.shortName()) } .flatMap { KotlinTopLevelFunctionFqnNameIndex.get(it.asString(), project, scope).asSequence() } .map { it.resolveToDescriptorIfAny() as? DeclarationDescriptor } fun getSubpackages(nameFilter: (Name) -> Boolean) = PackageIndexUtil.getSubPackageFqNames(fqName, scope, nameFilter) .map { GlobalSyntheticPackageViewDescriptor(it, project, scope) } override fun getContributedDescriptors( kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean ): Collection<DeclarationDescriptor> = (getClassesByNameFilter(nameFilter) + getFunctionsByNameFilter(nameFilter) + getSubpackages(nameFilter) ).filterNotNull().toList() } override val module: ModuleDescriptor get() = shouldNotBeCalled() override val fragments: List<PackageFragmentDescriptor> get() = shouldNotBeCalled() override fun getOriginal() = this override fun getName(): Name = fqName.shortName() override fun <R : Any?, D : Any?> accept(visitor: DeclarationDescriptorVisitor<R, D>?, data: D): R = shouldNotBeCalled() override fun acceptVoid(visitor: DeclarationDescriptorVisitor<Void, Void>?) = shouldNotBeCalled() override val annotations = Annotations.EMPTY }
apache-2.0
9e3bacd8eb664149a0e00dbff3f4ff6a
45.152318
141
0.720476
5.327982
false
false
false
false
jwren/intellij-community
tools/intellij.ide.starter/testSrc/com/intellij/ide/starter/tests/examples/data/IdeaCases.kt
2
785
package com.intellij.ide.starter.tests.examples.data import com.intellij.ide.starter.data.TestCaseTemplate import com.intellij.ide.starter.models.IdeProduct import com.intellij.ide.starter.project.ProjectInfo import kotlin.io.path.div object IdeaCases : TestCaseTemplate(IdeProduct.IU) { val GradleJitPackSimple = getTemplate().withProject( ProjectInfo( testProjectURL = "https://github.com/jitpack/gradle-simple/archive/refs/heads/master.zip", testProjectImageRelPath = { it / "gradle-simple-master" } ) ) val IntelliJCommunityProject = getTemplate().withProject( ProjectInfo( testProjectURL = "https://github.com/JetBrains/intellij-community/archive/master.zip", testProjectImageRelPath = { it / "intellij-community-master" } ) ) }
apache-2.0
997d9704d67b2ddb53c00b02c4762432
33.173913
96
0.75414
3.905473
false
true
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/block/copy/remote/RemoteBlockCopyFactory.kt
2
1749
package com.github.kerubistan.kerub.planner.steps.storage.block.copy.remote import com.github.kerubistan.kerub.model.dynamic.VirtualStorageBlockDeviceAllocation import com.github.kerubistan.kerub.model.expectations.CloneOfStorageExpectation import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.steps.storage.block.copy.AbstractBlockCopyFactory import com.github.kerubistan.kerub.utils.contains import io.github.kerubistan.kroki.collections.concat object RemoteBlockCopyFactory : AbstractBlockCopyFactory<RemoteBlockCopy>() { override fun produce(state: OperationalState): List<RemoteBlockCopy> = state.index.storageCloneRequirement.map { targetStorage -> val cloneOfStorageExpectation = targetStorage.stat.expectations.filterIsInstance<CloneOfStorageExpectation>().single() val sourceStorage = state.vStorage.getValue(cloneOfStorageExpectation.sourceStorageId) val unallocatedState = createUnallocatedState(state, targetStorage) allocationFactories.map { factory -> factory.produce(unallocatedState).map { allocationStep -> sourceStorage.dynamic?.allocations?.mapNotNull { sourceAllocation -> val sourceHost = state.hosts.getValue(sourceAllocation.hostId) if (sourceAllocation is VirtualStorageBlockDeviceAllocation && allocationStep.host in state.index.connectionTargets[sourceHost.id]) { RemoteBlockCopy( sourceHost = sourceHost.stat, targetDevice = targetStorage.stat, allocationStep = allocationStep, sourceDevice = sourceStorage.stat, sourceAllocation = sourceAllocation ) } else null } } } }.concat().concat().filterNotNull().concat() }
apache-2.0
e23c01b6ffac3e49e1146974d0327f2f
43.871795
92
0.770726
4.765668
false
false
false
false
jwren/intellij-community
plugins/devkit/devkit-tests/src/org/jetbrains/idea/devkit/IdePluginModuleBuilderTest.kt
1
6671
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.devkit import com.intellij.ide.starters.local.StarterModuleBuilder.Companion.setupTestModule import com.intellij.ide.starters.shared.JAVA_STARTER_LANGUAGE import com.intellij.ide.starters.shared.KOTLIN_STARTER_LANGUAGE import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase.JAVA_11 import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase4 import org.jetbrains.idea.devkit.module.IdePluginModuleBuilder import org.jetbrains.idea.devkit.module.IdePluginModuleBuilder.PluginType import org.junit.Assert.assertFalse import org.junit.Test class IdePluginModuleBuilderTest : LightJavaCodeInsightFixtureTestCase4(JAVA_11) { @Test fun pluginJavaProject() { IdePluginModuleBuilder().setupTestModule(fixture.module) { language = JAVA_STARTER_LANGUAGE isCreatingNewProject = true } fixture.configureFromTempProjectFile("build.gradle.kts") val buildGradleText = fixture.editor.document.text assertFalse("build.gradle.kts contains unprocessed VTL directives", buildGradleText.contains("\${context")) assertFalse("build.gradle.kts contains kotlin in Java project", buildGradleText.contains("kotlin")) expectFile("src/main/resources/META-INF/plugin.xml", PLUGIN_XML) expectFile("settings.gradle.kts", """ rootProject.name = "demo" """.trimIndent()) } @Test fun pluginKotlinProject() { IdePluginModuleBuilder().setupTestModule(fixture.module) { language = KOTLIN_STARTER_LANGUAGE isCreatingNewProject = true } fixture.configureFromTempProjectFile("build.gradle.kts") val buildGradleText = fixture.editor.document.text assertFalse("build.gradle.kts contains unprocessed VTL directives", buildGradleText.contains("\${context")) expectFile("src/main/resources/META-INF/plugin.xml", PLUGIN_XML) expectFile("settings.gradle.kts", """ rootProject.name = "demo" """.trimIndent()) } @Test fun themeProject() { val builder = IdePluginModuleBuilder() builder.setPluginType(PluginType.THEME) builder.setupTestModule(fixture.module) { language = JAVA_STARTER_LANGUAGE isCreatingNewProject = true } expectFile("resources/META-INF/plugin.xml", THEME_PLUGIN_XML) expectFile("resources/theme/demo.theme.json", THEME_JSON) } private val PLUGIN_XML: String = """ <!-- Plugin Configuration File. Read more: https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html --> <idea-plugin> <!-- Unique identifier of the plugin. It should be FQN. It cannot be changed between the plugin versions. --> <id>com.example.demo</id> <!-- Public plugin name should be written in Title Case. Guidelines: https://plugins.jetbrains.com/docs/marketplace/plugin-overview-page.html#plugin-name --> <name>Demo</name> <!-- A displayed Vendor name or Organization ID displayed on the Plugins Page. --> <vendor email="[email protected]" url="https://www.yourcompany.com">YourCompany</vendor> <!-- Description of the plugin displayed on the Plugin Page and IDE Plugin Manager. Simple HTML elements (text formatting, paragraphs, and lists) can be added inside of <![CDATA[ ]]> tag. Guidelines: https://plugins.jetbrains.com/docs/marketplace/plugin-overview-page.html#plugin-description --> <description><![CDATA[ Enter short description for your plugin here.<br> <em>most HTML tags may be used</em> ]]></description> <!-- Product and plugin compatibility requirements. Read more: https://plugins.jetbrains.com/docs/intellij/plugin-compatibility.html --> <depends>com.intellij.modules.platform</depends> <!-- Extension points defined by the plugin. Read more: https://plugins.jetbrains.com/docs/intellij/plugin-extension-points.html --> <extensions defaultExtensionNs="com.intellij"> </extensions> </idea-plugin> """.trimIndent() private val THEME_PLUGIN_XML: String = """ <!-- Plugin Configuration File. Read more: https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html --> <idea-plugin> <!-- Unique identifier of the plugin. It should be FQN. It cannot be changed between the plugin versions. --> <id>demo</id> <version>1.0.0</version> <!-- Public plugin name should be written in Title Case. Guidelines: https://plugins.jetbrains.com/docs/marketplace/plugin-overview-page.html#plugin-name --> <name>Demo</name> <category>UI</category> <!-- A displayed Vendor name or Organization ID displayed on the Plugins Page. --> <vendor email="[email protected]" url="https://www.yourcompany.com">YourCompany</vendor> <idea-version since-build="212" until-build="222.*"/> <!-- Description of the plugin displayed on the Plugin Page and IDE Plugin Manager. Simple HTML elements (text formatting, paragraphs, and lists) can be added inside of <![CDATA[ ]]> tag. Guidelines: https://plugins.jetbrains.com/docs/marketplace/plugin-overview-page.html#plugin-description --> <description><![CDATA[ Enter short description for your theme here.<br> <em>most HTML tags may be used</em> ]]></description> <!-- Short summary of new features and bugfixes in the latest plugin version. Displayed on the Plugin Page and IDE Plugin Manager. Simple HTML elements can be included between <![CDATA[ ]]> tags. --> <change-notes><![CDATA[ Initial release of the theme. ]]></change-notes> <!-- Product and plugin compatibility requirements. Read more: https://plugins.jetbrains.com/docs/intellij/plugin-compatibility.html --> <depends>com.intellij.modules.platform</depends> <extensions defaultExtensionNs="com.intellij"> <themeProvider id="demo" path="/theme/demo.theme.json"/> </extensions> </idea-plugin> """.trimIndent() private val THEME_JSON: String = """ { "name": "Demo", "author": "YourCompany", "dark": true, "colors": { "primaryRed": "#821010" }, "ui": { "Button.background": "primaryRed" } } """.trimIndent() private fun expectFile(path: String, content: String) { fixture.configureFromTempProjectFile(path) fixture.checkResult(content) } }
apache-2.0
81e492d7ebbb2b3f6f613ff5cf208309
40.7
135
0.687303
4.50135
false
true
false
false
smmribeiro/intellij-community
plugins/editorconfig/test/org/editorconfig/mock/EditorConfigMockLogger.kt
12
1708
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.mock import com.intellij.openapi.diagnostic.Logger import org.apache.log4j.Level import org.jetbrains.annotations.TestOnly import org.junit.Assert.assertEquals @TestOnly class EditorConfigMockLogger : Logger() { private var lastMessage: String? = null private var debugCalls = 0 private var infoCalls = 0 private var warnCalls = 0 private var errorCalls = 0 fun assertCallNumbers(debugCalls: Int = 0, infoCalls: Int = 0, warnCalls: Int = 0, errorCalls: Int = 0) { assertEquals(debugCalls, this.debugCalls) assertEquals(infoCalls, this.infoCalls) assertEquals(warnCalls, this.warnCalls) assertEquals(errorCalls, this.errorCalls) } fun assertLastMessage(message: String?) { assertEquals(message, lastMessage) } override fun isDebugEnabled(): Boolean = true override fun debug(message: String?) { debugCalls += 1 lastMessage = message } override fun debug(t: Throwable?) { debugCalls += 1 } override fun debug(message: String?, t: Throwable?) { debugCalls += 1 lastMessage = message } override fun info(message: String?) { infoCalls += 1 lastMessage = message } override fun info(message: String?, t: Throwable?) { infoCalls += 1 lastMessage = message } override fun warn(message: String?, t: Throwable?) { warnCalls += 1 lastMessage = message } override fun error(message: String?, t: Throwable?, vararg details: String?) { errorCalls += 1 lastMessage = message } override fun setLevel(level: Level) {} }
apache-2.0
b0f465056f3601434510ffc5b9bd9693
23.753623
140
0.703747
4.086124
false
false
false
false
zielu/GitToolBox
src/main/kotlin/zielu/gittoolbox/blame/calculator/persistence/FileBlameState.kt
1
368
package zielu.gittoolbox.blame.calculator.persistence import com.intellij.util.xmlb.annotations.XCollection internal data class FileBlameState( var accessTimestamp: Long = 0, var revision: BlameRevisionState = BlameRevisionState(), @XCollection( propertyElementName = "lines", style = XCollection.Style.v2 ) var lines: List<LineState> = listOf() )
apache-2.0
eb50ec52ba66954cd04085d8a12ee66f
27.307692
58
0.763587
4.229885
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/actions/persistence/ActionsEventLogGroup.kt
1
2513
// 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.internal.statistic.collectors.fus.actions.persistence import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.* import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector class ActionsEventLogGroup : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP companion object { const val ACTION_FINISHED_EVENT_ID = "action.finished" @JvmField val GROUP = EventLogGroup("actions", 66) @JvmField val ACTION_ID = EventFields.StringValidatedByCustomRule("action_id", "action") @JvmField val ACTION_CLASS = EventFields.StringValidatedByCustomRule("class", "class_name") @JvmField val ACTION_PARENT = EventFields.StringValidatedByCustomRule("parent", "class_name") @JvmField val TOGGLE_ACTION = EventFields.Boolean("enable") @JvmField val CONTEXT_MENU = EventFields.Boolean("context_menu") @JvmField val DUMB_START = EventFields.Boolean("dumb_start") @JvmField val DUMB = EventFields.Boolean("dumb") @JvmField val RESULT_TYPE = EventFields.String("type", arrayListOf("ignored", "performed", "failed", "unknown")) @JvmField val ERROR = EventFields.Class("error") @JvmField val RESULT = ObjectEventField("result", RESULT_TYPE, ERROR) @JvmField val ADDITIONAL = EventFields.createAdditionalDataField(GROUP.id, ACTION_FINISHED_EVENT_ID) @JvmField val ACTION_FINISHED = registerActionEvent( GROUP, ACTION_FINISHED_EVENT_ID, EventFields.StartTime, ADDITIONAL, EventFields.Language, EventFields.DurationMs, DUMB_START, RESULT ) @JvmStatic fun registerActionEvent(group: EventLogGroup, eventId: String, vararg extraFields: EventField<*>): VarargEventId { return group.registerVarargEvent( eventId, EventFields.PluginInfoFromInstance, EventFields.InputEvent, EventFields.ActionPlace, EventFields.CurrentFile, TOGGLE_ACTION, CONTEXT_MENU, DUMB, ACTION_ID, ACTION_CLASS, ACTION_PARENT, *extraFields ) } @JvmField val CUSTOM_ACTION_INVOKED = GROUP.registerEvent( "custom.action.invoked", EventFields.StringValidatedByCustomRule("action_id", "action"), EventFields.InputEvent) } }
apache-2.0
63150af375a351b0c65ebc960d7311e8
30.822785
140
0.714286
4.714822
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/uast/uast-kotlin-idea/src/org/jetbrains/uast/kotlin/generate/KotlinUastCodeGenerationPlugin.kt
1
21590
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin.generate import com.intellij.lang.Language import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.resolveToKotlinType import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.uast.* import org.jetbrains.uast.generate.UParameterInfo import org.jetbrains.uast.generate.UastCodeGenerationPlugin import org.jetbrains.uast.generate.UastElementFactory import org.jetbrains.uast.kotlin.* import org.jetbrains.uast.kotlin.internal.KotlinFakeUElement import org.jetbrains.uast.kotlin.internal.toSourcePsiFakeAware class KotlinUastCodeGenerationPlugin : UastCodeGenerationPlugin { override val language: Language get() = KotlinLanguage.INSTANCE override fun getElementFactory(project: Project): UastElementFactory = KotlinUastElementFactory(project) override fun <T : UElement> replace(oldElement: UElement, newElement: T, elementType: Class<T>): T? { val oldPsi = oldElement.toSourcePsiFakeAware().singleOrNull() ?: return null val newPsi = newElement.sourcePsi?.let { when { it is KtCallExpression && it.parent is KtQualifiedExpression -> it.parent else -> it } } ?: return null val psiFactory = KtPsiFactory(oldPsi.project) val oldParentPsi = oldPsi.parent val (updOldPsi, updNewPsi) = when { oldParentPsi is KtStringTemplateExpression && oldParentPsi.entries.size == 1 -> oldParentPsi to newPsi oldPsi is KtStringTemplateEntry && newPsi !is KtStringTemplateEntry && newPsi is KtExpression -> oldPsi to psiFactory.createBlockStringTemplateEntry(newPsi) oldPsi is KtBlockExpression && newPsi is KtBlockExpression -> { if (!hasBraces(oldPsi) && hasBraces(newPsi)) { oldPsi to psiFactory.createLambdaExpression("none", newPsi.statements.joinToString("\n") { "println()" }).bodyExpression!!.also { it.statements.zip(newPsi.statements).forEach { it.first.replace(it.second) } } } else oldPsi to newPsi } else -> oldPsi to newPsi } val replaced = updOldPsi.replace(updNewPsi)?.safeAs<KtElement>()?.let { ShortenReferences.DEFAULT.process(it) } return when { newElement.sourcePsi is KtCallExpression && replaced is KtQualifiedExpression -> replaced.selectorExpression else -> replaced }?.toUElementOfExpectedTypes(elementType) } } private fun hasBraces(oldPsi: KtBlockExpression): Boolean = oldPsi.lBrace != null && oldPsi.rBrace != null class KotlinUastElementFactory(project: Project) : UastElementFactory { private val psiFactory = KtPsiFactory(project) override fun createQualifiedReference(qualifiedName: String, context: PsiElement?): UQualifiedReferenceExpression? { return psiFactory.createExpression(qualifiedName).let { when (it) { is KtDotQualifiedExpression -> KotlinUQualifiedReferenceExpression(it, null) is KtSafeQualifiedExpression -> KotlinUSafeQualifiedExpression(it, null) else -> null } } } override fun createCallExpression( receiver: UExpression?, methodName: String, parameters: List<UExpression>, expectedReturnType: PsiType?, kind: UastCallKind, context: PsiElement? ): UCallExpression? { if (kind != UastCallKind.METHOD_CALL) return null val name = methodName.quoteIfNeeded() val methodCall = psiFactory.createExpression( buildString { if (receiver != null) { append("a") receiver.sourcePsi?.nextSibling.safeAs<PsiWhiteSpace>()?.let { whitespaces -> append(whitespaces.text) } append(".") } append(name) append("()") } ).getPossiblyQualifiedCallExpression() ?: return null if (receiver != null) { methodCall.parent.safeAs<KtDotQualifiedExpression>()?.receiverExpression?.replace(wrapULiteral(receiver).sourcePsi!!) } val valueArgumentList = methodCall.valueArgumentList for (parameter in parameters) { valueArgumentList?.addArgument(psiFactory.createArgument(wrapULiteral(parameter).sourcePsi as KtExpression)) } if (context !is KtElement) return KotlinUFunctionCallExpression(methodCall, null) val analyzableMethodCall = psiFactory.getAnalyzableMethodCall(methodCall, context) if (analyzableMethodCall.canMoveLambdaOutsideParentheses()) { analyzableMethodCall.moveFunctionLiteralOutsideParentheses() } if (expectedReturnType == null) return KotlinUFunctionCallExpression(analyzableMethodCall, null) val methodCallPsiType = KotlinUFunctionCallExpression(analyzableMethodCall, null).getExpressionType() if (methodCallPsiType == null || !expectedReturnType.isAssignableFrom(GenericsUtil.eliminateWildcards(methodCallPsiType))) { val typeParams = (context as? KtElement)?.let { kontext -> val resolutionFacade = kontext.getResolutionFacade() (expectedReturnType as? PsiClassType)?.parameters?.map { it.resolveToKotlinType(resolutionFacade) } } if (typeParams == null) return KotlinUFunctionCallExpression(analyzableMethodCall, null) for (typeParam in typeParams) { val typeParameter = psiFactory.createTypeArgument(typeParam.fqName?.asString().orEmpty()) analyzableMethodCall.addTypeArgument(typeParameter) } return KotlinUFunctionCallExpression(analyzableMethodCall, null) } return KotlinUFunctionCallExpression(analyzableMethodCall, null) } private fun KtPsiFactory.getAnalyzableMethodCall(methodCall: KtCallExpression, context: KtElement): KtCallExpression { val analyzableElement = ((createExpressionCodeFragment("(null)", context).copy() as KtExpressionCodeFragment) .getContentElement()!! as KtParenthesizedExpression).expression!! val isQualified = methodCall.parent is KtQualifiedExpression return if (isQualified) { (analyzableElement.replaced(methodCall.parent) as KtQualifiedExpression).lastChild as KtCallExpression } else { analyzableElement.replaced(methodCall) } } override fun createCallableReferenceExpression( receiver: UExpression?, methodName: String, context: PsiElement? ): UCallableReferenceExpression? { val text = receiver?.sourcePsi?.text ?: "" val callableExpression = psiFactory.createCallableReferenceExpression("$text::$methodName") ?: return null return KotlinUCallableReferenceExpression(callableExpression, null) } override fun createStringLiteralExpression(text: String, context: PsiElement?): ULiteralExpression { return KotlinStringULiteralExpression(psiFactory.createExpression(StringUtil.wrapWithDoubleQuote(text)), null) } override fun createLongConstantExpression(long: Long, context: PsiElement?): UExpression? { return when (val literalExpr = psiFactory.createExpression(long.toString() + "L")) { is KtConstantExpression -> KotlinULiteralExpression(literalExpr, null) is KtPrefixExpression -> KotlinUPrefixExpression(literalExpr, null) else -> null } } override fun createNullLiteral(context: PsiElement?): ULiteralExpression { return psiFactory.createExpression("null").toUElementOfType()!! } /*override*/ fun createIntLiteral(value: Int, context: PsiElement?): ULiteralExpression { return psiFactory.createExpression(value.toString()).toUElementOfType()!! } private fun KtExpression.ensureBlockExpressionBraces(): KtExpression { if (this !is KtBlockExpression || hasBraces(this)) return this val blockExpression = psiFactory.createBlock(this.statements.joinToString("\n") { "println()" }) for ((placeholder, statement) in blockExpression.statements.zip(this.statements)) { placeholder.replace(statement) } return blockExpression } @Deprecated("use version with context parameter") fun createIfExpression(condition: UExpression, thenBranch: UExpression, elseBranch: UExpression?): UIfExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createIfExpression(condition, thenBranch, elseBranch, null) } override fun createIfExpression( condition: UExpression, thenBranch: UExpression, elseBranch: UExpression?, context: PsiElement? ): UIfExpression? { val conditionPsi = condition.sourcePsi as? KtExpression ?: return null val thenBranchPsi = thenBranch.sourcePsi as? KtExpression ?: return null val elseBranchPsi = elseBranch?.sourcePsi as? KtExpression return KotlinUIfExpression(psiFactory.createIf(conditionPsi, thenBranchPsi.ensureBlockExpressionBraces(), elseBranchPsi?.ensureBlockExpressionBraces()), null) } @Deprecated("use version with context parameter") fun createParenthesizedExpression(expression: UExpression): UParenthesizedExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createParenthesizedExpression(expression, null) } override fun createParenthesizedExpression(expression: UExpression, context: PsiElement?): UParenthesizedExpression? { val source = expression.sourcePsi ?: return null val parenthesized = psiFactory.createExpression("(${source.text})") as? KtParenthesizedExpression ?: return null return KotlinUParenthesizedExpression(parenthesized, null) } @Deprecated("use version with context parameter") fun createSimpleReference(name: String): USimpleNameReferenceExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createSimpleReference(name, null) } override fun createSimpleReference(name: String, context: PsiElement?): USimpleNameReferenceExpression { return KotlinUSimpleReferenceExpression(psiFactory.createSimpleName(name), null) } @Deprecated("use version with context parameter") fun createSimpleReference(variable: UVariable): USimpleNameReferenceExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createSimpleReference(variable, null) } override fun createSimpleReference(variable: UVariable, context: PsiElement?): USimpleNameReferenceExpression? { return createSimpleReference(variable.name ?: return null, context) } @Deprecated("use version with context parameter") fun createReturnExpresion(expression: UExpression?, inLambda: Boolean): UReturnExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createReturnExpresion(expression, inLambda, null) } override fun createReturnExpresion(expression: UExpression?, inLambda: Boolean, context: PsiElement?): UReturnExpression { val label = if (inLambda && context != null) getParentLambdaLabelName(context)?.let { "@$it" } ?: "" else "" val returnExpression = psiFactory.createExpression("return$label 1") as KtReturnExpression val sourcePsi = expression?.sourcePsi if (sourcePsi != null) { returnExpression.returnedExpression!!.replace(sourcePsi) } else { returnExpression.returnedExpression?.delete() } return KotlinUReturnExpression(returnExpression, null) } private fun getParentLambdaLabelName(context: PsiElement): String? { val lambdaExpression = context.getParentOfType<KtLambdaExpression>(false) ?: return null lambdaExpression.parent.safeAs<KtLabeledExpression>()?.let { return it.getLabelName() } val callExpression = lambdaExpression.getStrictParentOfType<KtCallExpression>() ?: return null callExpression.valueArguments.find { it.getArgumentExpression()?.unpackFunctionLiteral(allowParentheses = false) === lambdaExpression } ?: return null return callExpression.getCallNameExpression()?.text } @Deprecated("use version with context parameter") fun createBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator ): UBinaryExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createBinaryExpression(leftOperand, rightOperand, operator, null) } override fun createBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator, context: PsiElement? ): UBinaryExpression? { val binaryExpression = joinBinaryExpression(leftOperand, rightOperand, operator) ?: return null return KotlinUBinaryExpression(binaryExpression, null) } private fun joinBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator ): KtBinaryExpression? { val leftPsi = leftOperand.sourcePsi ?: return null val rightPsi = rightOperand.sourcePsi ?: return null val binaryExpression = psiFactory.createExpression("a ${operator.text} b") as? KtBinaryExpression ?: return null binaryExpression.left?.replace(leftPsi) binaryExpression.right?.replace(rightPsi) return binaryExpression } @Deprecated("use version with context parameter") fun createFlatBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator ): UPolyadicExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createFlatBinaryExpression(leftOperand, rightOperand, operator, null) } override fun createFlatBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator, context: PsiElement? ): UPolyadicExpression? { fun unwrapParentheses(exp: KtExpression?) { if (exp !is KtParenthesizedExpression) return if (!KtPsiUtil.areParenthesesUseless(exp)) return exp.expression?.let { exp.replace(it) } } val binaryExpression = joinBinaryExpression(leftOperand, rightOperand, operator) ?: return null unwrapParentheses(binaryExpression.left) unwrapParentheses(binaryExpression.right) return psiFactory.createExpression(binaryExpression.text).toUElementOfType()!! } @Deprecated("use version with context parameter") fun createBlockExpression(expressions: List<UExpression>): UBlockExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createBlockExpression(expressions, null) } override fun createBlockExpression(expressions: List<UExpression>, context: PsiElement?): UBlockExpression { val sourceExpressions = expressions.flatMap { it.toSourcePsiFakeAware() } val block = psiFactory.createBlock( sourceExpressions.joinToString(separator = "\n") { "println()" } ) for ((placeholder, psiElement) in block.statements.zip(sourceExpressions)) { placeholder.replace(psiElement) } return KotlinUBlockExpression(block, null) } @Deprecated("use version with context parameter") fun createDeclarationExpression(declarations: List<UDeclaration>): UDeclarationsExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createDeclarationExpression(declarations, null) } override fun createDeclarationExpression(declarations: List<UDeclaration>, context: PsiElement?): UDeclarationsExpression { return object : KotlinUDeclarationsExpression(null), KotlinFakeUElement { override var declarations: List<UDeclaration> = declarations override fun unwrapToSourcePsi(): List<PsiElement> = declarations.flatMap { it.toSourcePsiFakeAware() } } } override fun createLambdaExpression( parameters: List<UParameterInfo>, body: UExpression, context: PsiElement? ): ULambdaExpression? { val resolutionFacade = (context as? KtElement)?.getResolutionFacade() val validator = (context as? KtElement)?.let { usedNamesFilter(it) } ?: { true } val newLambdaStatements = if (body is UBlockExpression) { body.expressions.flatMap { member -> when { member is UReturnExpression -> member.returnExpression?.toSourcePsiFakeAware().orEmpty() else -> member.toSourcePsiFakeAware() } } } else listOf(body.sourcePsi!!) val ktLambdaExpression = psiFactory.createLambdaExpression( parameters.joinToString(", ") { p -> val ktype = resolutionFacade?.let { p.type?.resolveToKotlinType(it) } StringBuilder().apply { append(p.suggestedName ?: ktype?.let { KotlinNameSuggester.suggestNamesByType(it, validator).firstOrNull() }) ?: KotlinNameSuggester.suggestNameByName("v", validator) ktype?.fqName?.toString()?.let { append(": ").append(it) } } }, newLambdaStatements.joinToString("\n") { "placeholder" } ) for ((old, new) in ktLambdaExpression.bodyExpression!!.statements.zip(newLambdaStatements)) { old.replace(new) } return ktLambdaExpression.toUElementOfType()!! } @Deprecated("use version with context parameter") fun createLambdaExpression(parameters: List<UParameterInfo>, body: UExpression): ULambdaExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createLambdaExpression(parameters, body, null) } override fun createLocalVariable( suggestedName: String?, type: PsiType?, initializer: UExpression, immutable: Boolean, context: PsiElement? ): ULocalVariable { val resolutionFacade = (context as? KtElement)?.getResolutionFacade() val validator = (context as? KtElement)?.let { usedNamesFilter(it) } ?: { true } val ktype = resolutionFacade?.let { type?.resolveToKotlinType(it) } val function = psiFactory.createFunction( buildString { append("fun foo() { ") append(if (immutable) "val" else "var") append(" ") append(suggestedName ?: ktype?.let { KotlinNameSuggester.suggestNamesByType(it, validator).firstOrNull() }) ?: KotlinNameSuggester.suggestNameByName("v", validator) ktype?.fqName?.toString()?.let { append(": ").append(it) } append(" = null") append("}") } ) val ktVariable = PsiTreeUtil.findChildOfType(function, KtVariableDeclaration::class.java)!! val newVariable = ktVariable.initializer!!.replace(initializer.sourcePsi!!).parent return newVariable.toUElementOfType<UVariable>() as ULocalVariable } @Deprecated("use version with context parameter") fun createLocalVariable( suggestedName: String?, type: PsiType?, initializer: UExpression, immutable: Boolean ): ULocalVariable? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createLocalVariable(suggestedName, type, initializer, immutable, null) } } private fun usedNamesFilter(context: KtElement): (String) -> Boolean { val scope = context.getResolutionScope() return { name: String -> scope.findClassifier(Name.identifier(name), NoLookupLocation.FROM_IDE) == null } }
apache-2.0
e54005a4662cd60afdefbeff12a15815
45.632829
166
0.69157
5.849363
false
false
false
false
ianhanniballake/muzei
example-unsplash/src/main/java/com/example/muzei/unsplash/UnsplashExampleWorker.kt
2
2907
/* * Copyright 2018 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.example.muzei.unsplash import android.content.Context import android.util.Log import androidx.core.net.toUri import androidx.work.Constraints import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.Worker import androidx.work.WorkerParameters import com.example.muzei.unsplash.BuildConfig.UNSPLASH_AUTHORITY import com.google.android.apps.muzei.api.provider.Artwork import com.google.android.apps.muzei.api.provider.ProviderContract import java.io.IOException class UnsplashExampleWorker( context: Context, workerParams: WorkerParameters ) : Worker(context, workerParams) { companion object { private const val TAG = "UnsplashExample" internal fun enqueueLoad(context: Context) { val workManager = WorkManager.getInstance(context) workManager.enqueue(OneTimeWorkRequestBuilder<UnsplashExampleWorker>() .setConstraints(Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build()) .build()) } } override fun doWork(): Result { val photos = try { UnsplashService.popularPhotos() } catch (e: IOException) { Log.w(TAG, "Error reading Unsplash response", e) return Result.retry() } if (photos.isEmpty()) { Log.w(TAG, "No photos returned from API.") return Result.failure() } val providerClient = ProviderContract.getProviderClient( applicationContext, UNSPLASH_AUTHORITY) val attributionString = applicationContext.getString(R.string.attribution) providerClient.addArtwork(photos.map { photo -> Artwork( token = photo.id, title = photo.description ?: attributionString, byline = photo.user.name, attribution = if (photo.description != null) attributionString else null, persistentUri = photo.urls.full.toUri(), webUri = photo.links.webUri, metadata = photo.user.links.webUri.toString()) }) return Result.success() } }
apache-2.0
2ea41009ddb3ad6788d7aab58e565054
35.797468
93
0.657379
4.902192
false
false
false
false
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/instance/LocalInstancePlugin.kt
1
3604
package com.cognifide.gradle.aem.instance import com.cognifide.gradle.aem.AemException import com.cognifide.gradle.aem.instance.tasks.InstanceProvision import com.cognifide.gradle.aem.instance.tasks.InstanceRcp import com.cognifide.gradle.aem.instance.tasks.InstanceTail import com.cognifide.gradle.aem.instance.tasks.* import com.cognifide.gradle.aem.pkg.PackagePlugin import com.cognifide.gradle.common.CommonDefaultPlugin import com.cognifide.gradle.common.RuntimePlugin import com.cognifide.gradle.common.checkForce import com.cognifide.gradle.common.tasks.runtime.* import org.gradle.api.Project class LocalInstancePlugin : CommonDefaultPlugin() { override fun Project.configureProject() { setupDependentPlugins() setupTasks() } private fun Project.setupDependentPlugins() { if (plugins.hasPlugin(PackagePlugin::class.java)) { throw AemException("Local instance plugin '${InstancePlugin.ID}' must be applied before package plugin '${PackagePlugin.ID}'!") } plugins.apply(InstancePlugin::class.java) plugins.apply(RuntimePlugin::class.java) } @Suppress("LongMethod") private fun Project.setupTasks() = tasks { // Plugin tasks val down = register<InstanceDown>(InstanceDown.NAME) val destroy = register<InstanceDestroy>(InstanceDestroy.NAME) { dependsOn(down) }.also { checkForce(it) } val resolve = register<InstanceResolve>(InstanceResolve.NAME) val create = register<InstanceCreate>(InstanceCreate.NAME) { mustRunAfter(destroy, resolve) } val up = register<InstanceUp>(InstanceUp.NAME) { dependsOn(create) mustRunAfter(down, destroy) } val restart = register<InstanceRestart>(InstanceRestart.NAME) { dependsOn(down, up) } named<InstanceProvision>(InstanceProvision.NAME) { mustRunAfter(resolve, create, up) } val await = named<InstanceAwait>(InstanceAwait.NAME) { mustRunAfter(create, up) } val setup = named<InstanceSetup>(InstanceSetup.NAME) { dependsOn(create, up) mustRunAfter(destroy) } val resetup = register<InstanceResetup>(InstanceResetup.NAME) { dependsOn(destroy, setup) } val backup = register<InstanceBackup>(InstanceBackup.NAME) { mustRunAfter(down) } named<InstanceTail>(InstanceTail.NAME) { mustRunAfter(resolve, create, up) } named<InstanceRcp>(InstanceRcp.NAME) { mustRunAfter(resolve, create, up) } named<InstanceGroovyEval>(InstanceGroovyEval.NAME) { mustRunAfter(resolve, create, up) } register<InstanceKill>(InstanceKill.NAME) // Runtime lifecycle named<Up>(Up.NAME) { dependsOn(up) mustRunAfter(backup) } named<Down>(Down.NAME) { dependsOn(down) } named<Destroy>(Destroy.NAME) { dependsOn(destroy) } named<Restart>(Restart.NAME) { dependsOn(restart) } named<Setup>(Setup.NAME) { dependsOn(setup) } named<Resetup>(Resetup.NAME) { dependsOn(resetup) } named<Resolve>(Resolve.NAME) { dependsOn(resolve) } named<Await>(Await.NAME) { dependsOn(await) } } companion object { const val ID = "com.cognifide.aem.instance.local" } }
apache-2.0
fe031c7aa253442e9c21bdb7e10b4604
31.468468
139
0.628191
4.499376
false
false
false
false
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/ui/about/AboutFragment.kt
1
1688
package sk.styk.martin.apkanalyzer.ui.about import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import dagger.hilt.android.AndroidEntryPoint import sk.styk.martin.apkanalyzer.databinding.FragmentAboutBinding import sk.styk.martin.apkanalyzer.util.file.AppOperations import sk.styk.martin.apkanalyzer.util.provideViewModel import javax.inject.Inject @AndroidEntryPoint class AboutFragment : Fragment() { @Inject lateinit var factory: AboutFragmentViewModel.Factory private lateinit var binding: FragmentAboutBinding private lateinit var viewModel: AboutFragmentViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = provideViewModel { factory.create() } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = FragmentAboutBinding.inflate(inflater, container, false) binding.aboutAppGithubLink.movementMethod = LinkMovementMethod.getInstance() binding.aboutAppPrivacyPolicy.movementMethod = LinkMovementMethod.getInstance() return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.viewModel = viewModel viewModel.openGooglePlay.observe(viewLifecycleOwner) { AppOperations.openGooglePlay( requireContext(), requireContext().packageName ) } } }
gpl-3.0
55219f99985667632377a58a657290e9
32.76
115
0.753555
5.308176
false
false
false
false
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/manager/file/ApkSaveManager.kt
1
3027
package sk.styk.martin.apkanalyzer.manager.file import android.content.ContentResolver import android.net.Uri import androidx.annotation.IntRange import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import kotlinx.coroutines.yield import sk.styk.martin.apkanalyzer.manager.notification.NotificationManager import sk.styk.martin.apkanalyzer.util.TAG_EXPORTS import sk.styk.martin.apkanalyzer.util.coroutines.DispatcherProvider import timber.log.Timber import java.io.File import java.io.FileInputStream import javax.inject.Inject import javax.inject.Singleton @Singleton class ApkSaveManager @Inject constructor( private val contentResolver: ContentResolver, private val notificationManager: NotificationManager, private val dispatcherProvider: DispatcherProvider) { sealed class AppSaveStatus(open val outputUri: Uri) { data class Progress(@IntRange(from = 0, to = 100) val currentProgress: Int, override val outputUri: Uri) : AppSaveStatus(outputUri) data class Done(override val outputUri: Uri) : AppSaveStatus(outputUri) } suspend fun saveApk(appName: String, sourceFile: File, targetUri: Uri) { GlobalScope.launch { try { saveApkInternal(appName, sourceFile, targetUri) .distinctUntilChanged() .debounce(1500) .collect { val notificationBuilder = notificationManager.showAppExportProgressNotification(appName) when (it) { is AppSaveStatus.Progress -> notificationManager.updateAppExportProgressNotification(notificationBuilder, it.currentProgress) is AppSaveStatus.Done -> notificationManager.showAppExportDoneNotification(appName, it.outputUri) } } } catch (e: Exception) { Timber.tag(TAG_EXPORTS).e(e, "Saving apk failed failed. Appname=${appName}, sourceFile=${sourceFile}, targetUri=$targetUri") } } } private suspend fun saveApkInternal(appName: String, sourceFile: File, targetUri: Uri) = flow { emit(AppSaveStatus.Progress(0, targetUri)) val fileSize = sourceFile.length() FileInputStream(sourceFile).use { source -> contentResolver.openOutputStream(targetUri)!!.use { output -> val buffer = ByteArray(10240) var len: Int = source.read(buffer) var readBytes = len while (len > 0) { yield() output.write(buffer, 0, len) len = source.read(buffer) readBytes += len emit(AppSaveStatus.Progress((readBytes * 100 / fileSize).toInt(), targetUri)) } } } emit(AppSaveStatus.Done(targetUri)) }.flowOn(dispatcherProvider.io()) }
gpl-3.0
df93976c778ea1e7a21deb1e4a4362dc
39.373333
157
0.635613
5.255208
false
false
false
false
Jire/Charlatano
src/main/kotlin/com/charlatano/utils/extensions/MemoryExtensions.kt
1
1330
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.utils.extensions import com.sun.jna.Memory fun Memory?.readable() = null != this fun Memory.byte(address: Long) = getByte(address) fun Memory.short(address: Long) = getShort(address) fun Memory.int(address: Long) = getInt(address) fun Memory.long(address: Long) = getLong(address) fun Memory.float(address: Long) = getFloat(address) fun Memory.double(address: Long) = getDouble(address) fun Memory.char(address: Long) = getChar(address) fun Memory.boolean(address: Long) = byte(address).toInt() != 0
agpl-3.0
f39672de50f99ac528578fc570f2ed37
40.59375
78
0.745113
3.789174
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/ui/views/ResilientEditText.kt
1
1573
package ch.rmy.android.framework.ui.views import android.content.Context import android.graphics.Canvas import android.util.AttributeSet import android.view.MotionEvent import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputConnection import android.view.inputmethod.InputConnectionWrapper import androidx.appcompat.R import androidx.appcompat.widget.AppCompatEditText import ch.rmy.android.framework.extensions.tryOrIgnore class ResilientEditText @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.editTextStyle, ) : AppCompatEditText(context, attrs, defStyleAttr) { override fun dispatchTouchEvent(event: MotionEvent?): Boolean = try { super.dispatchTouchEvent(event) } catch (e: IndexOutOfBoundsException) { true } catch (e: IllegalStateException) { true } override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? = super.onCreateInputConnection(outAttrs) ?.let { object : InputConnectionWrapper(it, false) { override fun getSelectedText(flags: Int): CharSequence? = try { super.getSelectedText(flags) } catch (e: IndexOutOfBoundsException) { null } } } override fun onDraw(canvas: Canvas?) { tryOrIgnore { super.onDraw(canvas) } } }
mit
32e9b535ebb8cc3ea6ae362d60006984
32.468085
82
0.638907
5.332203
false
false
false
false
aosp-mirror/platform_frameworks_support
jetifier/jetifier/processor/src/main/kotlin/com/android/tools/build/jetifier/processor/transform/proguard/patterns/ReplacersRunner.kt
1
2060
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.build.jetifier.processor.transform.proguard.patterns /** * Runs multiple [GroupsReplacer]s on given strings. */ class ReplacersRunner(val replacers: List<GroupsReplacer>) { /** * Runs all the [GroupsReplacer]s on the given [input]. * * The replacers have to be distinct as this method can't guarantee that output of one replacer * won't be matched by another replacer. */ fun applyReplacers(input: String): String { val sb = StringBuilder() var lastSeenChar = 0 var processedInput = input for (replacer in replacers) { val matcher = replacer.pattern.matcher(processedInput) while (matcher.find()) { if (lastSeenChar < matcher.start()) { sb.append(processedInput, lastSeenChar, matcher.start()) } val result = replacer.runReplacements(matcher) sb.append(result.joinToString(System.lineSeparator())) lastSeenChar = matcher.end() } if (lastSeenChar == 0) { continue } if (lastSeenChar <= processedInput.length - 1) { sb.append(processedInput, lastSeenChar, processedInput.length) } lastSeenChar = 0 processedInput = sb.toString() sb.setLength(0) } return processedInput } }
apache-2.0
3ad23ab75cdc02d2c043611258d3476a
32.241935
99
0.628641
4.724771
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/breadwallet/ui/settings/fingerprint/FingerprintSettingsController.kt
1
3148
/** * BreadWallet * * Created by Pablo Budelli <[email protected]> on 10/25/19. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.ui.settings.fingerprint import com.breadwallet.databinding.ControllerFingerprintSettingsBinding import com.breadwallet.ui.BaseMobiusController import com.breadwallet.ui.flowbind.checked import com.breadwallet.ui.flowbind.clicks import com.breadwallet.ui.settings.fingerprint.FingerprintSettings.E import com.breadwallet.ui.settings.fingerprint.FingerprintSettings.F import com.breadwallet.ui.settings.fingerprint.FingerprintSettings.M import drewcarlson.mobius.flow.FlowTransformer import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.onEach class FingerprintSettingsController : BaseMobiusController<M, E, F>() { override val defaultModel = M() override val update = FingerprintSettingsUpdate override val init = FingerprintSettingsInit override val flowEffectHandler: FlowTransformer<F, E> get() = createFingerprintSettingsHandler() private val binding by viewBinding(ControllerFingerprintSettingsBinding::inflate) override fun bindView(modelFlow: Flow<M>): Flow<E> { return with(binding) { modelFlow.map { it.unlockApp } .onEach { switchUnlockApp.isChecked = it } .launchIn(uiBindScope) modelFlow.map { it.sendMoney } .onEach { switchSendMoney.isChecked = it } .launchIn(uiBindScope) modelFlow.map { it.sendMoneyEnable } .onEach { switchSendMoney.isEnabled = it } .launchIn(uiBindScope) merge( faqBtn.clicks().map { E.OnFaqClicked }, backBtn.clicks().map { E.OnBackClicked }, switchSendMoney.checked().map { E.OnSendMoneyChanged(it) }, switchUnlockApp.checked().map { E.OnAppUnlockChanged(it) } ) } } }
mit
6aa103fc581a4c21f58a835e6caf1d77
42.123288
85
0.724905
4.588921
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/breadwallet/ui/importwallet/ImportUpdate.kt
1
7634
/** * BreadWallet * * Created by Drew Carlson <[email protected]> on 12/3/19. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.ui.importwallet import com.breadwallet.breadbox.toBigDecimal import com.breadwallet.tools.util.EventUtils import com.breadwallet.ui.importwallet.Import.E import com.breadwallet.ui.importwallet.Import.F import com.breadwallet.ui.importwallet.Import.M import com.spotify.mobius.Next.dispatch import com.spotify.mobius.Next.next import com.spotify.mobius.Next.noChange import com.spotify.mobius.Update val ImportUpdate = Update<M, E, F> { model, event -> when (event) { is E.OnScanClicked -> dispatch(setOf(F.Nav.GoToScan)) E.OnFaqClicked -> dispatch(setOf(F.Nav.GoToFaq)) E.OnCloseClicked -> when (model.loadingState) { M.LoadingState.IDLE -> dispatch(setOf<F>(F.Nav.GoBack)) else -> noChange() } E.Key.NoWallets -> dispatch(setOf(F.Nav.GoBack)) is E.Key.OnValid -> when { event.isPasswordProtected -> when { !model.keyPassword.isNullOrEmpty() -> next( model.copy( isKeyValid = true, keyRequiresPassword = true ), setOf<F>( F.EstimateImport.KeyWithPassword( privateKey = checkNotNull(model.privateKey), password = model.keyPassword ) ) ) else -> next( model.copy( isKeyValid = true, keyRequiresPassword = true ), setOf<F>(F.ShowPasswordInput) ) } else -> next( model.copy( isKeyValid = true, keyRequiresPassword = false ), setOf<F>( F.EstimateImport.Key( privateKey = checkNotNull(model.privateKey) ) ) ) } E.Key.OnInvalid -> next( model.reset(), setOf(F.ShowKeyInvalid) ) E.Key.OnPasswordInvalid -> next( model.reset(), setOf(F.ShowPasswordInvalid) ) is E.OnKeyScanned -> next( model.copy( privateKey = event.privateKey, keyRequiresPassword = event.isPasswordProtected, isKeyValid = true, loadingState = M.LoadingState.VALIDATING ), setOf( if (event.isPasswordProtected) { F.ShowPasswordInput } else { F.ValidateKey(event.privateKey, null) } ) ) is E.RetryImport -> { val newModel = model.copy( privateKey = event.privateKey, keyPassword = event.password, keyRequiresPassword = event.password != null, isKeyValid = true, loadingState = M.LoadingState.ESTIMATING ) val estimateEffect = when { newModel.keyRequiresPassword -> F.EstimateImport.KeyWithPassword( privateKey = event.privateKey, password = checkNotNull(event.password) ) else -> F.EstimateImport.Key( privateKey = event.privateKey ) } next(model, setOf<F>(estimateEffect)) } is E.Estimate.Success -> { val balance = event.balance.toBigDecimal() val fee = event.feeAmount.toBigDecimal() next( model.copy( currencyCode = event.currencyCode ), setOf( F.ShowConfirmImport( receiveAmount = (balance - fee).toPlainString(), feeAmount = fee.toPlainString() ) ) ) } is E.Estimate.FeeError -> next(model.reset(), setOf(F.ShowImportFailed)) is E.Estimate.BalanceTooLow -> next(model.reset(), setOf(F.ShowBalanceTooLow)) E.Estimate.NoBalance -> next(model.reset(), setOf(F.ShowNoBalance)) is E.Transfer.OnSuccess -> { val effects = mutableSetOf<F>(F.ShowImportSuccess) if (model.gift) { effects.add(F.TrackEvent(EventUtils.EVENT_GIFT_REDEEM)) if (model.scanned) { effects.add(F.TrackEvent(EventUtils.EVENT_GIFT_REDEEM_SCAN)) } else { effects.add(F.TrackEvent(EventUtils.EVENT_GIFT_REDEEM_LINK)) } } else if (!model.reclaimGiftHash.isNullOrBlank()) { effects.add(F.TrackEvent(EventUtils.EVENT_GIFT_REDEEM)) effects.add(F.TrackEvent(EventUtils.EVENT_GIFT_REDEEM_RECLAIM)) } next( model.reset(), effects ) } E.Transfer.OnFailed -> next(model.reset(), setOf(F.ShowImportFailed)) E.OnImportCancel -> next(model.reset()) E.OnImportConfirm -> next( model.copy( loadingState = M.LoadingState.SUBMITTING ), setOf( F.SubmitImport( privateKey = checkNotNull(model.privateKey), password = model.keyPassword, currencyCode = checkNotNull(model.currencyCode), reclaimGiftHash = model.reclaimGiftHash ) ) ) is E.OnPasswordEntered -> when { model.privateKey != null && model.keyRequiresPassword -> next( model.copy( keyPassword = event.password, loadingState = M.LoadingState.VALIDATING ), setOf<F>( F.ValidateKey( privateKey = model.privateKey, password = event.password ) ) ) else -> noChange() } } }
mit
59223a031d688b1cdac1b54137502f60
37.751269
80
0.516767
5.221614
false
false
false
false
ognev-zair/Kotlin-AgendaCalendarView
app/src/main/java/com/ognev/kotlin/agendacalendarview/sample/MyCalendarEvent.kt
1
1281
package com.ognev.kotlin.agendacalendarview.sample import com.ognev.kotlin.agendacalendarview.models.* import java.util.* /** * Sample Calendar Event */ class MyCalendarEvent : BaseCalendarEvent { override lateinit var startTime: Calendar override lateinit var endTime: Calendar override var event: Any? = null override lateinit var instanceDay: Calendar override lateinit var dayReference: IDayItem override lateinit var weekReference: IWeekItem override fun setEventInstanceDay(instanceDay: Calendar): MyCalendarEvent { this.instanceDay = instanceDay this.instanceDay.set(Calendar.HOUR, 0) this.instanceDay.set(Calendar.MINUTE, 0) this.instanceDay.set(Calendar.SECOND, 0) this.instanceDay.set(Calendar.MILLISECOND, 0) this.instanceDay.set(Calendar.AM_PM, 0) return this } constructor() constructor(startTime: Calendar, endTime: Calendar, dayItem: DayItem, event: SampleEvent?) { this.startTime = startTime this.endTime = endTime this.dayReference = dayItem this.event = event } override fun copy(): MyCalendarEvent = MyCalendarEvent() override fun hasEvent() = event != null }
apache-2.0
4cc733d2b72c89fdeffa54ae0aae3235
25.708333
78
0.679157
4.709559
false
false
false
false