repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
edsilfer/sticky-index
demo/src/main/java/br/com/stickyindex/sample/common/di/contact/ContactsViewModule.kt
1
1586
package br.com.stickyindex.sample.common.di.contact import android.arch.lifecycle.Lifecycle import android.support.v7.app.AppCompatActivity import br.com.edsilfer.toolkit.core.components.SchedulersCoupler import br.com.stickyindex.sample.data.ContactsDataSource import br.com.stickyindex.sample.domain.Router import br.com.stickyindex.sample.presentation.presenter.ContactsPresenter import br.com.stickyindex.sample.presentation.view.ContactsView import br.com.stickyindex.sample.presentation.view.adapter.ContactsAdapter import dagger.Module import dagger.Provides /** * Created by edgarsf on 18/03/2018. */ @Module class ContactsViewModule { @Provides fun providesLifecycle(contactsView: ContactsView): Lifecycle = contactsView.lifecycle @Provides fun providesContactsDataSource( contactsView: ContactsView ): ContactsDataSource = ContactsDataSource(contactsView.context!!) @Provides fun providesRouter(contactsView: ContactsView): Router = Router(contactsView.activity as AppCompatActivity) @Provides fun providesAdapter( contactsView: ContactsView, schedulers: SchedulersCoupler ): ContactsAdapter = ContactsAdapter(schedulers, contactsView.context!!) @Provides fun providesPresenter( lifecycle: Lifecycle, contactsView: ContactsView, datasource: ContactsDataSource, router: Router, schedulers: SchedulersCoupler ): ContactsPresenter = ContactsPresenter(lifecycle, contactsView, datasource, router, schedulers) }
apache-2.0
8683665763dd4b5c9bbb2c3612370555
32.765957
111
0.757251
4.664706
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/bukkit/creator/BukkitProjectSettingsWizard.kt
1
4428
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.bukkit.creator import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.creator.MinecraftModuleWizardStep import com.demonwav.mcdev.creator.MinecraftProjectCreator import com.demonwav.mcdev.creator.ValidatedField import com.demonwav.mcdev.creator.ValidatedFieldType.CLASS_NAME import com.demonwav.mcdev.creator.ValidatedFieldType.LIST import com.demonwav.mcdev.creator.ValidatedFieldType.NON_BLANK import com.demonwav.mcdev.creator.getVersionSelector import com.demonwav.mcdev.platform.PlatformType import com.demonwav.mcdev.platform.bukkit.data.LoadOrder import javax.swing.JComboBox import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel import javax.swing.JTextField import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.swing.Swing import kotlinx.coroutines.withContext class BukkitProjectSettingsWizard(private val creator: MinecraftProjectCreator) : MinecraftModuleWizardStep() { @ValidatedField(NON_BLANK) private lateinit var pluginNameField: JTextField @ValidatedField(NON_BLANK, CLASS_NAME) private lateinit var mainClassField: JTextField private lateinit var panel: JPanel private lateinit var descriptionField: JTextField @ValidatedField(LIST) private lateinit var authorsField: JTextField private lateinit var websiteField: JTextField private lateinit var prefixField: JTextField private lateinit var loadOrderBox: JComboBox<*> private lateinit var loadBeforeField: JTextField @ValidatedField(LIST) private lateinit var dependField: JTextField private lateinit var softDependField: JTextField private lateinit var title: JLabel private lateinit var minecraftVersionBox: JComboBox<String> private lateinit var errorLabel: JLabel private var config: BukkitProjectConfig? = null private var versionsLoaded: Boolean = false override fun getComponent(): JComponent { return panel } override fun isStepVisible(): Boolean { return creator.config is BukkitProjectConfig } override fun updateStep() { config = creator.config as? BukkitProjectConfig if (config == null) { return } val conf = config ?: return basicUpdateStep(creator, pluginNameField, mainClassField) when (conf.type) { PlatformType.BUKKIT -> { title.icon = PlatformAssets.BUKKIT_ICON_2X title.text = "<html><font size=\"5\">Bukkit Settings</font></html>" } PlatformType.SPIGOT -> { title.icon = PlatformAssets.SPIGOT_ICON_2X title.text = "<html><font size=\"5\">Spigot Settings</font></html>" } PlatformType.PAPER -> { title.icon = PlatformAssets.PAPER_ICON_2X title.text = "<html><font size=\"5\">Paper Settings</font></html>" } else -> { } } if (versionsLoaded) { return } versionsLoaded = true CoroutineScope(Dispatchers.Swing).launch { try { withContext(Dispatchers.IO) { getVersionSelector(conf.type) }.set(minecraftVersionBox) } catch (e: Exception) { errorLabel.isVisible = true } } } override fun validate(): Boolean { return super.validate() && minecraftVersionBox.selectedItem != null } override fun updateDataModel() { val conf = this.config ?: return conf.pluginName = this.pluginNameField.text conf.mainClass = this.mainClassField.text conf.description = this.descriptionField.text conf.website = this.websiteField.text conf.loadOrder = if (this.loadOrderBox.selectedIndex == 0) LoadOrder.POSTWORLD else LoadOrder.STARTUP conf.prefix = this.prefixField.text conf.minecraftVersion = this.minecraftVersionBox.selectedItem as String conf.setLoadBefore(this.loadBeforeField.text) conf.setAuthors(this.authorsField.text) conf.setDependencies(this.dependField.text) conf.setSoftDependencies(this.softDependField.text) } }
mit
4231c7167c1b00db7b00566b1368e68d
32.801527
111
0.695348
4.776699
false
true
false
false
BrianErikson/PushLocal-Android
PushLocal/src/main/java/com/beariksonstudios/automatic/pushlocal/pushlocal/activities/main/dialog/SyncListAdapter.kt
1
2855
package com.beariksonstudios.automatic.pushlocal.pushlocal.activities.main.dialog import android.content.Context import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import com.beariksonstudios.automatic.pushlocal.pushlocal.PLDatabase import com.beariksonstudios.automatic.pushlocal.pushlocal.R import com.beariksonstudios.automatic.pushlocal.pushlocal.server.Device /** * Created by BrianErikson on 8/18/2015. */ class SyncListAdapter(private val con: Context, resource: Int, private val selectedDevice: Device) : ArrayAdapter<String>(con, resource, SyncListAdapter.choices) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view: View if (convertView == null) { val inflater = LayoutInflater.from(context) view = inflater.inflate(R.layout.item_dialog_sync_list, parent, false) } else view = convertView val textView = view.findViewById(R.id.textView_item_dialog_list) as TextView textView.text = choices[position] val checkBox = view.findViewById(R.id.checkbox_item_dialog_list) as CheckBox // reset checkbox to prevent recyclable-view glitches checkBox.isChecked = false checkBox.setOnClickListener(null) if (choices[position] == choices[2]) { Log.d("Pushlocal", "$position ${choices[position]} ${choices[2]}") if (selectedDevice.isSaved) { checkBox.isChecked = true } checkBox.setOnClickListener { val db = PLDatabase(context) if (checkBox.isChecked) { val success = db.insertDevice(selectedDevice) if (success) { selectedDevice.isSaved = true Toast.makeText(context, selectedDevice.hostName + " is now saved.", Toast.LENGTH_SHORT).show() } else { Toast.makeText(context, selectedDevice.hostName + " could not be saved!", Toast.LENGTH_SHORT).show() } } else { val successfullyRemoved = db.removeDevice(selectedDevice.hostName) if (successfullyRemoved) { selectedDevice.isSaved = false Toast.makeText(context, selectedDevice.hostName + " is now deleted.", Toast.LENGTH_SHORT).show() } else { Toast.makeText(context, selectedDevice.hostName + " could not be deleted!", Toast.LENGTH_SHORT).show() } } } } return view } companion object { val choices = arrayOf("Notifications", "Text Messages", "Save this Device") } }
apache-2.0
140b793ee23217e32b9e8a4fbb809e4d
40.376812
126
0.615762
4.782245
false
false
false
false
Tvede-dk/CommonsenseAndroidKotlin
widgets/src/main/kotlin/com/commonsense/android/kotlin/views/widgets/layouts/UniformVerticalLayout.kt
1
2660
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate") package com.commonsense.android.kotlin.views.widgets.layouts import android.content.* import android.graphics.* import android.graphics.drawable.* import android.util.* import com.commonsense.android.kotlin.base.extensions.* import com.commonsense.android.kotlin.views.extensions.* /** * Created by Kasper Tvede on 27-08-2017. */ class UniformVerticalLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : UniformBaseLayout(context, attrs, defStyleAttr) { override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { val contentRect = getContentSize() val heightOfChild = childSizeOf(contentHeight) var currentTop = contentRect.top + contentMarginInt val leftOffset = contentRect.left + contentMarginInt val rightOffset = contentRect.right - contentMarginInt visibleChildren.forEach { it.layout(leftOffset, currentTop, rightOffset, currentTop + heightOfChild) currentTop += heightOfChild + contentMarginInt } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val height = getDefaultSize(suggestedMinimumHeight, heightMeasureSpec) val heightOfChild = childSizeOf(contentHeight) var maxWidth = suggestedMinimumWidth val ourMeasureHeight = MeasureSpec.makeMeasureSpec(heightOfChild, MeasureSpec.EXACTLY) visibleChildren.forEach { measureChild(it, widthMeasureSpec, ourMeasureHeight) maxWidth = maxOf(maxWidth, it.measuredWidth) } setMeasuredDimension(maxWidth, height) } override fun doDrawOurOwnBackground(canvas: Canvas, background: Drawable) { val leftOffset = contentMarginInt val rightOffset = canvas.width - contentMarginInt //left and right border canvas.draw(background, 0, 0, contentMarginInt, canvas.height) canvas.draw(background, canvas.width - contentMarginInt, 0, canvas.width, canvas.height) //all things "in between" including the sides val heightOfChild = childSizeOf(contentHeight) var currentTop = 0 (visibleChildrenCount + 1).forEach { canvas.draw(background, leftOffset, currentTop, rightOffset, currentTop + contentMarginInt) currentTop += heightOfChild + contentMarginInt } } }
mit
d2114193bb175e37c36dc4db6b52401d
35.452055
94
0.66391
4.916821
false
false
false
false
inorichi/tachiyomi-extensions
src/en/webcomics/src/eu/kanade/tachiyomi/extension/en/webcomics/Webcomics.kt
1
6975
package eu.kanade.tachiyomi.extension.en.webcomics import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element class Webcomics : ParsedHttpSource() { override val name = "Webcomics" override val baseUrl = "https://www.webcomicsapp.com" override val lang = "en" override val supportsLatest = true override fun popularMangaSelector() = "section.mangas div div.col-md-3" override fun latestUpdatesSelector() = "section.mangas div div.col-md-3" override fun headersBuilder() = super.headersBuilder() .add("Referer", "https://www.webcomicsapp.com") override fun popularMangaRequest(page: Int) = GET("$baseUrl/popular.html", headers) override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/latest.html", headers) private fun mangaFromElement(element: Element): SManga { val manga = SManga.create() element.select("a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.select("h5").text() } return manga } override fun popularMangaFromElement(element: Element) = mangaFromElement(element) override fun latestUpdatesFromElement(element: Element) = mangaFromElement(element) override fun popularMangaNextPageSelector() = null override fun latestUpdatesNextPageSelector() = null override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("section.book-info-left > .wrap") val manga = SManga.create() manga.genre = infoElement.select(".labels > label").joinToString(", ") { it.text() } manga.description = infoElement.select("p.p-description").text() manga.thumbnail_url = infoElement.select("img").first()?.attr("src") infoElement.select("p.p-schedule:first-of-type").text().let { if (it.contains("IDK")) manga.status = SManga.COMPLETED else manga.status = SManga.ONGOING } return manga } override fun searchMangaNextPageSelector() = throw UnsupportedOperationException("Not used") override fun searchMangaFromElement(element: Element): SManga { val infoElement = element.select(".col-md-5") val manga = SManga.create() infoElement.let { manga.title = it.select(".wiki-book-title").text().trim() manga.setUrlWithoutDomain(it.select("a").first().attr("href")) } return manga } override fun searchMangaSelector() = ".wiki-book-list > .row" override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val url = "$baseUrl/wiki.html?search=$query&page=$page".toHttpUrlOrNull()?.newBuilder() (if (filters.isEmpty()) getFilterList() else filters).forEach { filter -> when (filter) { is GenreFilter -> { val genre = getGenreList()[filter.state] url?.addQueryParameter("category", genre) } } } return GET(url.toString(), headers) } override fun searchMangaParse(response: Response): MangasPage { val document = response.asJsoup() var nextPage = true val mangas = document.select(searchMangaSelector()).filter { val shouldFilter = it.select(".col-md-2 > a").first().text() == "READ" if (nextPage) { nextPage = shouldFilter } shouldFilter }.map { element -> searchMangaFromElement(element) } return MangasPage(mangas, if (nextPage) hasNextPage(document) else false) } private fun hasNextPage(document: Document): Boolean { return !document.select(".pagination .page-item.active + .page-item").isEmpty() } override fun chapterListSelector() = "section.book-info-left > .wrap > ul > li" override fun chapterListRequest(manga: SManga) = mangaDetailsRequest(manga) override fun chapterListParse(response: Response): List<SChapter> { val document = response.asJsoup() /* Source only allows 20 chapters to be readable on their website, trying to read past that results in a page list empty error; so might as well not grab them. */ return if (document.select("${chapterListSelector()}:nth-child(21)").isEmpty()) { document.select(chapterListSelector()).asReversed().map { chapterFromElement(it) } } else { val chapters = mutableListOf<SChapter>() for (i in 1..20) document.select("${chapterListSelector()}:nth-child($i)").map { chapters.add(chapterFromElement(it)) } // Add a chapter notifying the user of the situation val lockedNotification = SChapter.create() lockedNotification.name = "[Attention] Additional chapters are restricted by the source to their own app" lockedNotification.url = "wiki.html" chapters.add(lockedNotification) chapters.reversed() } } override fun chapterFromElement(element: Element): SChapter { val urlElement = element.select("a") val chapter = SChapter.create() chapter.setUrlWithoutDomain(urlElement.attr("href")) chapter.name = urlElement.text().trim() return chapter } override fun mangaDetailsRequest(manga: SManga) = GET(baseUrl + "/" + manga.url, headers) override fun pageListRequest(chapter: SChapter) = GET(baseUrl + "/" + chapter.url, headers) override fun pageListParse(document: Document) = document .select("section.book-reader .img-list > li > img") .mapIndexed { i, element -> Page(i, "", element.attr("data-original")) } override fun imageUrlParse(document: Document) = "" private class GenreFilter(genres: Array<String>) : Filter.Select<String>("Genre", genres) override fun getFilterList() = FilterList( GenreFilter(getGenreList()) ) // [...$('.row.wiki-book-nav .col-md-8 ul a')].map(el => `"${el.textContent.trim()}"`).join(',\n') // https://www.webcomicsapp.com/wiki.html private fun getGenreList() = arrayOf( "All", "Fantasy", "Comedy", "Drama", "Modern", "Action", "Monster", "Romance", "Boys'Love", "Harem", "Thriller", "Historical", "Sci-fi", "Slice of Life" ) }
apache-2.0
a42389238bb534e1ec66d3cc8bee618d
36.5
118
0.644731
4.576772
false
false
false
false
ligee/kotlin-jupyter
src/main/kotlin/org/jetbrains/kotlinx/jupyter/JupyterClientDetector.kt
1
2231
package org.jetbrains.kotlinx.jupyter import org.jetbrains.kotlinx.jupyter.api.JupyterClientType object JupyterClientDetector { fun detect(): JupyterClientType { return try { doDetect() } catch (e: LinkageError) { log.error("Unable to detect Jupyter client type because of incompatible JVM version", e) JupyterClientType.UNKNOWN } } private fun doDetect(): JupyterClientType { log.info("Detecting Jupyter client type") val currentHandle = ProcessHandle.current() val ancestors = generateSequence(currentHandle) { it.parent().orElse(null) }.toList() for (handle in ancestors) { val info = handle.info() val command = info.command().orElse("") val arguments = info.arguments().orElse(emptyArray()).toList() log.info("Inspecting process: $command ${arguments.joinToString(" ")}") val correctDetector = detectors.firstOrNull { it.isThisClient(command, arguments) } ?: continue log.info("Detected type is ${correctDetector.type}") return correctDetector.type } log.info("Client type has not been detected") return JupyterClientType.UNKNOWN } private interface Detector { val type: JupyterClientType fun isThisClient(command: String, arguments: List<String>): Boolean } private fun detector(type: JupyterClientType, predicate: (String, List<String>) -> Boolean) = object : Detector { override val type: JupyterClientType get() = type override fun isThisClient(command: String, arguments: List<String>): Boolean { return predicate(command, arguments) } } private val detectors = listOf<Detector>( detector(JupyterClientType.JUPYTER_NOTEBOOK) { command, args -> "jupyter-notebook" in command || args.any { "jupyter-notebook" in it } }, detector(JupyterClientType.JUPYTER_LAB) { command, args -> "jupyter-lab" in command || args.any { "jupyter-lab" in it } }, detector(JupyterClientType.KERNEL_TESTS) { command, _ -> command.endsWith("idea64.exe") } ) }
apache-2.0
25adb5f580babb138601eee7624dd113
36.813559
117
0.6329
4.686975
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/tumui/person/model/Employee.kt
1
2357
package de.tum.`in`.tumcampusapp.component.tumui.person.model import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Base64 import com.tickaroo.tikxml.annotation.Element import com.tickaroo.tikxml.annotation.PropertyElement import com.tickaroo.tikxml.annotation.Xml import de.tum.`in`.tumcampusapp.R /** * An employee of the TUM. * * * Note: This model is based on the TUMOnline web service response format for a * corresponding request. */ @Xml(name = "person") data class Employee( @PropertyElement(name = "geschlecht") val gender: String? = null, @PropertyElement(name = "obfuscated_id") val id: String = "", @PropertyElement(name = "vorname") val name: String = "", @PropertyElement(name = "familienname") val surname: String = "", @Element(name = "dienstlich") val businessContact: Contact? = null, @PropertyElement(name = "sprechstunde") val consultationHours: String = "", @PropertyElement val email: String = "", @Element(name = "gruppen") val groupList: GroupList? = null, @PropertyElement(name = "image_data") val imageData: String = "", @Element(name = "privat") val privateContact: Contact? = null, @Element(name = "raeume") val roomList: RoomList? = null, @Element(name = "telefon_nebenstellen") val telSubstationList: TelSubstationList? = null, @PropertyElement(name = "titel") val title: String = "" ) { val groups: List<Group>? get() = groupList?.groups val image: Bitmap? get() { val imageAsBytes = Base64.decode(imageData.toByteArray(Charsets.UTF_8), Base64.DEFAULT) return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.size) } val rooms: List<Room>? get() = roomList?.rooms val telSubstations: List<TelSubstation>? get() = telSubstationList?.substations fun getNameWithTitle(context: Context): String { val resourceId = if (gender == Person.FEMALE) R.string.mrs else R.string.mr val salutation = context.getString(resourceId) val salutationWithName = "$salutation $name $surname" if (title.isBlank()) { return salutationWithName } else { return "$salutationWithName, $title" } } }
gpl-3.0
706b7ecb8189111c5437972d7d258871
30.426667
99
0.665677
3.895868
false
false
false
false
fredyw/leetcode
src/main/kotlin/leetcode/Problem2024.kt
1
1021
package leetcode import java.util.LinkedList import kotlin.math.max /** * https://leetcode.com/problems/maximize-the-confusion-of-an-exam/ */ class Problem2024 { fun maxConsecutiveAnswers(answerKey: String, k: Int): Int { return max(consecutiveAnswers(answerKey, k, 'T'), consecutiveAnswers(answerKey, k, 'F')) } private fun consecutiveAnswers(answerKey: String, k: Int, c: Char): Int { var max = 0 var indexes = LinkedList<Int>() var count = k var length = 0 for (i in answerKey.indices) { if (answerKey[i] == c) { if (count - 1 < 0) { count++ length = if (indexes.isEmpty()) { 0 } else { i - indexes.pollFirst() - 1 } } count-- indexes.add(i) } length++ max = max(max, length) } return max } }
mit
94ac9e98e9b28cc8ec70507e4c784e25
26.594595
96
0.473066
4.254167
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/Bangumi.kt
1
4176
package eu.kanade.tachiyomi.data.track.bangumi import android.content.Context import android.graphics.Color import com.google.gson.Gson import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.TrackService import eu.kanade.tachiyomi.data.track.model.TrackSearch import rx.Completable import rx.Observable import uy.kohesive.injekt.injectLazy class Bangumi(private val context: Context, id: Int) : TrackService(id) { override fun getScoreList(): List<String> { return IntRange(0, 10).map(Int::toString) } override fun displayScore(track: Track): String { return track.score.toInt().toString() } override fun add(track: Track): Observable<Track> { return api.addLibManga(track) } override fun update(track: Track): Observable<Track> { if (track.total_chapters != 0 && track.last_chapter_read == track.total_chapters) { track.status = COMPLETED } return api.updateLibManga(track) } override fun bind(track: Track): Observable<Track> { return api.statusLibManga(track) .flatMap { api.findLibManga(track).flatMap { remoteTrack -> if (remoteTrack != null && it != null) { track.copyPersonalFrom(remoteTrack) track.library_id = remoteTrack.library_id track.status = remoteTrack.status track.last_chapter_read = remoteTrack.last_chapter_read update(track) } else { // Set default fields if it's not found in the list track.score = DEFAULT_SCORE.toFloat() track.status = DEFAULT_STATUS add(track) update(track) } } } } override fun search(query: String): Observable<List<TrackSearch>> { return api.search(query) } override fun refresh(track: Track): Observable<Track> { return api.statusLibManga(track) .flatMap { track.copyPersonalFrom(it!!) api.findLibManga(track) .map { remoteTrack -> if (remoteTrack != null) { track.total_chapters = remoteTrack.total_chapters track.status = remoteTrack.status } track } } } companion object { const val READING = 3 const val COMPLETED = 2 const val ON_HOLD = 4 const val DROPPED = 5 const val PLANNING = 1 const val DEFAULT_STATUS = READING const val DEFAULT_SCORE = 0 } override val name = "Bangumi" private val gson: Gson by injectLazy() private val interceptor by lazy { BangumiInterceptor(this, gson) } private val api by lazy { BangumiApi(client, interceptor) } override fun getLogo() = R.drawable.bangumi override fun getLogoColor() = Color.rgb(0xF0, 0x91, 0x99) override fun getStatusList(): List<Int> { return listOf(READING, COMPLETED, ON_HOLD, DROPPED, PLANNING) } override fun getStatus(status: Int): String = with(context) { when (status) { READING -> getString(R.string.reading) COMPLETED -> getString(R.string.completed) ON_HOLD -> getString(R.string.on_hold) DROPPED -> getString(R.string.dropped) PLANNING -> getString(R.string.plan_to_read) else -> "" } } override fun login(username: String, password: String) = login(password) fun login(code: String): Completable { return api.accessToken(code).map { oauth: OAuth? -> interceptor.newAuth(oauth) if (oauth != null) { saveCredentials(oauth.user_id.toString(), oauth.access_token) } }.doOnError { logout() }.toCompletable() } fun saveToken(oauth: OAuth?) { val json = gson.toJson(oauth) preferences.trackToken(this).set(json) } fun restoreToken(): OAuth? { return try { gson.fromJson(preferences.trackToken(this).get(), OAuth::class.java) } catch (e: Exception) { null } } override fun logout() { super.logout() preferences.trackToken(this).set(null) interceptor.newAuth(null) } }
apache-2.0
773946555092701ee9d5282e0f197c9d
27
87
0.625718
3.988539
false
false
false
false
zlyne0/colonization
core/src/net/sf/freecol/common/model/ai/missions/workerrequest/ScorePolicy.kt
1
3473
package net.sf.freecol.common.model.ai.missions.workerrequest import net.sf.freecol.common.model.player.Player import promitech.colonization.ai.score.ScoreableObjectsList /* Two policies. One policy worker price to production value(gold). Used when looking for worker to buy to produce something. Secound policy, worker production value(gold). Used when has worker and looking for place to work. */ interface ScorePolicy { class WorkerPriceToValue(val entryPointTurnRange: EntryPointTurnRange, val player: Player) : ScorePolicy { override fun calculateScore(scores: ScoreableObjectsList<WorkerRequestScoreValue>) { for (obj in scores) { when (obj) { is SingleWorkerRequestScoreValue -> scoreSingle(obj) is MultipleWorkerRequestScoreValue -> scoreMultiple(obj) } } scores.sortAscending() } override fun scoreSingle(obj: SingleWorkerRequestScoreValue) { val range = entryPointTurnRange.trunsCost(obj.location) val unitPrice = player.europe.aiUnitPrice(obj.workerType) if (obj.productionValue != 0) { obj.score = (unitPrice / obj.productionValue) + range * 2 } else { obj.score = 10000 } } override fun scoreMultiple(obj: MultipleWorkerRequestScoreValue) { var unitPriceSum = 0 var productionValueSum = 0 val range = entryPointTurnRange.trunsCost(obj.location) for (workerScore in obj.workersScores) { unitPriceSum += player.europe.aiUnitPrice(workerScore.workerType) productionValueSum += workerScore.productionValue if (workerScore.productionValue != 0) { break } } if (productionValueSum != 0) { obj.score = (unitPriceSum / productionValueSum) + range * 2 } else { obj.score = 10000 } } } class WorkerProductionValue(val entryPointTurnRange: EntryPointTurnRange) : ScorePolicy { override fun calculateScore(scores: ScoreableObjectsList<WorkerRequestScoreValue>) { for (obj in scores) { when (obj) { is SingleWorkerRequestScoreValue -> scoreSingle(obj) is MultipleWorkerRequestScoreValue -> scoreMultiple(obj) } } scores.sortDescending() } override fun scoreSingle(obj: SingleWorkerRequestScoreValue) { val range = entryPointTurnRange.trunsCost(obj.location) obj.score = obj.productionValue - range } override fun scoreMultiple(obj: MultipleWorkerRequestScoreValue) { val range = entryPointTurnRange.trunsCost(obj.location) obj.score = 0 var levelWeight : Float = 1.0f for (workersScore in obj.workersScores) { if (workersScore.productionValue != 0) { obj.score = (workersScore.productionValue * levelWeight).toInt() - range break } levelWeight -= 0.25f } } } fun calculateScore(scores: ScoreableObjectsList<WorkerRequestScoreValue>) fun scoreSingle(obj: SingleWorkerRequestScoreValue) fun scoreMultiple(obj: MultipleWorkerRequestScoreValue) }
gpl-2.0
097d5465648642ecd0c29b41424ad6f7
37.175824
110
0.610135
4.816921
false
false
false
false
sn3d/nomic
nomic-core/src/main/kotlin/nomic/core/BundledBox.kt
1
2858
/* * Copyright 2017 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nomic.core import nomic.core.fact.GroupFact import nomic.core.fact.NameFact import nomic.core.fact.VersionFact import nomic.core.script.BundleScript import java.nio.ByteBuffer /** * This is [Box] that is loaded from [Bundle] and can be installed to your system. * @author [email protected] */ open class BundledBox : Box, Bundle { //------------------------------------------------------------------------------------------------- // public API //------------------------------------------------------------------------------------------------- protected val bundle: Bundle override val script: Script get() = BundleScript(bundle) constructor(bundle: Bundle, facts: List<Fact> = emptyList()) { this.bundle = bundle; this.facts = facts; } constructor(id: BoxRef, bundle: Bundle) : this(id.group, id.name, id.version, bundle) constructor(id: BoxRef, bundle: Bundle, facts: List<Fact>) : this(id.group, id.name, id.version, bundle, facts) constructor(group: String, name: String, version: String, bundle: Bundle, facts: List<Fact> = emptyList()) : this(bundle, listOf(NameFact(name), GroupFact(group), VersionFact(version)) + facts) companion object { val empty = BundledBox(InMemoryBundle(), listOf()) } //------------------------------------------------------------------------------------------------- // implemented methods & properties //------------------------------------------------------------------------------------------------- final override val facts: List<Fact> override val name: String get() = facts.findFactType(NameFact::class.java).name override val group: String get() = facts.findFactType(GroupFact::class.java).group override val version: String get() = facts.findFactType(VersionFact::class.java).version override fun entry(path: String): Entry? = bundle.entry(path) override fun entries(filter: (Entry) -> Boolean): List<Entry> = bundle.entries(filter) override fun toString(): String { return "BundledBox(${ref()})" } } class ApplicationBox(bundle: Bundle, facts: List<Fact>) : BundledBox(bundle, facts) { fun toModuleBox() = ModuleBox(this.bundle, this.facts) } class ModuleBox(bundle: Bundle, facts: List<Fact>) : BundledBox(bundle, facts)
apache-2.0
0baf8976917b020ee9b79c3212871c67
32.244186
109
0.625962
4.106322
false
false
false
false
Mindera/skeletoid
rxjava/src/debug/kotlin/com/mindera/skeletoid/rxjava/schedulers/Schedulers.kt
1
925
package com.mindera.skeletoid.rxjava.schedulers import com.mindera.skeletoid.threads.threadpools.ThreadPoolUtils import io.reactivex.Scheduler object Schedulers { private val computationThreadPool by lazy { val maxComputationThreads = Runtime.getRuntime().availableProcessors() ThreadPoolUtils.getScheduledThreadPool("RxComputationTP", maxComputationThreads) } private val ioThreadPool by lazy { val maxIoThreads = Runtime.getRuntime().availableProcessors() ThreadPoolUtils.getScheduledThreadPool("RxIoTP", maxIoThreads + 2) } fun computation(): Scheduler = io.reactivex.schedulers.Schedulers.from(computationThreadPool) fun io(): Scheduler = io.reactivex.schedulers.Schedulers.from(ioThreadPool) fun single(): Scheduler = io.reactivex.schedulers.Schedulers.single() fun main(): Scheduler = io.reactivex.android.schedulers.AndroidSchedulers.mainThread() }
mit
cfd8d2a7fc9ce9be1f3e1b76c1f47103
41.045455
97
0.770811
4.842932
false
false
false
false
paslavsky/music-sync-manager
msm-server/src/main/kotlin/net/paslavsky/msm/setting/description/XmlPropertiesDescription.kt
1
1813
package net.paslavsky.msm.setting.description import javax.xml.bind.annotation.* import java.util.ArrayList import org.apache.commons.lang3.builder.ToStringBuilder import org.apache.commons.lang3.builder.HashCodeBuilder import org.apache.commons.lang3.builder.EqualsBuilder /** * <p>Class for anonymous complex type. * <p/> * <p>The following schema fragment specifies the expected content contained within this class. * <p/> * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="group" type="{http://paslavsky.net/property-description/1.0}Group" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="property" type="{http://paslavsky.net/property-description/1.0}Property" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * @author Andrey Paslavsky * @version 1.0 */ XmlAccessorType(XmlAccessType.FIELD) XmlType(name = "", propOrder = arrayOf("groups", "properties")) XmlRootElement(name = "properties", namespace = "http://paslavsky.net/property-description/1.0") public class XmlPropertiesDescription { XmlElement(name = "group", namespace = "http://paslavsky.net/property-description/1.0") public val groups: MutableCollection<XmlPropertyGroup> = ArrayList() XmlElement(name = "property", namespace = "http://paslavsky.net/property-description/1.0") public val properties: MutableCollection<XmlProperty> = ArrayList() override fun toString(): String = ToStringBuilder(this). append("groups", "XmlPropertyGroup[${groups.size()}]")!!. append("properties", "XmlProperty[${properties.size()}]")!!. toString(); }
apache-2.0
aa6b84b2abae37dde29009df8d02e4b1
41.186047
139
0.702151
3.707566
false
false
false
false
googlesamples/android-media-controller
mediacontroller/src/main/java/com/example/android/mediacontroller/tv/TvPresenters.kt
1
3286
/* * Copyright 2018 Google Inc. All rights reserved. * * 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.android.mediacontroller.tv import android.annotation.TargetApi import android.graphics.drawable.BitmapDrawable import android.os.Build import androidx.leanback.widget.ImageCardView import androidx.leanback.widget.Presenter import android.text.TextUtils import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.example.android.mediacontroller.MediaAppDetails import com.example.android.mediacontroller.R /** * Used to display apps in TvLauncherFragment */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) class MediaAppCardPresenter : Presenter() { override fun onCreateViewHolder(parent: ViewGroup?): ViewHolder { if (parent == null) { return ViewHolder(null) } val card = ImageCardView(parent.context).apply { isFocusable = true isFocusableInTouchMode = true findViewById<TextView>(R.id.title_text).apply { ellipsize = TextUtils.TruncateAt.END } findViewById<TextView>(R.id.content_text).apply { ellipsize = TextUtils.TruncateAt.MIDDLE } } return ViewHolder(card) } override fun onBindViewHolder(viewHolder: ViewHolder?, item: Any?) { if (item == null) { return } val appDetails = item as MediaAppDetails (viewHolder?.view as ImageCardView).apply { titleText = appDetails.appName contentText = appDetails.packageName val hasBanner = (appDetails.banner != null) val image = appDetails.banner ?: appDetails.icon mainImage = BitmapDrawable(viewHolder.view.context.resources, image) if (hasBanner) { val width = resources.getDimensionPixelSize(R.dimen.tv_banner_width) val height = resources.getDimensionPixelSize(R.dimen.tv_banner_height) setMainImageDimensions(width, height) } else { val width = resources.getDimensionPixelSize(R.dimen.tv_icon_width) val height = resources.getDimensionPixelSize(R.dimen.tv_icon_height) setMainImageDimensions(width, height) } // FIT_XY scales the icon/banner such that it fills the ImageView; the dimensions of the // ImageView are set above to ensure that the image retains its original aspect ratio setMainImageScaleType(ImageView.ScaleType.FIT_XY) } } override fun onUnbindViewHolder(viewHolder: ViewHolder?) { (viewHolder?.view as ImageCardView).apply { mainImage = null } } }
apache-2.0
443edd3c33ce40c16c46aab990e86c1a
37.22093
100
0.672855
4.832353
false
false
false
false
square/wire
wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaProtoAdapterFactory.kt
1
9081
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.schema import com.squareup.wire.FieldEncoding import com.squareup.wire.FieldEncoding.VARINT import com.squareup.wire.ProtoAdapter import com.squareup.wire.ProtoReader import com.squareup.wire.ProtoWriter import com.squareup.wire.ReverseProtoWriter import com.squareup.wire.Syntax import com.squareup.wire.WireField import com.squareup.wire.internal.FieldOrOneOfBinding import com.squareup.wire.internal.MessageBinding import com.squareup.wire.internal.RuntimeMessageAdapter import com.squareup.wire.schema.Field.EncodeMode import okio.ByteString /** * Creates type adapters to read and write protocol buffer data from a schema model. This doesn't * require an intermediate code gen step. */ internal class SchemaProtoAdapterFactory( val schema: Schema, private val includeUnknown: Boolean ) { private val adapterMap = mutableMapOf<ProtoType?, ProtoAdapter<*>>( ProtoType.BOOL to ProtoAdapter.BOOL, ProtoType.BYTES to ProtoAdapter.BYTES, ProtoType.DOUBLE to ProtoAdapter.DOUBLE, ProtoType.FLOAT to ProtoAdapter.FLOAT, ProtoType.FIXED32 to ProtoAdapter.FIXED32, ProtoType.FIXED64 to ProtoAdapter.FIXED64, ProtoType.INT32 to ProtoAdapter.INT32, ProtoType.INT64 to ProtoAdapter.INT64, ProtoType.SFIXED32 to ProtoAdapter.SFIXED32, ProtoType.SFIXED64 to ProtoAdapter.SFIXED64, ProtoType.SINT32 to ProtoAdapter.SINT32, ProtoType.SINT64 to ProtoAdapter.SINT64, ProtoType.STRING to ProtoAdapter.STRING, ProtoType.UINT32 to ProtoAdapter.UINT32, ProtoType.UINT64 to ProtoAdapter.UINT64 ) operator fun get(protoType: ProtoType): ProtoAdapter<Any> { if (protoType.isMap) throw UnsupportedOperationException("map types not supported") val result = adapterMap[protoType] if (result != null) { return result as ProtoAdapter<Any> } val type = requireNotNull(schema.getType(protoType)) { "unknown type: $protoType" } if (type is EnumType) { val enumAdapter = EnumAdapter(type) adapterMap[protoType] = enumAdapter return enumAdapter } if (type is MessageType) { val messageBinding = SchemaMessageBinding(type.type.typeUrl, type.syntax, includeUnknown) // Put the adapter in the map early to mitigate the recursive calls to get() made below. val deferredAdapter = DeferredAdapter<Map<String, Any>>(messageBinding) adapterMap[protoType] = deferredAdapter for (field in type.fields) { messageBinding.fields[field.tag] = SchemaFieldOrOneOfBinding(field, null) } for (oneOf in type.oneOfs) { for (field in oneOf.fields) { messageBinding.fields[field.tag] = SchemaFieldOrOneOfBinding(field, oneOf) } } val messageAdapter = RuntimeMessageAdapter(messageBinding) deferredAdapter.delegate = messageAdapter adapterMap[protoType] = messageAdapter return messageAdapter as ProtoAdapter<Any> } throw IllegalArgumentException("unexpected type: $protoType") } /** We prevent cycles by linking against while we're still building the graph of adapters. */ private class DeferredAdapter<T>( binding: SchemaMessageBinding ) : ProtoAdapter<T>( fieldEncoding = FieldEncoding.LENGTH_DELIMITED, type = binding.messageType, typeUrl = binding.typeUrl, syntax = binding.syntax ) { lateinit var delegate: ProtoAdapter<T> override fun decode(reader: ProtoReader) = delegate.decode(reader) override fun encode(writer: ProtoWriter, value: T) = delegate.encode(writer, value) override fun encode(writer: ReverseProtoWriter, value: T) = delegate.encode(writer, value) override fun encodedSize(value: T): Int = delegate.encodedSize(value) override fun redact(value: T): T = delegate.redact(value) } private class EnumAdapter( private val enumType: EnumType ) : ProtoAdapter<Any>(VARINT, Any::class, null, enumType.syntax) { override fun encodedSize(value: Any): Int { if (value is String) { val constant = enumType.constant(value)!! return INT32.encodedSize(constant.tag) } else if (value is Int) { return INT32.encodedSize(value) } else { throw IllegalArgumentException("unexpected " + enumType.type + ": " + value) } } override fun encode(writer: ProtoWriter, value: Any) { if (value is String) { val constant = enumType.constant(value) writer.writeVarint32(constant!!.tag) } else if (value is Int) { writer.writeVarint32(value) } else { throw IllegalArgumentException("unexpected " + enumType.type + ": " + value) } } override fun encode(writer: ReverseProtoWriter, value: Any) { if (value is String) { val constant = enumType.constant(value) writer.writeVarint32(constant!!.tag) } else if (value is Int) { writer.writeVarint32(value) } else { throw IllegalArgumentException("unexpected " + enumType.type + ": " + value) } } override fun decode(reader: ProtoReader): Any { val value = UINT32.decode(reader) val constant = enumType.constant(value) return constant?.name ?: value } override fun redact(value: Any): Any { throw UnsupportedOperationException() } } private class SchemaMessageBinding( override val typeUrl: String?, override val syntax: Syntax, private val includeUnknown: Boolean ) : MessageBinding<Map<String, Any>, MutableMap<String, Any>> { override val messageType = Map::class override val fields = mutableMapOf<Int, FieldOrOneOfBinding<Map<String, Any>, MutableMap<String, Any>>>() override fun unknownFields(message: Map<String, Any>) = ByteString.EMPTY override fun getCachedSerializedSize(message: Map<String, Any>) = 0 override fun setCachedSerializedSize(message: Map<String, Any>, size: Int) { } override fun newBuilder(): MutableMap<String, Any> = mutableMapOf() override fun build(builder: MutableMap<String, Any>) = builder.toMap() override fun addUnknownField( builder: MutableMap<String, Any>, tag: Int, fieldEncoding: FieldEncoding, value: Any? ) { if (!includeUnknown || value == null) return val name = tag.toString() val values = builder.getOrPut(name) { mutableListOf<Any>() } as MutableList<Any> values.add(value) } override fun clearUnknownFields(builder: MutableMap<String, Any>) { } } private inner class SchemaFieldOrOneOfBinding( val field: Field, val oneOf: OneOf? ) : FieldOrOneOfBinding<Map<String, Any>, MutableMap<String, Any>>() { override val tag: Int = field.tag override val label: WireField.Label get() { if (oneOf != null) return WireField.Label.ONE_OF return when (this.field.encodeMode!!) { EncodeMode.OMIT_IDENTITY -> WireField.Label.OMIT_IDENTITY EncodeMode.NULL_IF_ABSENT -> WireField.Label.OPTIONAL EncodeMode.MAP, EncodeMode.PACKED, EncodeMode.REPEATED -> WireField.Label.REPEATED EncodeMode.REQUIRED -> WireField.Label.REQUIRED } } override val redacted: Boolean = field.isRedacted override val isMap: Boolean = field.type!!.isMap override val isMessage: Boolean = schema.getType(field.type!!) is MessageType override val name: String = field.name override val declaredName: String = field.name override val wireFieldJsonName: String = field.jsonName!! override val writeIdentityValues: Boolean = false override val keyAdapter: ProtoAdapter<*> get() = get(this.field.type!!.keyType!!) override val singleAdapter: ProtoAdapter<*> get() = get(this.field.type!!) override fun value(builder: MutableMap<String, Any>, value: Any) { if (isMap) { val map = builder.getOrPut(field.name) { mutableMapOf<String, Any>() } as MutableMap<String, Any> map.putAll(value as Map<String, Any>) } else if (field.isRepeated) { val list = builder.getOrPut(field.name) { mutableListOf<Any>() } as MutableList<Any> list += value } else { set(builder, value) } } override fun set(builder: MutableMap<String, Any>, value: Any?) { builder[field.name] = value!! } override fun get(message: Map<String, Any>) = message[field.name] override fun getFromBuilder(builder: MutableMap<String, Any>) = builder[field.name] } }
apache-2.0
90a9d618c6f0f31ede3cd838c1ec48bb
35.324
97
0.696289
4.287535
false
false
false
false
Saketme/JRAW
lib/src/main/kotlin/net/dean/jraw/pagination/Stream.kt
2
2309
package net.dean.jraw.pagination import net.dean.jraw.Experimental import net.dean.jraw.models.UniquelyIdentifiable /** * A Stream is special Iterator subclass that polls from a given source (usually a [Paginator]), and yields new data as * each item becomes available. * * Consider [next] to be a blocking operation if this Stream is given a data source that interacts with the network. */ @Experimental class Stream<out T : UniquelyIdentifiable> @JvmOverloads constructor( private val dataSource: RedditIterable<T>, private val backoff: BackoffStrategy = ConstantBackoffStrategy(), historySize: Int = 500 ) : Iterator<T> { /** Keeps track of the uniqueIds we've seen recently */ private val history = RotatingSearchList<String>(historySize) private var currentIterator: Iterator<T>? = null private var resumeTimeMillis = -1L override fun hasNext(): Boolean = true override fun next(): T { val it = currentIterator if (it != null && it.hasNext()) { return it.next() } val new = requestNew() currentIterator = new return new.next() } private fun requestNew(): Iterator<T> { var newDataIterator: Iterator<T>? = null while (newDataIterator == null) { // Make sure to honor the backoff strategy if (resumeTimeMillis > System.currentTimeMillis()) { Thread.sleep(resumeTimeMillis - System.currentTimeMillis()) } dataSource.restart() val (new, old) = dataSource.next().partition { history.contains(it.uniqueId) } old.forEach { history.add(it.uniqueId) } // Calculate at which time to poll for new data val backoffMillis = backoff.delayRequest(old.size, new.size + old.size) require(backoffMillis >= 0) { "delayRequest must return a non-negative integer, was $backoffMillis" } resumeTimeMillis = System.currentTimeMillis() + backoff.delayRequest(old.size, new.size + old.size) // Yield in reverse order so that if more than one unseen item is present the older items are yielded first if (old.isNotEmpty()) newDataIterator = old.asReversed().iterator() } return newDataIterator } }
mit
415a91e4c81e3bf79326ea9b2ae61997
35.650794
119
0.653963
4.572277
false
false
false
false
onoderis/failchat
src/main/kotlin/failchat/peka2tv/Peka2tvApiClient.kt
1
3150
package failchat.peka2tv import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import failchat.chat.ImageFormat.RASTER import failchat.chat.badge.ImageBadge import failchat.exception.UnexpectedResponseCodeException import failchat.exception.UnexpectedResponseException import failchat.util.emptyBody import failchat.util.jsonMediaType import failchat.util.thenUse import failchat.util.toFuture import failchat.util.withSuffix import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import java.util.concurrent.CompletableFuture class Peka2tvApiClient( private val httpClient: OkHttpClient, private val objectMapper: ObjectMapper, apiUrl: String ) { private val apiUrl = apiUrl.withSuffix("/") fun findUser(name: String): CompletableFuture<Peka2tvUser> { val requestBody = objectMapper.createObjectNode() .put("name", name) return request("/user", requestBody) .thenApply { Peka2tvUser(name, it.get("id").asLong()) } } fun requestBadges(): CompletableFuture<Map<Peka2tvBadgeId, ImageBadge>> { // https@ //github.com/peka2tv/api/blob/master/smile.md#%D0%98%D0%BA%D0%BE%D0%BD%D0%BA%D0%B8 return request("/icon/list") .thenApply { it.map { badgeNode -> badgeNode.get("id").longValue() to ImageBadge( badgeNode.get("url").textValue(), RASTER, badgeNode.get("user").get("name").textValue() + " subscriber" ) } .toMap() } } fun requestEmoticons(): CompletableFuture<List<Peka2tvEmoticon>> { // https://github.com/peka2tv/api/blob/master/smile.md#Смайлы return request("/smile") .thenApply { it.map { node -> Peka2tvEmoticon( node.get("code").asText(), node.get("url").asText(), node.get("id").longValue() ) } } } fun request(path: String, body: JsonNode? = null): CompletableFuture<JsonNode> { val request = Request.Builder() .url(apiUrl + path.removePrefix("/")) .post(body?.toRequestBody() ?: emptyBody) .header("User-Agent", "failchat client") .header("Accept", "application/json; version=1.0") .build() return httpClient.newCall(request) .toFuture() .thenUse { if (it.code != 200) throw UnexpectedResponseCodeException(it.code) val responseBody = it.body ?: throw UnexpectedResponseException("null body") return@thenUse objectMapper.readTree(responseBody.string()) } } private fun JsonNode.toRequestBody() = RequestBody.create(jsonMediaType, this.toString()) }
gpl-3.0
7137679a369397705b5c0f779fd035d7
36.428571
100
0.573473
4.792683
false
false
false
false
Maccimo/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesSmartSearchField.kt
4
3650
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages import com.intellij.openapi.application.EDT import com.intellij.openapi.project.Project import com.intellij.ui.SearchTextField import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.extensibility.Subscription import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.withContext import java.awt.Dimension import java.awt.event.KeyEvent class PackagesSmartSearchField( searchFieldFocus: Flow<Unit>, project: Project ) : SearchTextField(false) { init { @Suppress("MagicNumber") // Swing dimension constants PackageSearchUI.setHeight(this, height = 25) @Suppress("MagicNumber") // Swing dimension constants minimumSize = Dimension(100.scaled(), minimumSize.height) textEditor.setTextToTriggerEmptyTextStatus(PackageSearchBundle.message("packagesearch.search.hint")) textEditor.emptyText.isShowAboveCenter = true PackageSearchUI.overrideKeyStroke(textEditor, "shift ENTER", this::transferFocusBackward) searchFieldFocus .onEach { withContext(Dispatchers.EDT) { requestFocus() } } .launchIn(project.lifecycleScope) } /** * Trying to navigate to the first element in the brief list * @return true in case of success; false if the list is empty */ var goToTable: () -> Boolean = { false } var fieldClearedListener: (() -> Unit)? = null private val listeners = mutableSetOf<(KeyEvent) -> Unit>() fun registerOnKeyPressedListener(action: (KeyEvent) -> Unit): Subscription { listeners.add(action) return Subscription { listeners.remove(action) } } override fun preprocessEventForTextField(e: KeyEvent?): Boolean { e?.let { keyEvent -> listeners.forEach { listener -> listener(keyEvent) } } if (e?.keyCode == KeyEvent.VK_DOWN || e?.keyCode == KeyEvent.VK_PAGE_DOWN) { goToTable() // trying to navigate to the list instead of "show history" e.consume() // suppress default "show history" logic anyway return true } return super.preprocessEventForTextField(e) } override fun getBackground() = PackageSearchUI.HeaderBackgroundColor override fun onFocusLost() { super.onFocusLost() addCurrentTextToHistory() } override fun onFieldCleared() { super.onFieldCleared() fieldClearedListener?.invoke() } }
apache-2.0
de989c479e0090607523f88dc79ac672
38.247312
108
0.69589
4.860186
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/commands/MarksCommand.kt
1
1951
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.commands import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.ex.ranges.Ranges import com.maddyhome.idea.vim.helper.EngineStringHelper import com.maddyhome.idea.vim.vimscript.model.ExecutionResult /** * see "h :marks" */ data class MarksCommand(val ranges: Ranges, val argument: String) : Command.SingleExecution(ranges, argument) { override val argFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_OPTIONAL, Access.READ_ONLY) override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult { // Yeah, lower case. Vim uses lower case here, but Title Case in :registers. Go figure. val res = injector.markGroup.getMarks(editor) .filter { argument.isEmpty() || argument.contains(it.key) } .joinToString("\n", prefix = "mark line col file/text\n") { mark -> // Lines are 1 based, columns zero based. See :help :marks val line = (mark.line + 1).toString().padStart(5) val column = mark.col.toString().padStart(3) val vf = editor.getVirtualFile() val text = if (vf != null && vf.path == mark.filename) { val lineText = editor.getLineText(mark.line).trim().take(200) EngineStringHelper.toPrintableCharacters(injector.parser.stringToKeys(lineText)).take(200) } else { mark.filename } " ${mark.key} $line $column $text" } injector.exOutputPanel.getPanel(editor).output(res) return ExecutionResult.Success } }
mit
2462baec09ae225a048e1452d42d9552
38.02
132
0.712455
3.917671
false
false
false
false
edwardharks/Aircraft-Recognition
feedback/src/main/kotlin/com/edwardharker/aircraftrecognition/ui/feedback/FeedbackDialogFragment.kt
1
2813
package com.edwardharker.aircraftrecognition.ui.feedback import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import android.widget.EditText import androidx.appcompat.app.AppCompatDialogFragment import com.edwardharker.aircraftrecognition.feedback.FeedbackView import com.edwardharker.aircraftrecognition.feedback.feedbackPresenter import com.edwardharker.aircraftrecognition.ui.Navigator import com.edwardharker.aircraftrecognition.ui.showKeyboard import com.edwardharker.aircraftrecognition.ui.toast fun Navigator.launchFeedbackDialog() { val fragmentManager = activity.supportFragmentManager val fragment = FeedbackDialogFragment.newInstance() fragment.show(fragmentManager, FeedbackDialogFragment.TAG) } class FeedbackDialogFragment : AppCompatDialogFragment(), FeedbackView { private val presenter = feedbackPresenter() private val handler = Handler() private val dismissRunnable = { dismiss() } private lateinit var enterFeedbackGroup: View private lateinit var feedbackConfirmationGroup: View override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.fragment_dialog_feedback, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val messageEditText = view.findViewById<EditText>(R.id.feedback_message) val submitButton = view.findViewById<View>(R.id.submit_button) enterFeedbackGroup = view.findViewById(R.id.enter_feedback_group) feedbackConfirmationGroup = view.findViewById(R.id.feedback_confirmation_group) messageEditText.showKeyboard() submitButton.setOnClickListener { presenter.submitFeedback(messageEditText.text.toString()) } } override fun onStart() { super.onStart() presenter.startPresenting(this) } override fun onStop() { super.onStop() presenter.stopPresenting() handler.removeCallbacks(dismissRunnable) } override fun showSuccess() { enterFeedbackGroup.visibility = GONE feedbackConfirmationGroup.visibility = VISIBLE handler.postDelayed(dismissRunnable, DISMISS_DELAY) } override fun showValidationError() { toast(R.string.feedback_validation_error) } companion object { private const val DISMISS_DELAY = 2000L const val TAG = "FeedbackDialogFragment" fun newInstance(): FeedbackDialogFragment { return FeedbackDialogFragment() } } }
gpl-3.0
6decac00891d61e3d566d0a123aedc29
32.891566
87
0.740491
5.152015
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/repository/ArtistRepositoryImpl.kt
1
1956
package com.kelsos.mbrc.repository import com.kelsos.mbrc.data.library.Artist import com.kelsos.mbrc.di.modules.AppDispatchers import com.kelsos.mbrc.repository.data.LocalArtistDataSource import com.kelsos.mbrc.repository.data.RemoteArtistDataSource import com.raizlabs.android.dbflow.list.FlowCursorList import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.withContext import org.threeten.bp.Instant import javax.inject.Inject class ArtistRepositoryImpl @Inject constructor( private val localDataSource: LocalArtistDataSource, private val remoteDataSource: RemoteArtistDataSource, private val dispatchers: AppDispatchers ) : ArtistRepository { override suspend fun getArtistByGenre(genre: String): FlowCursorList<Artist> = localDataSource.getArtistByGenre(genre) override suspend fun getAllCursor(): FlowCursorList<Artist> = localDataSource.loadAllCursor() override suspend fun getAndSaveRemote(): FlowCursorList<Artist> { getRemote() return localDataSource.loadAllCursor() } override suspend fun getRemote() { val epoch = Instant.now().epochSecond withContext(dispatchers.io) { remoteDataSource.fetch() .onCompletion { localDataSource.removePreviousEntries(epoch) } .collect { artists -> val data = artists.map { it.apply { dateAdded = epoch } } localDataSource.saveAll(data) } } } override suspend fun search(term: String): FlowCursorList<Artist> = localDataSource.search(term) override suspend fun getAlbumArtistsOnly(): FlowCursorList<Artist> = localDataSource.getAlbumArtists() override suspend fun getAllRemoteAndShowAlbumArtist(): FlowCursorList<Artist> { getRemote() return localDataSource.getAlbumArtists() } override suspend fun cacheIsEmpty(): Boolean = localDataSource.isEmpty() override suspend fun count(): Long = localDataSource.count() }
gpl-3.0
1e6df2e3bc3cf3a078fdbeff5ce592c8
32.152542
98
0.767382
4.713253
false
false
false
false
simoneapp/S3-16-simone
app/src/main/java/app/simone/shared/utils/Analytics.kt
2
2032
package app.simone.shared.utils import android.content.Context import android.os.Bundle import com.google.firebase.analytics.FirebaseAnalytics /** * Created by nicola on 12/10/2017. */ enum class AnalyticsAppAction { SINGLE_PLAYER_TOUCHED, MULTI_PLAYER_TOUCHED, SETTINGS_TOUCHED, SCOREBOARD_TOUCHED, CREDITS_TOUCHED, GAME_START_TOUCHED } class Analytics { companion object { fun logAchievement(name: String, context: Context) { val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, FirebaseAnalytics.Event.UNLOCK_ACHIEVEMENT) bundle.putString(FirebaseAnalytics.Param.ACHIEVEMENT_ID, name) log(context, bundle) } fun logAppOpen(context: Context) { val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, FirebaseAnalytics.Event.APP_OPEN) log(context, bundle) } fun logScore(score: Int, context: Context) { val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, FirebaseAnalytics.Event.POST_SCORE) bundle.putString(FirebaseAnalytics.Param.SCORE, score.toString()) log(context, bundle) } fun logAppAction(type: AnalyticsAppAction, context: Context) { val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, type.toString()) log(context, bundle) } fun logNewSinglePlayerGame(type: Int, context: Context) { val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "NEW_SINGLE_PLAYER_GAME") bundle.putString("SINGLE_PLAYER_TYPE", type.toString()) log(context, bundle) } private fun log(context: Context, bundle: Bundle) { val analytics = FirebaseAnalytics.getInstance(context) analytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle) } } }
mit
ba6ab53e2913e1077e15903f8ebee8ec
31.269841
110
0.651083
4.556054
false
false
false
false
DanielGrech/anko
dsl/testData/compile/AndroidLayoutParamsTest.kt
3
2488
package com.example.android_test import android.app.Activity import android.os.Bundle import org.jetbrains.anko.* import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.AbsoluteLayout import android.widget.FrameLayout import android.widget.GridLayout import android.view.Gravity public open class MyActivity() : Activity() { public override fun onCreate(savedInstanceState: Bundle?): Unit { super.onCreate(savedInstanceState) UI { linearLayout { editText { layoutParams(-2, -2) { bottomMargin = 1 leftMargin = 2 rightMargin = 3 topMargin = 4 height = 9 gravity = Gravity.RIGHT weight = 1.3591409142295225f } } } relativeLayout { editText { layoutParams(-2, -2) { bottomMargin = 1 leftMargin = 2 rightMargin = 3 topMargin = 4 height = 9 addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE) addRule(RelativeLayout.CENTER_IN_PARENT) } } } absoluteLayout { editText { layoutParams(-2, -2, 12, 23) { height = 9 x = 100 y = 200 } } } frameLayout { editText { layoutParams(-2, -2) { bottomMargin = 1 leftMargin = 2 rightMargin = 3 topMargin = 4 height = 9 gravity = Gravity.RIGHT } } } gridLayout { editText { layoutParams() { bottomMargin = 1 leftMargin = 2 rightMargin = 3 topMargin = 4 height = 9 gravity = Gravity.RIGHT } } } } } }
apache-2.0
6ffb5231e212b449713979f18f7f10a0
30.506329
86
0.38746
6.853994
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/jvm-debugger/test/testData/stepping/stepInto/continueLabel.kt
13
226
package continueLabel fun main(args: Array<String>) { //Breakpoint! for(el in 0..1) { val a1 = 1 if (el == 0) { continue } val a2 = 2 } val a3 = 3 } // STEP_INTO: 9
apache-2.0
fa5f746fb4a4d76d23a5a97efd4051b4
14.133333
31
0.446903
3.183099
false
false
false
false
SimpleMobileTools/Simple-Music-Player
app/src/main/kotlin/com/simplemobiletools/musicplayer/helpers/M3uExporter.kt
1
1708
package com.simplemobiletools.musicplayer.helpers import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.extensions.showErrorToast import com.simplemobiletools.commons.extensions.toast import com.simplemobiletools.commons.extensions.writeLn import com.simplemobiletools.musicplayer.R import com.simplemobiletools.musicplayer.models.Track import java.io.OutputStream class M3uExporter(val activity: BaseSimpleActivity) { var failedEvents = 0 var exportedEvents = 0 enum class ExportResult { EXPORT_FAIL, EXPORT_OK, EXPORT_PARTIAL } fun exportPlaylist( outputStream: OutputStream?, tracks: ArrayList<Track>, callback: (result: ExportResult) -> Unit ) { if (outputStream == null) { callback(ExportResult.EXPORT_FAIL) return } activity.toast(R.string.exporting) try { outputStream.bufferedWriter().use { out -> out.writeLn(M3U_HEADER) for (track in tracks) { out.writeLn(M3U_ENTRY + track.duration + M3U_DURATION_SEPARATOR + track.artist + " - " + track.title) out.writeLn(track.path) exportedEvents++ } } } catch (e: Exception) { failedEvents++ activity.showErrorToast(e) } finally { outputStream.close() } callback( when { exportedEvents == 0 -> ExportResult.EXPORT_FAIL failedEvents > 0 -> ExportResult.EXPORT_PARTIAL else -> ExportResult.EXPORT_OK } ) } }
gpl-3.0
afaec0e8dcba607c70be409cc70a1e83
30.054545
121
0.606557
4.811268
false
false
false
false
spinnaker/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteTaskHandlerTest.kt
2
13398
/* * Copyright 2017 Netflix, 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.netflix.spinnaker.orca.q.handler import com.netflix.spectator.api.NoopRegistry import com.netflix.spinnaker.orca.DefaultStageResolver import com.netflix.spinnaker.orca.NoOpTaskImplementationResolver import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.CANCELED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.FAILED_CONTINUE import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.REDIRECT import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SKIPPED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.STOPPED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.api.pipeline.models.TaskExecution import com.netflix.spinnaker.orca.api.test.pipeline import com.netflix.spinnaker.orca.api.test.stage import com.netflix.spinnaker.orca.events.TaskComplete import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.model.TaskExecutionImpl import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.q.CompleteStage import com.netflix.spinnaker.orca.q.CompleteTask import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.orca.q.SkipStage import com.netflix.spinnaker.orca.q.StageDefinitionBuildersProvider import com.netflix.spinnaker.orca.q.StartTask import com.netflix.spinnaker.orca.q.buildTasks import com.netflix.spinnaker.orca.q.get import com.netflix.spinnaker.orca.q.multiTaskStage import com.netflix.spinnaker.orca.q.rollingPushStage import com.netflix.spinnaker.orca.q.singleTaskStage import com.netflix.spinnaker.q.Queue import com.netflix.spinnaker.spek.and import com.netflix.spinnaker.time.fixedClock import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.check import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.never import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyZeroInteractions import com.nhaarman.mockito_kotlin.whenever import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek import org.springframework.context.ApplicationEventPublisher object CompleteTaskHandlerTest : SubjectSpek<CompleteTaskHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val publisher: ApplicationEventPublisher = mock() val clock = fixedClock() val stageResolver = DefaultStageResolver(StageDefinitionBuildersProvider(emptyList())) subject(GROUP) { CompleteTaskHandler(queue, repository, DefaultStageDefinitionBuilderFactory(stageResolver), ContextParameterProcessor(), publisher, clock, NoopRegistry()) } fun resetMocks() = reset(queue, repository, publisher) setOf(SUCCEEDED, SKIPPED).forEach { successfulStatus -> describe("when a task completes with $successfulStatus status") { given("the stage contains further tasks") { val pipeline = pipeline { stage { type = multiTaskStage.type multiTaskStage.buildTasks(this, NoOpTaskImplementationResolver()) } } val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1", successfulStatus, successfulStatus ) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the task state in the stage") { verify(repository).storeStage( check { it.tasks.first().apply { assertThat(status).isEqualTo(successfulStatus) assertThat(endTime).isEqualTo(clock.millis()) } } ) } it("runs the next task") { verify(queue) .push( StartTask( message.executionType, message.executionId, message.application, message.stageId, "2" ) ) } it("publishes an event") { verify(publisher).publishEvent( check<TaskComplete> { assertThat(it.executionType).isEqualTo(pipeline.type) assertThat(it.executionId).isEqualTo(pipeline.id) assertThat(it.stage.id).isEqualTo(message.stageId) assertThat(it.task.id).isEqualTo(message.taskId) assertThat(it.task.status).isEqualTo(successfulStatus) } ) } } given("the stage is complete") { val pipeline = pipeline { stage { type = singleTaskStage.type singleTaskStage.buildTasks(this, NoOpTaskImplementationResolver()) } } val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1", SUCCEEDED, SUCCEEDED ) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the task state in the stage") { verify(repository).storeStage( check { it.tasks.last().apply { assertThat(status).isEqualTo(SUCCEEDED) assertThat(endTime).isEqualTo(clock.millis()) } } ) } it("emits an event to signal the stage is complete") { verify(queue) .push( CompleteStage( message.executionType, message.executionId, message.application, message.stageId ) ) } } given("the task is the end of a rolling push loop") { val pipeline = pipeline { stage { refId = "1" type = rollingPushStage.type rollingPushStage.buildTasks(this, NoOpTaskImplementationResolver()) } } and("when the task returns REDIRECT") { val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stageByRef("1").id, "4", REDIRECT, REDIRECT ) beforeGroup { pipeline.stageByRef("1").apply { tasks[0].status = SUCCEEDED tasks[1].status = SUCCEEDED tasks[2].status = SUCCEEDED } whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("repeats the loop") { verify(queue).push( check<StartTask> { assertThat(it.taskId).isEqualTo("2") } ) } it("resets the status of the loop tasks") { verify(repository).storeStage( check { assertThat(it.tasks[1..3].map(TaskExecution::getStatus)).allMatch { it == NOT_STARTED } } ) } it("does not publish an event") { verifyZeroInteractions(publisher) } } } } } setOf(TERMINAL, CANCELED, STOPPED).forEach { status -> describe("when a task completes with $status status") { val pipeline = pipeline { stage { type = multiTaskStage.type multiTaskStage.buildTasks(this, NoOpTaskImplementationResolver()) } } val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1", status, status ) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the task state in the stage") { verify(repository).storeStage( check { it.tasks.first().apply { assertThat(status).isEqualTo(status) assertThat(endTime).isEqualTo(clock.millis()) } } ) } it("fails the stage") { verify(queue).push( CompleteStage( message.executionType, message.executionId, message.application, message.stageId ) ) } it("does not run the next task") { verify(queue, never()).push(any<RunTask>()) } it("publishes an event") { verify(publisher).publishEvent( check<TaskComplete> { assertThat(it.executionType).isEqualTo(pipeline.type) assertThat(it.executionId).isEqualTo(pipeline.id) assertThat(it.stage.id).isEqualTo(message.stageId) assertThat(it.task.id).isEqualTo(message.taskId) assertThat(it.task.status).isEqualTo(status) } ) } } } describe("when a task should complete parent stage") { val task = fun(isStageEnd: Boolean): TaskExecution { val task = TaskExecutionImpl() task.isStageEnd = isStageEnd return task } it("is last task in stage") { subject.shouldCompleteStage(task(true), SUCCEEDED, SUCCEEDED) == true subject.shouldCompleteStage(task(false), SUCCEEDED, SUCCEEDED) == false } it("did not originally complete with FAILED_CONTINUE") { subject.shouldCompleteStage(task(false), TERMINAL, TERMINAL) == true subject.shouldCompleteStage(task(false), FAILED_CONTINUE, TERMINAL) == true subject.shouldCompleteStage(task(false), FAILED_CONTINUE, FAILED_CONTINUE) == false } } describe("manual skip behavior") { given("a stage with a manual skip flag") { val pipeline = pipeline { stage { refId = "1" type = singleTaskStage.type singleTaskStage.buildTasks(this, NoOpTaskImplementationResolver()) context["manualSkip"] = true } } val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stageByRef("1").id, "1", SKIPPED, SKIPPED ) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("skips the stage") { verify(queue).push(SkipStage(pipeline.stageByRef("1"))) } } given("a stage whose parent has a manual skip flag") { val pipeline = pipeline { stage { refId = "1" type = singleTaskStage.type singleTaskStage.buildTasks(this, NoOpTaskImplementationResolver()) context["manualSkip"] = true stage { refId = "1<1" type = singleTaskStage.type singleTaskStage.buildTasks(this, NoOpTaskImplementationResolver()) } } } val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stageByRef("1<1").id, "1", SKIPPED, SKIPPED ) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("skips the parent stage") { verify(queue).push(SkipStage(pipeline.stageByRef("1"))) } } } })
apache-2.0
6e828bcb8d8b9fd876dd0b1933335e26
30.673759
158
0.628303
4.814229
false
false
false
false
Emberwalker/Artemis-Kotlin
src/main/kotlin/io/drakon/artemis/Artemis.kt
1
1869
package io.drakon.artemis import io.drakon.artemis.logging.ExitLogThread import io.drakon.artemis.logging.ModMapper import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger import net.minecraftforge.fml.common.Mod as mod import net.minecraftforge.fml.common.Mod.EventHandler as eventHandler import net.minecraftforge.fml.common.event.FMLPreInitializationEvent import net.minecraftforge.fml.common.event.FMLInitializationEvent import net.minecraftforge.fml.common.event.FMLPostInitializationEvent import io.drakon.artemis.logging.TracingPrintStream import io.drakon.artemis.management.Config /** * Artemis * * STDOUT/STDERR Redirection * * @author Arkan <[email protected]> */ [mod(modid = "Artemis", name = "Artemis (Kotlin Experimental)", dependencies = "before:*", acceptableRemoteVersions="*", modLanguage = "kotlin")] class Artemis { companion object { public val logger: Logger = LogManager.getLogger("Artemis/Core") public val outLog: Logger = LogManager.getLogger("Artemis/STDOUT") public val errLog: Logger = LogManager.getLogger("Artemis/STDERR") } eventHandler fun preInit(evt: FMLPreInitializationEvent) { logger.info("Beginning preflight.") logger.info("Loading config...") Config.loadConfig(evt.getSuggestedConfigurationFile()) logger.info("Injecting print streams...") System.setOut(TracingPrintStream(outLog, System.out)) System.setErr(TracingPrintStream(errLog, System.err)) if (Config.blamefile) { logger.info("Injecting JVM shutdown hook...") Runtime.getRuntime().addShutdownHook(ExitLogThread()) } if (Config.logging.mapModIds) ModMapper.init() println("Artemis test.") System.err.println("Artemis error.") logger.info("Preflight complete.") } }
mit
e93f632f2a7063d287f86270b6592946
31.224138
145
0.724987
4.144124
false
true
false
false
GunoH/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/output/InlayScratchFileRenderer.kt
2
1936
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.scratch.output import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorCustomElementRenderer import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.impl.ComplementaryFontsRegistry import com.intellij.openapi.editor.impl.FontInfo import com.intellij.openapi.editor.markup.TextAttributes import java.awt.Graphics import java.awt.Rectangle class InlayScratchFileRenderer(val text: String, private val outputType: ScratchOutputType) : EditorCustomElementRenderer { private fun getFontInfo(editor: Editor): FontInfo { val colorsScheme = editor.colorsScheme val fontPreferences = colorsScheme.fontPreferences val attributes = getAttributesForOutputType(outputType) val fontStyle = attributes.fontType return ComplementaryFontsRegistry.getFontAbleToDisplay( 'a'.code, fontStyle, fontPreferences, FontInfo.getFontRenderContext(editor.contentComponent) ) } override fun calcWidthInPixels(inlay: Inlay<*>): Int { val fontInfo = getFontInfo(inlay.editor) return fontInfo.fontMetrics().stringWidth(text) } override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) { val attributes = getAttributesForOutputType(outputType) val fgColor = attributes.foregroundColor ?: return g.color = fgColor val fontInfo = getFontInfo(inlay.editor) g.font = fontInfo.font val metrics = fontInfo.fontMetrics() g.drawString(text, targetRegion.x, targetRegion.y + metrics.ascent) } override fun toString(): String { return "${text.takeWhile { it.isWhitespace() }}${outputType.name}: ${text.trim()}" } }
apache-2.0
1b3ed3e2fb545a05902deefb2781a6da
44.023256
158
0.742252
4.533958
false
false
false
false
GunoH/intellij-community
platform/editor-ui-api/src/com/intellij/ide/ui/UISettingsState.kt
4
8547
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.ui import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.ReportValue import com.intellij.openapi.util.SystemInfo import com.intellij.ui.scale.JBUIScale import com.intellij.util.PlatformUtils import com.intellij.util.xmlb.annotations.OptionTag import com.intellij.util.xmlb.annotations.Transient import javax.swing.SwingConstants class UISettingsState : BaseState() { companion object { /** * Returns the default font size scaled by #defFontScale * * @return the default scaled font size */ @JvmStatic val defFontSize: Float get() = JBUIScale.DEF_SYSTEM_FONT_SIZE * UISettings.defFontScale } @get:OptionTag("FONT_FACE") @Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.fontFace")) var fontFace by string() @get:OptionTag("FONT_SIZE") @Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.fontSize")) var fontSize by property(0) @get:OptionTag("FONT_SCALE") @Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.fontScale")) var fontScale by property(0f) @get:ReportValue @get:OptionTag("RECENT_FILES_LIMIT") var recentFilesLimit by property(50) @get:ReportValue @get:OptionTag("RECENT_LOCATIONS_LIMIT") var recentLocationsLimit by property(25) @get:OptionTag("CONSOLE_COMMAND_HISTORY_LIMIT") var consoleCommandHistoryLimit by property(300) @get:OptionTag("OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE") var overrideConsoleCycleBufferSize by property(false) @get:OptionTag("CONSOLE_CYCLE_BUFFER_SIZE_KB") var consoleCycleBufferSizeKb by property(1024) @get:ReportValue @get:OptionTag("EDITOR_TAB_LIMIT") var editorTabLimit by property(10) @get:OptionTag("REUSE_NOT_MODIFIED_TABS") var reuseNotModifiedTabs by property(false) @get:OptionTag("OPEN_TABS_IN_MAIN_WINDOW") var openTabsInMainWindow by property(false) @get:OptionTag("OPEN_IN_PREVIEW_TAB_IF_POSSIBLE") var openInPreviewTabIfPossible by property(false) @get:OptionTag("SHOW_TOOL_WINDOW_NUMBERS") var showToolWindowsNumbers by property(false) @get:OptionTag("HIDE_TOOL_STRIPES") var hideToolStripes by property(false) @get:OptionTag("WIDESCREEN_SUPPORT") var wideScreenSupport by property(false) @get:OptionTag("LEFT_HORIZONTAL_SPLIT") var leftHorizontalSplit by property(false) @get:OptionTag("RIGHT_HORIZONTAL_SPLIT") var rightHorizontalSplit by property(false) @get:OptionTag("SHOW_EDITOR_TOOLTIP") var showEditorToolTip by property(true) @get:OptionTag("SHOW_WRITE_THREAD_INDICATOR") var showWriteThreadIndicator by property(false) @get:OptionTag("ALLOW_MERGE_BUTTONS") var allowMergeButtons by property(true) @get:OptionTag("SHOW_MAIN_TOOLBAR") var showMainToolbar by property(false) @get:OptionTag("SHOW_STATUS_BAR") var showStatusBar by property(true) @get:OptionTag("SHOW_MAIN_MENU") var showMainMenu by property(true) @get:OptionTag("SHOW_NAVIGATION_BAR") var showNavigationBar by property(true) @get:OptionTag("NAVIGATION_BAR_LOCATION") var navigationBarLocation by enum(NavBarLocation.BOTTOM) @get:OptionTag("SHOW_NAVIGATION_BAR_MEMBERS") var showMembersInNavigationBar by property(true) @get:OptionTag("SCROLL_TAB_LAYOUT_IN_EDITOR") var scrollTabLayoutInEditor by property(true) @get:OptionTag("HIDE_TABS_IF_NEED") var hideTabsIfNeeded by property(true) @get:OptionTag("SHOW_PINNED_TABS_IN_A_SEPARATE_ROW") var showPinnedTabsInASeparateRow by property(false) @get:OptionTag("SHOW_CLOSE_BUTTON") var showCloseButton by property(true) @get:OptionTag("CLOSE_TAB_BUTTON_ON_THE_RIGHT") var closeTabButtonOnTheRight by property(true) @get:OptionTag("EDITOR_TAB_PLACEMENT") @get:ReportValue var editorTabPlacement: Int by property(SwingConstants.TOP) @get:OptionTag("SHOW_FILE_ICONS_IN_TABS") var showFileIconInTabs by property(true) @get:OptionTag("HIDE_KNOWN_EXTENSION_IN_TABS") var hideKnownExtensionInTabs by property(false) var showTreeIndentGuides by property(false) var compactTreeIndents by property(false) @get:OptionTag("SORT_TABS_ALPHABETICALLY") var sortTabsAlphabetically by property(false) @get:OptionTag("KEEP_TABS_ALPHABETICALLY_SORTED") var alwaysKeepTabsAlphabeticallySorted by property(false) @get:OptionTag("OPEN_TABS_AT_THE_END") var openTabsAtTheEnd by property(false) @get:OptionTag("CLOSE_NON_MODIFIED_FILES_FIRST") var closeNonModifiedFilesFirst by property(false) @get:OptionTag("ACTIVATE_MRU_EDITOR_ON_CLOSE") var activeMruEditorOnClose by property(false) // TODO[anton] consider making all IDEs use the same settings @get:OptionTag("ACTIVATE_RIGHT_EDITOR_ON_CLOSE") var activeRightEditorOnClose by property(PlatformUtils.isAppCode()) @get:OptionTag("IDE_AA_TYPE") @Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.ideAAType")) internal var ideAAType by enum(AntialiasingType.SUBPIXEL) @get:OptionTag("EDITOR_AA_TYPE") @Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.editorAAType")) internal var editorAAType by enum(AntialiasingType.SUBPIXEL) @get:OptionTag("COLOR_BLINDNESS") var colorBlindness by enum<ColorBlindness>() @get:OptionTag("CONTRAST_SCROLLBARS") var useContrastScrollBars by property(false) @get:OptionTag("MOVE_MOUSE_ON_DEFAULT_BUTTON") var moveMouseOnDefaultButton by property(false) @get:OptionTag("ENABLE_ALPHA_MODE") var enableAlphaMode by property(false) @get:OptionTag("ALPHA_MODE_DELAY") var alphaModeDelay by property(1500) @get:OptionTag("ALPHA_MODE_RATIO") var alphaModeRatio by property(0.5f) @get:OptionTag("OVERRIDE_NONIDEA_LAF_FONTS") var overrideLafFonts by property(false) @get:OptionTag("SHOW_ICONS_IN_MENUS") var showIconsInMenus by property(true) // IDEADEV-33409, should be disabled by default on MacOS @get:OptionTag("DISABLE_MNEMONICS") var disableMnemonics by property(SystemInfo.isMac) @get:OptionTag("DISABLE_MNEMONICS_IN_CONTROLS") var disableMnemonicsInControls by property(false) @get:OptionTag("USE_SMALL_LABELS_ON_TABS") var useSmallLabelsOnTabs by property(SystemInfo.isMac) @get:OptionTag("MAX_LOOKUP_WIDTH2") var maxLookupWidth by property(500) @get:OptionTag("MAX_LOOKUP_LIST_HEIGHT") var maxLookupListHeight by property(11) @get:OptionTag("DND_WITH_PRESSED_ALT_ONLY") var dndWithPressedAltOnly by property(false) @get:OptionTag("SEPARATE_MAIN_MENU") var separateMainMenu by property(false) @get:OptionTag("DEFAULT_AUTOSCROLL_TO_SOURCE") var defaultAutoScrollToSource by property(false) @get:Transient var presentationMode: Boolean = false @get:OptionTag("PRESENTATION_MODE_FONT_SIZE") var presentationModeFontSize by property(24) @get:OptionTag("MARK_MODIFIED_TABS_WITH_ASTERISK") var markModifiedTabsWithAsterisk by property(false) @get:OptionTag("SHOW_TABS_TOOLTIPS") var showTabsTooltips by property(true) @get:OptionTag("SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES") var showDirectoryForNonUniqueFilenames by property(true) var smoothScrolling by property(true) @get:OptionTag("NAVIGATE_TO_PREVIEW") var navigateToPreview by property(false) @get:OptionTag("FULL_PATHS_IN_TITLE_BAR") var fullPathsInWindowHeader by property(false) @get:OptionTag("BORDERLESS_MODE") var mergeMainMenuWithWindowTitle by property(SystemInfo.isWin10OrNewer && SystemInfo.isJetBrainsJvm) var animatedScrolling by property(!SystemInfo.isMac || !SystemInfo.isJetBrainsJvm) var animatedScrollingDuration by property( when { SystemInfo.isWindows -> 200 SystemInfo.isMac -> 50 else -> 150 } ) var animatedScrollingCurvePoints by property( when { SystemInfo.isWindows -> 1684366536 SystemInfo.isMac -> 845374563 else -> 729434056 } ) @get:OptionTag("SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY") var sortLookupElementsLexicographically by property(false) @get:OptionTag("MERGE_EQUAL_STACKTRACES") var mergeEqualStackTraces by property(true) @get:OptionTag("SORT_BOOKMARKS") var sortBookmarks by property(false) @get:OptionTag("PIN_FIND_IN_PATH_POPUP") var pinFindInPath by property(false) @get:OptionTag("SHOW_INPLACE_COMMENTS") var showInplaceComments by property(false) @get:OptionTag("SHOW_VISUAL_FORMATTING_LAYER") var showVisualFormattingLayer by property(false) @Suppress("FunctionName") fun _incrementModificationCount() = incrementModificationCount() }
apache-2.0
3669318d888c69a5eba266f3538be44b
38.027397
120
0.770095
4.001404
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/StoryViewerPagerAdapter.kt
1
1609
package org.thoughtcrime.securesms.stories.viewer import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DiffUtil import androidx.viewpager2.adapter.FragmentStateAdapter import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.stories.viewer.page.StoryViewerPageFragment class StoryViewerPagerAdapter( fragment: Fragment, private val initialStoryId: Long, private val isFromNotification: Boolean, private val groupReplyStartPosition: Int ) : FragmentStateAdapter(fragment) { private var pages: List<RecipientId> = emptyList() fun setPages(newPages: List<RecipientId>) { val oldPages = pages pages = newPages val callback = Callback(oldPages, pages) DiffUtil.calculateDiff(callback).dispatchUpdatesTo(this) } override fun getItemCount(): Int = pages.size override fun createFragment(position: Int): Fragment { return StoryViewerPageFragment.create(pages[position], initialStoryId, isFromNotification, groupReplyStartPosition) } private class Callback( private val oldList: List<RecipientId>, private val newList: List<RecipientId> ) : DiffUtil.Callback() { override fun getOldListSize(): Int = oldList.size override fun getNewListSize(): Int = newList.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition] == newList[newItemPosition] } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition] == newList[newItemPosition] } } }
gpl-3.0
b17406f861259258fc04f1086b721e31
32.520833
119
0.773773
4.920489
false
false
false
false
AsamK/TextSecure
contacts/app/src/main/java/org/signal/contactstest/ContactLookupActivity.kt
2
1177
package org.signal.contactstest import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class ContactLookupActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_contact_lookup) val list: RecyclerView = findViewById(R.id.list) val adapter = ContactsAdapter { uri -> startActivity( Intent(Intent.ACTION_VIEW).apply { data = uri } ) } list.layoutManager = LinearLayoutManager(this) list.adapter = adapter val viewModel: ContactLookupViewModel by viewModels() viewModel.contacts.observe(this) { adapter.submitList(it) } val lookupText: TextView = findViewById(R.id.lookup_text) val lookupButton: Button = findViewById(R.id.lookup_button) lookupButton.setOnClickListener { viewModel.onLookup(lookupText.text.toString()) } } }
gpl-3.0
9bf9497a425f35b5916748b30fef0010
28.425
63
0.750212
4.544402
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-plugins/ktor-server-html-builder/jvmAndNix/src/io/ktor/server/html/Template.kt
1
3131
/* * 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.server.html /** * A template that expands inside [TOuter]. * @see [respondHtmlTemplate] */ public interface Template<in TOuter> { public fun TOuter.apply() } /** * A placeholder that is inserted inside [TOuter]. * @see [respondHtmlTemplate] */ public open class Placeholder<TOuter> { private var content: TOuter.(Placeholder<TOuter>) -> Unit = { } public var meta: String = "" public operator fun invoke(meta: String = "", content: TOuter.(Placeholder<TOuter>) -> Unit) { this.content = content this.meta = meta } public fun apply(destination: TOuter) { destination.content(this) } } /** * A placeholder that can be used to insert the content that appears multiple times (for example, list items). * @see [respondHtmlTemplate] */ public open class PlaceholderList<TOuter, TInner> { private var items = ArrayList<PlaceholderItem<TInner>>() public val size: Int get() = items.size public operator fun invoke(meta: String = "", content: TInner.(Placeholder<TInner>) -> Unit = {}) { val placeholder = PlaceholderItem<TInner>(items.size, items) placeholder(meta, content) items.add(placeholder) } public fun isEmpty(): Boolean = items.size == 0 public fun isNotEmpty(): Boolean = isEmpty().not() public fun apply(destination: TOuter, render: TOuter.(PlaceholderItem<TInner>) -> Unit) { for (item in items) { destination.render(item) } } } /** * An item of a [PlaceholderList] when it is expanded. */ public class PlaceholderItem<TOuter>(public val index: Int, public val collection: List<PlaceholderItem<TOuter>>) : Placeholder<TOuter>() { public val first: Boolean get() = index == 0 public val last: Boolean get() = index == collection.lastIndex } /** * Inserts every element of [PlaceholderList]. */ public fun <TOuter, TInner> TOuter.each( items: PlaceholderList<TOuter, TInner>, itemTemplate: TOuter.(PlaceholderItem<TInner>) -> Unit ) { items.apply(this, itemTemplate) } /** * Inserts [Placeholder]. */ public fun <TOuter> TOuter.insert(placeholder: Placeholder<TOuter>): Unit = placeholder.apply(this) /** * A placeholder that is also a [Template]. * It can be used to insert child templates and create nested layouts. */ public open class TemplatePlaceholder<TTemplate> { private var content: TTemplate.() -> Unit = { } public operator fun invoke(content: TTemplate.() -> Unit) { this.content = content } public fun apply(template: TTemplate) { template.content() } } public fun <TTemplate : Template<TOuter>, TOuter> TOuter.insert( template: TTemplate, placeholder: TemplatePlaceholder<TTemplate> ) { placeholder.apply(template) with(template) { apply() } } public fun <TOuter, TTemplate : Template<TOuter>> TOuter.insert(template: TTemplate, build: TTemplate.() -> Unit) { template.build() with(template) { apply() } }
apache-2.0
0a4c09d198f72d2458c4a60452622205
27.463636
119
0.670073
3.855911
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/creator/SpongeForgeChooser.kt
1
2977
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.creator import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.platform.PlatformType import com.demonwav.mcdev.platform.forge.ForgeProjectConfiguration import com.demonwav.mcdev.platform.hybrid.SpongeForgeProjectConfiguration import com.demonwav.mcdev.platform.sponge.SpongeProjectConfiguration import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.util.ui.UIUtil import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel import javax.swing.JRadioButton class SpongeForgeChooser(private val creator: MinecraftProjectCreator) : ModuleWizardStep() { private lateinit var panel: JPanel private lateinit var singleRadioButton: JRadioButton private lateinit var title: JLabel override fun getComponent(): JComponent { if (UIUtil.isUnderDarcula()) { title.icon = PlatformAssets.SPONGE_FORGE_ICON_2X_DARK } else { title.icon = PlatformAssets.SPONGE_FORGE_ICON_2X } return panel } override fun updateDataModel() {} override fun isStepVisible(): Boolean { // Only show this if both Sponge and Forge are selected val values = creator.settings.values return values.count { conf -> conf is ForgeProjectConfiguration || conf is SpongeProjectConfiguration } >= 2 || values.any { conf -> conf is SpongeForgeProjectConfiguration } } override fun onStepLeaving() { if (singleRadioButton.isSelected) { // First remove the singular forge and sponge configurations creator.settings .values .removeIf { configuration -> configuration is ForgeProjectConfiguration || configuration is SpongeProjectConfiguration } // Now add the combined SpongeForgeProjectConfiguration only if it's not already there if (creator.settings.values.none { configuration -> configuration is SpongeForgeProjectConfiguration }) { creator.settings[PlatformType.FORGE] = SpongeForgeProjectConfiguration() } } else { // First remove the multi sponge forge configuration creator.settings.values.removeIf { configuration -> configuration is SpongeForgeProjectConfiguration } // Now add Forge and Sponge configurations respectively, but only if they aren't already there if (creator.settings.values.none { configuration -> configuration is ForgeProjectConfiguration }) { creator.settings[PlatformType.FORGE] = ForgeProjectConfiguration() } if (creator.settings.values.none { configuration -> configuration is SpongeProjectConfiguration }) { creator.settings[PlatformType.SPONGE] = SpongeProjectConfiguration() } } } }
mit
a6689b81d03cdf025668e13537b7cf42
39.22973
136
0.705072
5.21366
false
true
false
false
iSoron/uhabits
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/database/Repository.kt
1
9256
/* * 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.database import org.apache.commons.lang3.StringUtils import org.apache.commons.lang3.tuple.ImmutablePair import org.apache.commons.lang3.tuple.Pair import java.lang.reflect.Field import java.util.ArrayList import java.util.HashMap import java.util.LinkedList class Repository<T>( private val klass: Class<T>, private val db: Database, ) { /** * Returns the record that has the id provided. If no record is found, returns null. */ fun find(id: Long): T? { return findFirst(String.format("where %s=?", getIdName()), id.toString()) } /** * Returns all records matching the given SQL query. * * The query should only contain the "where" part of the SQL query, and optionally the "order * by" part. "Group by" is not allowed. If no matching records are found, returns an empty list. */ fun findAll(query: String, vararg params: String): List<T> { db.query(buildSelectQuery() + query, *params).use { c -> return cursorToMultipleRecords(c) } } /** * Returns the first record matching the given SQL query. See findAll for more details about * the parameters. */ fun findFirst(query: String, vararg params: String): T? { db.query(buildSelectQuery() + query, *params).use { c -> return if (!c.moveToNext()) null else cursorToSingleRecord(c) } } /** * Executes the given SQL query on the repository. * * The query can be of any kind. For example, complex deletes and updates are allowed. The * repository does not perform any checks to guarantee that the query is valid, however the * underlying database might. */ fun execSQL(query: String, vararg params: Any) { db.execute(query, *params) } /** * Executes the given callback inside a database transaction. * * If the callback terminates without throwing any exceptions, the transaction is considered * successful. If any exceptions are thrown, the transaction is aborted. Nesting transactions * is not allowed. */ fun executeAsTransaction(callback: Runnable) { db.beginTransaction() try { callback.run() db.setTransactionSuccessful() } catch (e: Exception) { throw RuntimeException(e) } finally { db.endTransaction() } } /** * Saves the record on the database. * * If the id of the given record is null, it is assumed that the record has not been inserted * in the repository yet. The record will be inserted, a new id will be automatically generated, * and the id of the given record will be updated. * * If the given record has a non-null id, then an update will be performed instead. That is, * the previous record will be overwritten by the one provided. */ fun save(record: T) { try { val fields = getFields() val columns = getColumnNames() val values: MutableMap<String, Any?> = HashMap() for (i in fields.indices) values[columns[i]] = fields[i][record] var id = getIdField()[record] as Long? var affectedRows = 0 if (id != null) { affectedRows = db.update(getTableName(), values, "${getIdName()}=?", id.toString()) } if (id == null || affectedRows == 0) { id = db.insert(getTableName(), values) getIdField()[record] = id } } catch (e: Exception) { throw RuntimeException(e) } } /** * Removes the given record from the repository. The id of the given record is also set to null. */ fun remove(record: T) { try { val id = getIdField()[record] as Long? db.delete(getTableName(), "${getIdName()}=?", id.toString()) getIdField()[record] = null } catch (e: Exception) { throw RuntimeException(e) } } private fun cursorToMultipleRecords(c: Cursor): List<T> { val records: MutableList<T> = LinkedList() while (c.moveToNext()) records.add(cursorToSingleRecord(c)) return records } @Suppress("UNCHECKED_CAST") private fun cursorToSingleRecord(cursor: Cursor): T { return try { val constructor = klass.declaredConstructors[0] constructor.isAccessible = true val record = constructor.newInstance() as T var index = 0 for (field in getFields()) copyFieldFromCursor(record, field, cursor, index++) record } catch (e: Exception) { throw RuntimeException(e) } } private fun copyFieldFromCursor(record: T, field: Field, c: Cursor, index: Int) { when { field.type.isAssignableFrom(java.lang.Integer::class.java) -> field[record] = c.getInt(index) field.type.isAssignableFrom(java.lang.Long::class.java) -> field[record] = c.getLong(index) field.type.isAssignableFrom(java.lang.Double::class.java) -> field[record] = c.getDouble(index) field.type.isAssignableFrom(java.lang.String::class.java) -> field[record] = c.getString(index) else -> throw RuntimeException("Type not supported: ${field.type.name} ${field.name}") } } private fun buildSelectQuery(): String { return String.format("select %s from %s ", StringUtils.join(getColumnNames(), ", "), getTableName()) } private val fieldColumnPairs: List<Pair<Field, Column>> get() { val fields: MutableList<Pair<Field, Column>> = ArrayList() for (f in klass.declaredFields) { f.isAccessible = true for (annotation in f.annotations) { if (annotation !is Column) continue fields.add(ImmutablePair(f, annotation)) } } return fields } private var cacheFields: Array<Field>? = null private fun getFields(): Array<Field> { if (cacheFields == null) { val fields: MutableList<Field> = ArrayList() val columns = fieldColumnPairs for (pair in columns) fields.add(pair.left) cacheFields = fields.toTypedArray() } return cacheFields!! } private var cacheColumnNames: Array<String>? = null private fun getColumnNames(): Array<String> { if (cacheColumnNames == null) { val names: MutableList<String> = ArrayList() val columns = fieldColumnPairs for (pair in columns) { var cname = pair.right.name if (cname.isEmpty()) cname = pair.left.name if (names.contains(cname)) throw RuntimeException("duplicated column : $cname") names.add(cname) } cacheColumnNames = names.toTypedArray() } return cacheColumnNames!! } private var cacheTableName: String? = null private fun getTableName(): String { if (cacheTableName == null) { val name = getTableAnnotation().name if (name.isEmpty()) throw RuntimeException("Table name is empty") cacheTableName = name } return cacheTableName!! } private var cacheIdName: String? = null private fun getIdName(): String { if (cacheIdName == null) { val id = getTableAnnotation().id if (id.isEmpty()) throw RuntimeException("Table id is empty") cacheIdName = id } return cacheIdName!! } private var cacheIdField: Field? = null private fun getIdField(): Field { if (cacheIdField == null) { val fields = getFields() val idName = getIdName() for (f in fields) if (f.name == idName) { cacheIdField = f break } if (cacheIdField == null) throw RuntimeException("Field not found: $idName") } return cacheIdField!! } private fun getTableAnnotation(): Table { var t: Table? = null for (annotation in klass.annotations) { if (annotation !is Table) continue t = annotation break } if (t == null) throw RuntimeException("Table annotation not found") return t } }
gpl-3.0
7d0534fb32071fd202cb576e91626b0d
35.152344
108
0.603458
4.512433
false
false
false
false
google/ground-android
ground/src/main/java/com/google/android/ground/model/locationofinterest/LocationOfInterest.kt
1
2690
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.model.locationofinterest import com.google.android.ground.model.AuditInfo import com.google.android.ground.model.geometry.* import com.google.android.ground.model.job.Job import com.google.android.ground.model.mutation.LocationOfInterestMutation import com.google.android.ground.model.mutation.Mutation import com.google.android.ground.model.mutation.Mutation.SyncStatus import java.util.* /** User-defined locations of interest (LOI) shown on the map. */ data class LocationOfInterest( /** A system-defined ID for this LOI. */ val id: String, /** The survey ID associated with this LOI. */ val surveyId: String, /** The job associated with this LOI. */ val job: Job, /** A user-specified ID for this location of interest. */ val customId: String? = null, /** A human readable caption for this location of interest. */ val caption: String? = null, /** User and time audit info pertaining to the creation of this LOI. */ val created: AuditInfo, /** User and time audit info pertaining to the last modification of this LOI. */ val lastModified: AuditInfo, /** Geometry associated with this LOI. */ val geometry: Geometry, ) { // TODO: Delete me once we no longer have Java callers. /** Returns the type of this LOI based on its Geometry. */ val type: LocationOfInterestType = when (geometry) { is Point -> LocationOfInterestType.POINT is Polygon -> LocationOfInterestType.POLYGON is LineString -> LocationOfInterestType.LINE_STRING is LinearRing -> LocationOfInterestType.LINEAR_RING is MultiPolygon -> LocationOfInterestType.MULTIPOLYGON } /** * Converts this LOI to a mutation that can be used to update this LOI in the remote and local * database. */ fun toMutation(type: Mutation.Type, userId: String): LocationOfInterestMutation = LocationOfInterestMutation( jobId = job.id, type = type, syncStatus = SyncStatus.PENDING, surveyId = surveyId, locationOfInterestId = id, userId = userId, clientTimestamp = Date() ) }
apache-2.0
8b87b4bff68a4e696635e99163377525
36.887324
96
0.723792
4.269841
false
false
false
false
toonine/BalaFM
app/src/main/java/com/nice/balafm/RegisterActivity.kt
1
10470
package com.nice.balafm import android.app.Activity import android.content.SharedPreferences import android.graphics.Color import android.os.Bundle import android.preference.PreferenceManager import android.support.v7.app.AppCompatActivity import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.MenuItem import android.widget.Toast import com.nice.balafm.util.* import kotlinx.android.synthetic.main.activity_register.* import okhttp3.* import org.json.JSONObject import java.io.IOException class RegisterActivity : AppCompatActivity() { private var okhttpClient = OkHttpClient.Builder() .cookieJar(object : CookieJar { private val cookieStore = HashMap<String, List<Cookie>>() override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) { cookieStore.put(url.host(), cookies) } override fun loadForRequest(url: HttpUrl): List<Cookie> { val cookies = cookieStore[url.host()] return cookies ?: ArrayList<Cookie>() } }) .build() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //为了适配状态栏的操作 window.statusBarColor = Color.parseColor("#f9f9f9") setStatusBarLightMode(true) setContentView(R.layout.activity_register) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) initView() } private fun initView() { judgeRegisterButtonEnabled() registerPhoneEditText.addTextChangedListener(object : TextWatcher { override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { judgeRegisterButtonEnabled() } override fun afterTextChanged(p0: Editable?) {} override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} }) registerPassWordEditText.addTextChangedListener(object : TextWatcher { override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { judgeRegisterButtonEnabled() } override fun afterTextChanged(p0: Editable?) {} override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} }) registerVerificationEditText.addTextChangedListener(object : TextWatcher { override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { judgeRegisterButtonEnabled() } override fun afterTextChanged(p0: Editable?) {} override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} }) getVerificationButton.setOnClickListener { //合法性验证 when { registerPhoneEditText.text.toString().isBlank() -> { Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show() return@setOnClickListener } !validatePhoneNumber(registerPhoneEditText.text.toString()) -> { Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show() return@setOnClickListener } } val ReqJson = mapToJson(mapOf("phone" to registerPhoneEditText.text.toString(), "type" to "register")) //等待请求button不可点击 getVerificationButton.isClickable = false getVerificationButton.text = "请稍后..." getVerificationButton.setBackgroundColor(Color.parseColor("#b8b8b8")) postJsonRequest(URL_SEND_VERIFICATION, ReqJson, object : Callback { override fun onResponse(call: Call, response: Response) { val RespJson = response.body()!!.string() Log.d(TAG, "cookie : ${response.header("Set-Cookie", "")}") if (isGoodJson(RespJson)) { val jsonObject = JSONObject(RespJson) if (!jsonObject.isNull("result")) { val result = jsonObject.getInt("result") Log.d(TAG, "onSendVerification: result = $result") if (result == RESULT_SUCCESS) { runOnUiThread { val timer = CountDownTimerUtils(getVerificationButton, 60000, 1000) timer.start() } } else runOnUiThread { Toast.makeText(this@RegisterActivity, ERROR_MESSAGE_SEND_VERIFICATION[result], Toast.LENGTH_SHORT).show() } } } else runOnUiThread { Toast.makeText(this@RegisterActivity, "服务器内部错误", Toast.LENGTH_SHORT).show() } } override fun onFailure(call: Call, e: IOException) { Log.d(TAG, "error: $e") runOnUiThread { getVerificationButton.isClickable = true getVerificationButton.text = "获取验证码" getVerificationButton.setBackgroundColor(Color.parseColor("#ff8922")) Toast.makeText(this@RegisterActivity, "访问服务器出错, 请稍后重试", Toast.LENGTH_SHORT).show() } } }, okhttpClient) } registerButton.setOnClickListener { //合法性验证 when { !validatePhoneNumber(registerPhoneEditText.text.toString()) -> { Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show() return@setOnClickListener } !validatePassword(registerPassWordEditText.text.toString()) -> { Toast.makeText(this, "密码必须是6-20位字母或数字", Toast.LENGTH_SHORT).show() return@setOnClickListener } !validateVerificationCode(registerVerificationEditText.text.toString()) -> { Toast.makeText(this, "验证码必须是6位数字", Toast.LENGTH_SHORT).show() return@setOnClickListener } } setRegisterButtonEnabled(false) registerButton.text = "注册中..." val ReqJson = mapToJson(mapOf("phone" to registerPhoneEditText.text.toString(), "password" to registerPassWordEditText.text.toString(), "verificationCode" to registerVerificationEditText.text.toString())) postJsonRequest(URL_REGISTER, ReqJson, object : Callback { override fun onResponse(call: Call, response: Response) { val RespJson = response.body()!!.string() if (isGoodJson(RespJson)) { val jsonObject = JSONObject(RespJson) val result = jsonObject.getInt("result") if (result == RESULT_SUCCESS) { val uid = jsonObject.getInt("uid") setResult(Activity.RESULT_OK) runOnUiThread { PreferenceManager.getDefaultSharedPreferences(this@RegisterActivity).edit() .putString(LoginActivity.SAVED_ACCOUNT, registerPhoneEditText.text.toString()) .putString(LoginActivity.SAVED_PASSWORD, registerPassWordEditText.text.toString()) .apply() globalUid = uid finish() } } else runOnUiThread { setRegisterButtonEnabled(true) registerButton.text = "注册并登录" Toast.makeText(this@RegisterActivity, ERROR_MESSAGE_REGISTER[result], Toast.LENGTH_SHORT).show() } } else runOnUiThread { setRegisterButtonEnabled(true) registerButton.text = "注册并登录" Toast.makeText(this@RegisterActivity, "服务器内部错误", Toast.LENGTH_SHORT).show() } } override fun onFailure(call: Call, e: IOException) { Log.d(TAG, "error: $e") runOnUiThread { setRegisterButtonEnabled(true) registerButton.text = "注册并登录" Toast.makeText(this@RegisterActivity, "访问服务器出错, 请稍后重试", Toast.LENGTH_SHORT).show() } } }, okhttpClient) } } private fun judgeRegisterButtonEnabled() { val empty = registerPhoneEditText.text.toString().isBlank() || registerPassWordEditText.text.toString().isBlank() || registerVerificationEditText.text.toString().isBlank() setRegisterButtonEnabled(!empty) } private fun setRegisterButtonEnabled(enabled: Boolean) { if (enabled) { registerButton.isEnabled = true registerButton.background = getDrawable(R.drawable.bg_login_button_enabled) } else { registerButton.isEnabled = false registerButton.background = getDrawable(R.drawable.bg_login_button_disabled) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> finish() } return true } companion object { private val TAG = "RegisterActivity" internal val URL_SEND_VERIFICATION = HOST_ADDRESS + "/sendVerificationCode" private val URL_REGISTER = HOST_ADDRESS + "/register" private val ERROR_MESSAGE_SEND_VERIFICATION = arrayOf("", "该手机号已经绑定过", "发送的手机号有误") private val ERROR_MESSAGE_REGISTER = arrayOf("", "验证码不正确", "手机号已经绑定过", "发送的手机号有误", "密码格式不正确", "验证码已过期") } }
apache-2.0
746bde597ad989da85a496c151f6cddd
42.32618
216
0.556766
5.142129
false
false
false
false
Mark-Kovalyov/CardRaytracerBenchmark
experimental/kotlin/CardRaytracer/src/main/kotlin/CardRaytracer.kt
1
5174
import java.io.FileOutputStream import java.io.OutputStream import java.io.PrintWriter import java.lang.Math.* /** * Special thanks to Paul Heckbert * <p/> * http://tproger.ru/translations/business-card-raytracer * <p/> * Kotlin port * <p/> * 3-MAR-2016 - (mayton) Begin... * 5-MAR-2016 - (mayton) More logic has been fixed. */ class CardRaytracer { val WIDTH = 512; val HEIGHT = 512; val SUB_SAMPLES = 64; // Position vectors: val ZERO_VECTOR = Vector(0.0, 0.0, 0.0); val Z_ORTHO_VECTOR = Vector(0.0, 0.0, 1.0); val CAMERA_ASPECT_VECTOR = Vector(17.0, 16.0, 8.0); val CAMERA_DEST_VECTOR = Vector(-6.0, -16.0, 0.0); // Color vectors: val COLOR_CELL1_VECTOR = Vector(3.0, 1.0, 1.0); val COLOR_CELL2_VECTOR = Vector(3.0, 3.0, 3.0); val COLOR_DARK_GRAY_VECTOR = Vector(13.0, 13.0, 13.0); val COLOR_SKY = Vector(0.7, 0.6, 1.0); var width = WIDTH; var height = HEIGHT; var out: OutputStream; val G = intArrayOf( 0x0003C712, // 00111100011100010010 0x00044814, // 01000100100000010100 0x00044818, // 01000100100000011000 0x0003CF94, // 00111100111110010100 0x00004892, // 00000100100010010010 0x00004891, // 00000100100010010001 0x00038710, // 00111000011100010000 0x00000010, // 00000000000000010000 0x00000010 ); val M: Int = 1048576; // 2^20 val J: Int = 2045; var oldI: Int = 12357; constructor(out: OutputStream, width: Int = 512, height: Int = 512) { this.out = out; this.width = width; this.height = height; } fun Random(): Double { oldI = (oldI * J + 1) % M; return oldI.toDouble() / M; } // TODO: Fix expressions with '+','*','%' e.t.c. overloadings fun tracer(o: Vector, d: Vector, t: DoubleBox, n: VectorBox): Int { t.value = 1e9; var m: Int = 0; var p: Double = -o.z / d.z; if (0.01 < p) { t.value = p; n.value = Z_ORTHO_VECTOR; m = 1; } for (k in 18 downTo 0) { for (j in 8 downTo 0) { if (((G[j] and 1) shl k) != 0) { var _p: Vector = o.plus(Vector(-k.toDouble(), 0.0, -j - 4.0)); var b: Double = _p.mod(d); var c: Double = _p.mod(_p) - 1.0; var q: Double = b * b - c; if (q > 0) { var s: Double = -b - Math.sqrt(q); if (s < t.value && s > 0.01) { t.value = s; n.value = (_p.plus(d.times(t.value))).norm(); m = 2; } } } } } return m; } fun sampler(o: Vector, d: Vector): Vector { var t = DoubleBox(0.0); var n = VectorBox(ZERO_VECTOR); var m = tracer(o, d, t, n); if (m == 0) { return COLOR_SKY.times(Math.pow(1.0 - d.z, 4.0)); } var h: Vector = o.plus(d.times(t.value)); var l: Vector = Vector(9.0 + Random(), 9.0 + Random(), 16.0).plus(h.times(-1.0)).norm(); var r: Vector = d.plus(n.value.times(n.value.mod(d) * -2.0)); var b: Double = l.mod(n.value); if (b < 0 || tracer(h, l, t, n) != 0) { b = 0.0; } var p: Double = Math.pow(l.mod(r) * (if (b > 0) 1.0 else 0.0), 99.0); if ((m and 1) != 0) { h = h.times(0.2); return if ((((Math.ceil(h.x).toInt() + Math.ceil(h.y).toInt()) and 1) != 0)) COLOR_CELL1_VECTOR else COLOR_CELL2_VECTOR.times(b * 0.2 + 0.1); } return Vector(p, p, p).plus(sampler(h, r).times(0.5)); } fun process() { var wr = PrintWriter(out); wr.printf("P6 %d %d 255 ", width, height); wr.flush(); var g: Vector = CAMERA_DEST_VECTOR.norm(); // Vector a = !(Vector(0, 0, 1) ^ g) * .002; var a: Vector = ((Z_ORTHO_VECTOR.vprod(g)).norm()).times(0.002); // Vector b = !(g ^ a) * .002; var b: Vector = g.vprod(a).norm().times(0.002); // Vector c = (a + b) * -256 + g; var c: Vector = (a.plus(b)).times(-256.0).plus(g); for (y in height - 1 downTo 0) { for (x in width - 1 downTo 0) { var p: Vector = COLOR_DARK_GRAY_VECTOR; for (r in 0..SUB_SAMPLES - 1) { var t: Vector = a.times(Random() - 0.5).times(99.0).plus(b.times(Random() - 0.5).times(99.0)); p = sampler(CAMERA_ASPECT_VECTOR.plus(t), t.times(-1.0).plus(a.times(Random() + x).plus(b.times(Random() + y)).plus(c).times(16.0)).norm() ).times(3.5).plus(p); } var R = p.x.toInt(); var G = p.y.toInt(); var B = p.z.toInt(); out.write(R); out.write(G); out.write(B); } } out.flush(); } }
gpl-3.0
e72e582e5dc5da5d53faf14afde70b7c
31.540881
124
0.462891
3.156803
false
false
false
false
nadraliev/DsrWeatherApp
app/src/main/java/soutvoid/com/DsrWeatherApp/ui/screen/weather/widgets/forecastList/widgets/TemperatureGraphView.kt
1
4942
package soutvoid.com.DsrWeatherApp.ui.screen.weather.widgets.forecastList.widgets import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Typeface import android.util.AttributeSet import android.view.View import soutvoid.com.DsrWeatherApp.app.log.Logger import soutvoid.com.DsrWeatherApp.ui.util.* /** * рисует точку с текстом температуры и линии до соседних точек */ class TemperatureGraphView: View { var prevTemp: Double? = null var currentTemp: Double? = null var nextTemp: Double? = null private var maxTemp: Double = .0 private var minTemp: Double = .0 private var dotPaint: Paint private var linePaint: Paint private var textPaint: Paint private val themedColor by lazy { Logger.d("shit") context.getThemeColor(android.R.attr.textColorPrimary) } var isBold: Boolean = false set(value) { field = value if (isBold) textPaint.typeface = Typeface.DEFAULT_BOLD else textPaint.typeface = Typeface.DEFAULT } init { dotPaint = initDotPaint() linePaint = initLinePaint() textPaint = initTextPaint() } constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) override fun draw(canvas: Canvas?) { super.draw(canvas) canvas?.let { drawCurrentTempDot(it, dotPaint) drawCurrentTemperature(it, textPaint) drawLineToNext(it, linePaint) drawLineToPrev(it, linePaint) } } private fun initDotPaint(): Paint { val dotPaint = Paint() dotPaint.color = themedColor dotPaint.flags = Paint.ANTI_ALIAS_FLAG return dotPaint } private fun initLinePaint() : Paint { val linePaint = Paint() linePaint.color = themedColor linePaint.flags = Paint.ANTI_ALIAS_FLAG linePaint.style = Paint.Style.FILL_AND_STROKE linePaint.strokeWidth = dpToPx(2.7).toFloat() return linePaint } private fun initTextPaint(): Paint { val textPaint = Paint() textPaint.color = themedColor textPaint.flags = Paint.ANTI_ALIAS_FLAG textPaint.textSize = spToPx(14f).toFloat() return textPaint } private fun drawCurrentTempDot(canvas: Canvas, paint: Paint) { currentTemp?.let { canvas.drawCircle(measuredWidth.toFloat() / 2, dpToPx(calculateY(it)).toFloat(), dpToPx(4.0).toFloat(), paint) } } private fun drawCurrentTemperature(canvas: Canvas, paint: Paint) { currentTemp?.let { canvas.drawText( "${Math.round(it)}${UnitsUtils.getDegreesUnits(context)}", measuredWidth.toFloat() / 2 - dpToPx(9.0).toFloat(), dpToPx(calculateY(it) - 10).toFloat(), paint ) } } private fun drawLineToNext(canvas: Canvas, paint: Paint) { ifNotNull(currentTemp, nextTemp) { current, next -> canvas.drawLine( measuredWidth.toFloat() / 2, dpToPx(calculateY(current)).toFloat(), measuredWidth.toFloat() * 3 / 2, dpToPx(calculateY(next)).toFloat(), paint ) } } private fun drawLineToPrev(canvas: Canvas, paint: Paint) { ifNotNull(currentTemp, prevTemp) { current, prev -> canvas.drawLine( measuredWidth.toFloat() / 2, dpToPx(calculateY(current)).toFloat(), -measuredWidth.toFloat() / 2, dpToPx(calculateY(prev)).toFloat(), paint ) } } /** * посчитать координату y, считая сверху * @return координата y в dp */ private fun calculateY(temperature: Double): Double { return (maxTemp - temperature) * 5 + 30 } private fun resizeSelfToTemperature() { val height = maxOf(70, calculateTempGraphHeight()) layoutParams.height = dpToPx(height.toDouble()).toInt() } /** * высота графика в зависимости от разброса температуры * @return высота в dp */ private fun calculateTempGraphHeight(): Int { return (maxTemp - minTemp).toInt() * 5 + 50 } /** * установить разброс температуры */ fun setMinMaxTemp(minTemp: Double, maxTemp: Double) { this.minTemp = minTemp this.maxTemp = maxTemp resizeSelfToTemperature() } }
apache-2.0
3f71b05bf0adec9a49cc0a175ea5fbd0
31.006711
144
0.627517
4.208297
false
false
false
false
dkandalov/katas
kotlin/src/katas/kotlin/snake/v0_refactored/SwingUI.kt
1
4494
package katas.kotlin.snake.v0_refactored import java.awt.Color import java.awt.Dimension import java.awt.Font import java.awt.Graphics import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import java.awt.event.KeyEvent.* import java.awt.event.WindowEvent import javax.swing.* fun main() { val gameUI = GameSwingUI() gameUI.init(object: GameUI.Observer { lateinit var game: Game override fun onGameStart() { game = Game.create(50, 50) gameUI.paint(game) } override fun onTimer() { if (game.state != Game.State.Playing) return game = game.updateOnTimer() gameUI.paint(game) } override fun onUserInput(direction: Direction) { if (game.state != Game.State.Playing) return game = game.updateOnUserInput(direction) gameUI.paint(game) } }) } interface GameUI { fun init(observer: Observer) fun paint(game: Game) interface Observer { fun onGameStart() fun onTimer() fun onUserInput(direction: Direction) } } class GameSwingUI: GameUI { private lateinit var gamePanel: GamePanel private lateinit var jFrame: JFrame private lateinit var timer: GameTimer override fun init(observer: GameUI.Observer) { gamePanel = GamePanel() timer = GameTimer { SwingUtilities.invokeLater { observer.onTimer() } }.init() jFrame = JFrame("Snake") jFrame.apply { defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE addKeyListener(object: KeyAdapter() { override fun keyPressed(event: KeyEvent) { val direction = when (event.keyCode) { VK_UP, VK_I -> Direction.Up VK_RIGHT, VK_L -> Direction.Right VK_DOWN, VK_K -> Direction.Down VK_LEFT, VK_J -> Direction.Left else -> null } if (direction != null) { observer.onUserInput(direction) } if (event.keyCode == VK_Q) { dispatchEvent(WindowEvent(jFrame, WindowEvent.WINDOW_CLOSING)) } if (event.keyCode == VK_S) { observer.onGameStart() } } }) add(gamePanel) pack() setLocationRelativeTo(null) isVisible = true } SwingUtilities.invokeLater { observer.onGameStart() } } override fun paint(game: Game) { gamePanel.repaintState(game) } } private class GameTimer(delay: Int = 500, callback: () -> Unit) { private val timer = Timer(delay) { callback() } fun init() = this.apply { timer.start() } } private class GamePanel: JPanel() { private var game: Game? = null private val messageFont = Font("DejaVu Sans", Font.BOLD, 35) fun repaintState(game: Game) { this.game = game repaint() } override fun paintComponent(g: Graphics) { super.paintComponent(g) game?.let { game -> val cellWidth = width / game.width val cellHeight = height / game.height val xPad = cellWidth / 10 val yPad = cellHeight / 10 g.color = Color.blue for ((x, y) in game.snake.body) { g.fillRect( x * cellWidth, y * cellHeight, cellWidth - xPad, cellHeight - yPad ) } g.color = Color.red for ((x, y) in game.apples) { g.fillRect( x * cellWidth, y * cellHeight, cellWidth - xPad, cellHeight - yPad ) } if (game.state != Game.State.Playing) { val message = "Game Over!" g.font = messageFont val textWidth = g.fontMetrics.stringWidth(message) val textHeight = g.fontMetrics.height g.drawString(message, width / 2 - textWidth / 2, height / 2 - textHeight / 2) } } } override fun getPreferredSize() = Dimension(800, 800) }
unlicense
ee7391b825fadcfe752551561ed5a4fb
27.264151
93
0.511794
4.63299
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/view/MyDrawerLayout.kt
1
2717
package jp.juggler.subwaytooter.view import android.content.Context import android.graphics.Rect import android.util.AttributeSet import androidx.core.view.ViewCompat import androidx.drawerlayout.widget.DrawerLayout class MyDrawerLayout : DrawerLayout { companion object { // private val log = LogCategory("MyDrawerLayout") } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) private var bottomExclusionWidth: Int = 0 private var bottomExclusionHeight: Int = 0 private val exclusionRects = listOf(Rect(), Rect(), Rect(), Rect()) override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { super.onLayout(changed, l, t, r, b) // 画面下部の左右にはボタンがあるので、システムジェスチャーナビゲーションの対象外にする val w = r - l val h = b - t if (w > 0 && h > 0) { // log.d("onLayout $l,$t,$r,$b bottomExclusionSize=$bottomExclusionWidth,$bottomExclusionHeight") exclusionRects[0].set( 0, h - bottomExclusionHeight * 2, 0 + bottomExclusionWidth, h ) exclusionRects[1].set( w - bottomExclusionWidth, h - bottomExclusionHeight * 2, w, h ) exclusionRects[2].set( 0, 0, bottomExclusionWidth, (bottomExclusionHeight * 1.5f).toInt() ) exclusionRects[3].set( w - bottomExclusionWidth, 0, w, (bottomExclusionHeight * 1.5).toInt() ) ViewCompat.setSystemGestureExclusionRects(this, exclusionRects) setWillNotDraw(false) } } // デバッグ用 // val paint = Paint() // override fun dispatchDraw(canvas : Canvas?) { // super.dispatchDraw(canvas) // // canvas ?: return // // log.d("dispatchDraw") // for(rect in exclusionRects) { // paint.color = 0x40ff0000 // canvas.drawRect(rect, paint) // } // } fun setExclusionSize(sizeDp: Int) { val w = (sizeDp * 1.25f + 0.5f).toInt() val h = (sizeDp * 1.5f + 0.5f).toInt() bottomExclusionWidth = w bottomExclusionHeight = h } }
apache-2.0
5cb06681bb9f949ff9da87c4a63f0cce
26.204301
109
0.535646
4.163492
false
false
false
false
paplorinc/intellij-community
platform/credential-store/src/keePass/KeePassFileManager.kt
1
9321
// 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.credentialStore.keePass import com.intellij.credentialStore.EncryptionSpec import com.intellij.credentialStore.LOG import com.intellij.credentialStore.getTrimmedChars import com.intellij.credentialStore.kdbx.IncorrectMasterPasswordException import com.intellij.credentialStore.kdbx.KdbxPassword import com.intellij.credentialStore.kdbx.KdbxPassword.Companion.createAndClear import com.intellij.credentialStore.kdbx.KeePassDatabase import com.intellij.credentialStore.kdbx.loadKdbx import com.intellij.credentialStore.toByteArrayAndClear import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.components.dialog import com.intellij.ui.layout.* import com.intellij.util.SmartList import com.intellij.util.io.delete import com.intellij.util.io.exists import java.awt.Component import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.security.SecureRandom import javax.swing.JPasswordField internal open class KeePassFileManager(private val file: Path, masterKeyFile: Path, private val masterKeyEncryptionSpec: EncryptionSpec, private val secureRandom: Lazy<SecureRandom>) { private val masterKeyFileStorage = MasterKeyFileStorage(masterKeyFile) fun clear() { if (!file.exists()) { return } try { // don't create with preloaded empty db because "clear" action should remove only IntelliJ group from database, // but don't remove other groups val masterPassword = masterKeyFileStorage.load() if (masterPassword != null) { val db = loadKdbx(file, KdbxPassword.createAndClear(masterPassword)) val store = KeePassCredentialStore(file, masterKeyFileStorage, db) store.clear() store.save(masterKeyEncryptionSpec) return } } catch (e: Exception) { // ok, just remove file if (e !is IncorrectMasterPasswordException && ApplicationManager.getApplication()?.isUnitTestMode == false) { LOG.error(e) } } file.delete() } fun import(fromFile: Path, event: AnActionEvent?) { if (file == fromFile) { return } try { doImportOrUseExisting(fromFile, event) } catch (e: IncorrectMasterPasswordException) { throw e } catch (e: Exception) { LOG.warn(e) Messages.showMessageDialog(event?.getData(PlatformDataKeys.CONTEXT_COMPONENT)!!, "Internal error", "Cannot Import", Messages.getErrorIcon()) } } // throws IncorrectMasterPasswordException if user cancelled ask master password dialog @Throws(IncorrectMasterPasswordException::class) fun useExisting() { if (file.exists()) { if (!doImportOrUseExisting(file, event = null)) { throw IncorrectMasterPasswordException() } } else { saveDatabase(file, KeePassDatabase(), generateRandomMasterKey(masterKeyEncryptionSpec, secureRandom.value), masterKeyFileStorage, secureRandom.value) } } private fun doImportOrUseExisting(file: Path, event: AnActionEvent?): Boolean { val contextComponent = event?.getData(PlatformDataKeys.CONTEXT_COMPONENT) // check master key file in parent dir of imported file val possibleMasterKeyFile = file.parent.resolve(MASTER_KEY_FILE_NAME) var masterPassword = MasterKeyFileStorage(possibleMasterKeyFile).load() if (masterPassword != null) { try { loadKdbx(file, KdbxPassword(masterPassword)) } catch (e: IncorrectMasterPasswordException) { LOG.warn("On import \"$file\" found existing master key file \"$possibleMasterKeyFile\" but key is not correct") masterPassword = null } } if (masterPassword == null && !requestMasterPassword("Specify Master Password", contextComponent = contextComponent) { try { loadKdbx(file, KdbxPassword(it)) masterPassword = it null } catch (e: IncorrectMasterPasswordException) { "Master password not correct." } }) { return false } if (file !== this.file) { Files.copy(file, this.file, StandardCopyOption.REPLACE_EXISTING) } masterKeyFileStorage.save(createMasterKey(masterPassword!!)) return true } fun askAndSetMasterKey(event: AnActionEvent?, topNote: String? = null): Boolean { val contextComponent = event?.getData(PlatformDataKeys.CONTEXT_COMPONENT) // to open old database, key can be required, so, to avoid showing 2 dialogs, check it before val db = try { if (file.exists()) loadKdbx(file, KdbxPassword(this.masterKeyFileStorage.load() ?: throw IncorrectMasterPasswordException(isFileMissed = true))) else KeePassDatabase() } catch (e: IncorrectMasterPasswordException) { // ok, old key is required return requestCurrentAndNewKeys(contextComponent) } return requestMasterPassword("Set Master Password", topNote = topNote, contextComponent = contextComponent) { saveDatabase(file, db, createMasterKey(it), masterKeyFileStorage, secureRandom.value) null } } protected open fun requestCurrentAndNewKeys(contextComponent: Component?): Boolean { val currentPasswordField = JPasswordField() val newPasswordField = JPasswordField() val panel = panel { row("Current password:") { currentPasswordField().focused() } row("New password:") { newPasswordField() } commentRow("If the current password is unknown, clear the KeePass database.") } return dialog(title = "Change Master Password", panel = panel, parent = contextComponent) { val errors = SmartList<ValidationInfo>() val current = checkIsEmpty(currentPasswordField, errors) val new = checkIsEmpty(newPasswordField, errors) if (errors.isEmpty()) { try { if (doSetNewMasterPassword(current!!, new!!)) { return@dialog errors } } catch (e: IncorrectMasterPasswordException) { errors.add(ValidationInfo("The current password is incorrect.", currentPasswordField)) new?.fill(0.toChar()) } } else { current?.fill(0.toChar()) new?.fill(0.toChar()) } errors }.showAndGet() } @Suppress("MemberVisibilityCanBePrivate") protected fun doSetNewMasterPassword(current: CharArray, new: CharArray): Boolean { val db = loadKdbx(file, createAndClear(current.toByteArrayAndClear())) saveDatabase(file, db, createMasterKey(new), masterKeyFileStorage, secureRandom.value) return false } private fun createMasterKey(value: CharArray) = createMasterKey(value.toByteArrayAndClear()) private fun createMasterKey(value: ByteArray, isAutoGenerated: Boolean = false) = MasterKey(value, isAutoGenerated, masterKeyEncryptionSpec) private fun checkIsEmpty(field: JPasswordField, errors: MutableList<ValidationInfo>): CharArray? { val chars = field.getTrimmedChars() if (chars == null) { errors.add(ValidationInfo("Current master password is empty.", field)) } return chars } protected open fun requestMasterPassword(title: String, topNote: String? = null, contextComponent: Component? = null, ok: (value: ByteArray) -> String?): Boolean { val passwordField = JPasswordField() val panel = panel { topNote?.let { noteRow(it) } row("Master password:") { passwordField().focused() } } return dialog(title = title, panel = panel, parent = contextComponent) { val errors = SmartList<ValidationInfo>() val value = checkIsEmpty(passwordField, errors) if (errors.isEmpty()) { val result = value!!.toByteArrayAndClear() ok(result)?.let { errors.add(ValidationInfo(it, passwordField)) } if (!errors.isEmpty()) { result.fill(0) } } errors } .showAndGet() } fun saveMasterKeyToApplyNewEncryptionSpec() { // if null, master key file doesn't exist now, it will be saved later somehow, no need to re-save with a new encryption spec val existing = masterKeyFileStorage.load() ?: return // no need to re-save db file because master password is not changed, only master key encryption spec changed masterKeyFileStorage.save(createMasterKey(existing, isAutoGenerated = masterKeyFileStorage.isAutoGenerated())) } fun setCustomMasterPasswordIfNeed(defaultDbFile: Path) { // https://youtrack.jetbrains.com/issue/IDEA-174581#focus=streamItem-27-3081868-0-0 // for custom location require to set custom master password to make sure that user will be able to reuse file on another machine if (file == defaultDbFile) { return } if (!masterKeyFileStorage.isAutoGenerated()) { return } askAndSetMasterKey(null, topNote = "Database in a custom location, therefore\ncustom master password is required.") } }
apache-2.0
350cfa30d72119ce106eec8ce9bd95ff
36.740891
173
0.699818
4.892913
false
false
false
false
chrislo27/Tickompiler
src/main/kotlin/rhmodding/tickompiler/compiler/Compiler.kt
2
9590
package rhmodding.tickompiler.compiler import org.parboiled.Parboiled import org.parboiled.parserunners.RecoveringParseRunner import rhmodding.tickompiler.* import rhmodding.tickompiler.Function import java.io.File import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.charset.Charset class Compiler(val tickflow: String, val functions: Functions) { private var hasStartedTiming = false private var startNanoTime: Long = 0 set(value) { if (!hasStartedTiming) { field = value hasStartedTiming = true } } enum class VariableType { VARIABLE, MARKER, STRING } fun unicodeStringToInts(str: String, ordering: ByteOrder): List<Long> { val result = mutableListOf<Long>() var i = 0 while (i <= str.length) { var int = 0 if (i < str.length) int += str[i].toByte().toInt() shl (if (ordering == ByteOrder.BIG_ENDIAN) 16 else 0) if (i + 1 < str.length) int += str[i + 1].toByte().toInt() shl (if (ordering == ByteOrder.BIG_ENDIAN) 0 else 16) i += 2 result.add(int.toLong()) } return result } fun stringToInts(str: String, ordering: ByteOrder): List<Long> { val result = mutableListOf<Long>() var i = 0 while (i <= str.length) { var int = 0 if (i < str.length) int += str[i].toByte().toInt() shl (if (ordering == ByteOrder.BIG_ENDIAN) 24 else 0) if (i + 1 < str.length) int += str[i + 1].toByte().toInt() shl (if (ordering == ByteOrder.BIG_ENDIAN) 16 else 8) if (i + 2 < str.length) int += str[i + 2].toByte().toInt() shl (if (ordering == ByteOrder.BIG_ENDIAN) 8 else 16) if (i + 3 < str.length) int += str[i + 3].toByte().toInt() shl (if (ordering == ByteOrder.BIG_ENDIAN) 0 else 24) i += 4 result.add(int.toLong()) } return result } fun compileStatement(statement: Any, longs: MutableList<Long>, variables: MutableMap<String, Pair<Long, VariableType>>) { when (statement) { is FunctionCallNode -> { val argAnnotations = mutableListOf<Pair<Int, Int>>() val funcCall = FunctionCall(statement.func, statement.special?.getValue(variables) ?: 0, statement.args.mapIndexed { index, it -> if (it.type == ExpType.VARIABLE && variables[it.id as String]?.second == VariableType.MARKER) { argAnnotations.add(Pair(index, 0)) } if (it.type == ExpType.USTRING) { argAnnotations.add(Pair(index, 1)) } if (it.type == ExpType.STRING) { argAnnotations.add(Pair(index, 2)) } it.getValue(variables) }) if (statement.func == "bytes") { argAnnotations.add(Pair(statement.args.size, 3)) } if (argAnnotations.size > 0) { longs.add(0xFFFFFFFF) longs.add(argAnnotations.size.toLong()) argAnnotations.forEach { longs.add((it.second + (it.first shl 8)).toLong()) } } val function: Function = functions[funcCall.func] if (function::class.java.isAnnotationPresent(DeprecatedFunction::class.java)) { println("DEPRECATION WARNING at ${statement.position.line}:${statement.position.column} -> " + function::class.java.annotations.filterIsInstance<DeprecatedFunction>().first().value) } function.checkArgsNeeded(funcCall) function.produceBytecode(funcCall).forEach { longs.add(it) } } is VarAssignNode -> { variables[statement.variable] = statement.expr.getValue(variables) to VariableType.VARIABLE } /*is LoopNode -> { (1..statement.expr.getValue(variables)).forEach { statement.statements.forEach { compileStatement(it, longs, variables) } } }*/ } } constructor(file: File) : this(preProcess(file), MegamixFunctions) constructor(file: File, functions: Functions) : this( preProcess(file), functions) fun compile(endianness: ByteOrder): CompileResult { startNanoTime = System.nanoTime() // Split tickflow into lines, stripping comments val commentLess = tickflow.lines().joinToString("\n") { it.replaceAfter("//", "").replace("//", "").trim() } val parser = Parboiled.createParser(TickflowParser::class.java) val result = RecoveringParseRunner<Any>(parser.TickflowCode()).run(commentLess) // println(ParseTreeUtils.printNodeTree(result)) val longs: MutableList<Long> = mutableListOf() val variables: MutableMap<String, Pair<Long, VariableType>> = mutableMapOf() // result.valueStack.reversed().forEach(::println) var counter = 0L val startMetadata = MutableList<Long>(3) { 0 } var hasMetadata = false val ustrings = mutableListOf<String>() val strings = mutableListOf<String>() result.valueStack.reversed().forEach { when (it) { is AliasAssignNode -> functions[it.expr.getValue(variables)] = it.alias is FunctionCallNode -> { val funcCall = FunctionCall(it.func, 0, it.args.map { if (it.type == ExpType.STRING) { strings.add(it.string as String) } if (it.type == ExpType.USTRING) { ustrings.add(it.string as String) } 0L }) val function: Function = functions[funcCall.func] val len = function.produceBytecode(funcCall).size counter += len * 4 } is MarkerNode -> { variables[it.name] = counter to VariableType.MARKER if (it.name == "start") { startMetadata[1] = counter } if (it.name == "assets") { startMetadata[2] = counter } } is DirectiveNode -> { hasMetadata = true when (it.name) { "index" -> startMetadata[0] = it.num "start" -> startMetadata[1] = it.num "assets" -> startMetadata[2] = it.num } } } } ustrings.forEach { variables[it] = counter to VariableType.STRING counter += unicodeStringToInts(it, endianness).size * 4 } strings.forEach { variables[it] = counter to VariableType.STRING counter += stringToInts(it, endianness).size * 4 } result.valueStack.reversed().forEach { compileStatement(it, longs, variables) } longs.add(0xFFFFFFFE) ustrings.forEach { longs.addAll(unicodeStringToInts(it, endianness)) } strings.forEach { longs.addAll(stringToInts(it, endianness)) } val buffer = ByteBuffer.allocate(longs.size * 4 + (if (hasMetadata) 12 else 0)) buffer.order(endianness) if (hasMetadata) { startMetadata.forEach { buffer.putInt(it.toInt()) } } longs.forEach { buffer.putInt(it.toInt()) } return CompileResult(result.matched, (System.nanoTime() - startNanoTime) / 1_000_000.0, buffer) } } private fun preProcess(file: File): String { val tickflow = file.readText(Charset.forName("UTF-8")) val newTickflow = tickflow.lines().joinToString("\n") { if (it.startsWith("#include")) { val filename = it.split(" ")[1] val otherfile = File(file.parentFile, filename) if (otherfile.exists() && otherfile.isFile) { otherfile.readText(Charset.forName("UTF-8")) } else { throw CompilerError("Included file $filename not found.") } } else it } return newTickflow } data class CompileResult(val success: Boolean, val timeMs: Double, val data: ByteBuffer) data class FunctionCall(val func: String, val specialArg: Long, val args: List<Long>)
mit
0a34575480723d22a0c80f28f9979186
40.695652
143
0.490407
4.890362
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Message.kt
1
5985
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.common.startsWith import org.objectweb.asm.Opcodes.* import org.objectweb.asm.Type.* import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.UniqueMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 @DependsOn(DualNode::class) class Message : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<DualNode>() } .and { it.instanceFields.size >= 6 } .and { it.instanceFields.count { it.type == INT_TYPE } == 3 } .and { it.instanceFields.count { it.type == String::class.type } == 3 } @DependsOn(set::class) class sender : OrderMapper.InMethod.Field(set::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == String::class.type } } @DependsOn(set::class) class prefix : OrderMapper.InMethod.Field(set::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == String::class.type } } @DependsOn(set::class) class text : OrderMapper.InMethod.Field(set::class, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == String::class.type } } @DependsOn(set::class) class type : OrderMapper.InMethod.Field(set::class, 2, 3) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(set::class) class cycle : OrderMapper.InMethod.Field(set::class, 1, 3) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(set::class) class count : OrderMapper.InMethod.Field(set::class, 0, 3) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(TriBool::class) class isFromFriend0 : OrderMapper.InConstructor.Field(Message::class, 0, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == type<TriBool>() } } @DependsOn(TriBool::class) class isFromIgnored0 : OrderMapper.InConstructor.Field(Message::class, 1, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == type<TriBool>() } } @MethodParameters("type", "sender", "prefix", "text") class set : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.startsWith(INT_TYPE, String::class.type, String::class.type, String::class.type) } } @DependsOn(Username::class) class senderUsername : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<Username>() } } @MethodParameters() @DependsOn(isFromFriend0::class) class isFromFriend : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE && it.arguments.isEmpty() } .and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<isFromFriend0>().id } } } @MethodParameters() @DependsOn(isFromIgnored0::class) class isFromIgnored : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE && it.arguments.isEmpty() } .and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<isFromIgnored0>().id } } } @MethodParameters() @DependsOn(isFromFriend::class) class fillIsFromFriend : UniqueMapper.InMethod.Method(isFromFriend::class) { override val predicate = predicateOf<Instruction2> { it.isMethod } } @MethodParameters() @DependsOn(isFromIgnored::class) class fillIsFromIgnored : UniqueMapper.InMethod.Method(isFromIgnored::class) { override val predicate = predicateOf<Instruction2> { it.isMethod } } @MethodParameters() @DependsOn(senderUsername::class) class fillSenderUsername : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE && it.arguments.isEmpty() } .and { it.instructions.any { it.opcode == PUTFIELD && it.fieldId == field<senderUsername>().id } } } @MethodParameters() @DependsOn(isFromFriend0::class, Client.TriBool_unknown::class) class clearIsFromFriend : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE && it.arguments.isEmpty() } .and { it.instructions.any { it.opcode == PUTFIELD && it.fieldId == field<isFromFriend0>().id } } .and { it.instructions.any { it.opcode == GETSTATIC && it.fieldId == field<Client.TriBool_unknown>().id } } } @MethodParameters() @DependsOn(isFromIgnored0::class, Client.TriBool_unknown::class) class clearIsFromIgnored : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE && it.arguments.isEmpty() } .and { it.instructions.any { it.opcode == PUTFIELD && it.fieldId == field<isFromIgnored0>().id } } .and { it.instructions.any { it.opcode == GETSTATIC && it.fieldId == field<Client.TriBool_unknown>().id } } } }
mit
7fda194070c9a89c02c6dbba1417b47b
46.888
123
0.685046
4.124742
false
false
false
false
google/intellij-community
plugins/kotlin/base/highlighting/src/org/jetbrains/kotlin/idea/base/highlighting/KotlinHighlightingUtils.kt
5
3431
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("KotlinHighlightingUtils") package org.jetbrains.kotlin.idea.base.highlighting import com.intellij.codeInsight.daemon.OutsidersPsiFileSupport import com.intellij.openapi.project.DumbService import com.intellij.psi.PsiManager import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.idea.base.util.KotlinPlatformUtils import org.jetbrains.kotlin.idea.base.util.getOutsiderFileOrigin import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.NotUnderContentRootModuleInfo import org.jetbrains.kotlin.idea.core.script.IdeScriptReportSink import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtCodeFragment import org.jetbrains.kotlin.psi.KtFile import kotlin.script.experimental.api.ScriptDiagnostic @ApiStatus.Internal fun KtFile.shouldHighlightErrors(): Boolean { if (isCompiled) { return false } if (this is KtCodeFragment && context != null) { return true } val canCheckScript = shouldCheckScript() if (canCheckScript == true) { return this.shouldHighlightScript() } return RootKindFilter.projectSources.copy(includeScriptsOutsideSourceRoots = canCheckScript == null).matches(this) } @ApiStatus.Internal fun KtFile.shouldHighlightFile(): Boolean { if (this is KtCodeFragment && context != null) { return true } if (isCompiled) return false if (OutsidersPsiFileSupport.isOutsiderFile(virtualFile)) { val origin = getOutsiderFileOrigin(project, virtualFile) ?: return false val psiFileOrigin = PsiManager.getInstance(project).findFile(origin) as? KtFile ?: return false return psiFileOrigin.shouldHighlightFile() } val shouldCheckScript = shouldCheckScript() if (shouldCheckScript == true) { return this.shouldHighlightScript() } return if (shouldCheckScript != null) { RootKindFilter.everything.matches(this) && moduleInfo !is NotUnderContentRootModuleInfo } else { RootKindFilter.everything.copy(includeScriptsOutsideSourceRoots = true).matches(this) } } private fun KtFile.shouldCheckScript(): Boolean? = runReadAction { when { // to avoid SNRE from stub (KTIJ-7633) DumbService.getInstance(project).isDumb -> null isScript() -> true else -> false } } private fun KtFile.shouldHighlightScript(): Boolean { if (KotlinPlatformUtils.isCidr) { // There is no Java support in CIDR. So do not highlight errors in KTS if running in CIDR. return false } if (!ScriptConfigurationManager.getInstance(project).hasConfiguration(this)) return false if (IdeScriptReportSink.getReports(this).any { it.severity == ScriptDiagnostic.Severity.FATAL }) { return false } if (!ScriptDefinitionsManager.getInstance(project).isReady()) return false return RootKindFilter.projectSources.copy(includeScriptsOutsideSourceRoots = true).matches(this) }
apache-2.0
52147f376fd0de7022825855e85d9118
36.304348
120
0.758379
4.556441
false
false
false
false
google/intellij-community
plugins/git4idea/src/git4idea/search/GitSearchEverywhereContributor.kt
3
8678
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.search import com.intellij.icons.AllIcons import com.intellij.ide.actions.searcheverywhere.* import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.codeStyle.NameUtil import com.intellij.ui.render.IconCompCompPanel import com.intellij.util.Processor import com.intellij.util.text.Matcher import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.vcs.log.Hash import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.VcsRef import com.intellij.vcs.log.data.DataPack import com.intellij.vcs.log.data.VcsLogData import com.intellij.vcs.log.impl.VcsLogContentUtil import com.intellij.vcs.log.impl.VcsProjectLog import com.intellij.vcs.log.ui.render.LabelIcon import com.intellij.vcs.log.util.VcsLogUtil import com.intellij.vcs.log.util.containsAll import com.intellij.vcs.log.visible.filters.VcsLogFilterObject import git4idea.GitVcs import git4idea.branch.GitBranchUtil import git4idea.i18n.GitBundle import git4idea.log.GitRefManager import git4idea.repo.GitRepositoryManager import git4idea.search.GitSearchEverywhereItemType.* import java.awt.Component import java.util.function.Function import javax.swing.JLabel import javax.swing.JList import javax.swing.ListCellRenderer internal class GitSearchEverywhereContributor(private val project: Project) : WeightedSearchEverywhereContributor<Any>, DumbAware { private val filter = PersistentSearchEverywhereContributorFilter( GitSearchEverywhereItemType.values().asList(), project.service<GitSearchEverywhereFilterConfiguration>(), Function { it.displayName }, Function { null } ) override fun fetchWeightedElements( pattern: String, progressIndicator: ProgressIndicator, consumer: Processor<in FoundItemDescriptor<Any>> ) { if (!ProjectLevelVcsManager.getInstance(project).checkVcsIsActive(GitVcs.NAME)) return val logManager = VcsProjectLog.getInstance(project).logManager ?: return val dataManager = logManager.dataManager val storage = dataManager.storage val index = dataManager.index val dataPack = awaitFullLogDataPack(dataManager, progressIndicator) ?: return if (filter.isSelected(COMMIT_BY_HASH) && pattern.length >= 7 && VcsLogUtil.HASH_REGEX.matcher(pattern).matches()) { storage.findCommitId { progressIndicator.checkCanceled() it.hash.asString().startsWith(pattern, true) && dataPack.containsAll(listOf(it), storage) }?.let { commitId -> val id = storage.getCommitIndex(commitId.hash, commitId.root) dataManager.miniDetailsGetter.loadCommitsDataSynchronously(listOf(id), progressIndicator) { consumer.process(FoundItemDescriptor(it, COMMIT_BY_HASH.weight)) } } } val matcher = NameUtil.buildMatcher("*$pattern") .withCaseSensitivity(NameUtil.MatchingCaseSensitivity.NONE) .typoTolerant() .build() dataPack.refsModel.stream().forEach { progressIndicator.checkCanceled() when (it.type) { GitRefManager.LOCAL_BRANCH, GitRefManager.HEAD -> processRefOfType(it, LOCAL_BRANCH, matcher, consumer) GitRefManager.REMOTE_BRANCH -> processRefOfType(it, REMOTE_BRANCH, matcher, consumer) GitRefManager.TAG -> processRefOfType(it, TAG, matcher, consumer) } } if (filter.isSelected(COMMIT_BY_MESSAGE) && Registry.`is`("git.search.everywhere.commit.by.message")) { if (pattern.length < 3) return val allRootsIndexed = GitRepositoryManager.getInstance(project).repositories.all { index.isIndexed(it.root) } if (!allRootsIndexed) return index.dataGetter?.filterMessages(VcsLogFilterObject.fromPattern(pattern)) { commitIdx -> progressIndicator.checkCanceled() dataManager.miniDetailsGetter.loadCommitsDataSynchronously(listOf(commitIdx), progressIndicator) { consumer.process(FoundItemDescriptor(it, COMMIT_BY_MESSAGE.weight)) } } } } private fun processRefOfType(ref: VcsRef, type: GitSearchEverywhereItemType, matcher: Matcher, consumer: Processor<in FoundItemDescriptor<Any>>) { if (!filter.isSelected(type)) return if (matcher.matches(ref.name)) consumer.process(FoundItemDescriptor(ref, type.weight)) } private fun awaitFullLogDataPack(dataManager: VcsLogData, indicator: ProgressIndicator): DataPack? { if (!Registry.`is`("vcs.log.keep.up.to.date")) return null var dataPack: DataPack do { indicator.checkCanceled() dataPack = dataManager.dataPack } while (!dataPack.isFull && Thread.sleep(1000) == Unit) return dataPack } private val renderer = object : ListCellRenderer<Any> { private val panel = IconCompCompPanel(JLabel(), JLabel()).apply { border = JBUI.Borders.empty(0, 8) } override fun getListCellRendererComponent( list: JList<out Any>, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean ): Component { panel.reset() panel.background = UIUtil.getListBackground(isSelected, cellHasFocus) panel.setIcon(when (value) { is VcsRef -> LabelIcon(panel.center, JBUI.scale(16), panel.background, listOf(value.type.backgroundColor)) else -> AllIcons.Vcs.CommitNode }) panel.center.apply { font = list.font text = when (value) { is VcsRef -> value.name is VcsCommitMetadata -> value.subject else -> null } foreground = UIUtil.getListForeground(isSelected, cellHasFocus) } panel.right.apply { font = list.font text = when (value) { is VcsRef -> getTrackingRemoteBranchName(value) is VcsCommitMetadata -> value.id.toShortString() else -> null } foreground = if (!isSelected) UIUtil.getInactiveTextColor() else UIUtil.getListForeground(isSelected, cellHasFocus) } return panel } @NlsSafe private fun getTrackingRemoteBranchName(vcsRef: VcsRef): String? { if (vcsRef.type != GitRefManager.LOCAL_BRANCH) { return null } val repository = GitRepositoryManager.getInstance(project).getRepositoryForRootQuick(vcsRef.root) ?: return null return GitBranchUtil.getTrackInfo(repository, vcsRef.name)?.remoteBranch?.name } } override fun getElementsRenderer(): ListCellRenderer<in Any> = renderer override fun processSelectedItem(selected: Any, modifiers: Int, searchText: String): Boolean { val hash: Hash? val root: VirtualFile? when (selected) { is VcsRef -> { hash = selected.commitHash root = selected.root } is VcsCommitMetadata -> { hash = selected.id root = selected.root } else -> { hash = null root = null } } if (hash != null && root != null) { VcsLogContentUtil.runInMainLog(project) { it.vcsLog.jumpToCommit(hash, root) } return true } return false } override fun getActions(onChanged: Runnable) = listOf(SearchEverywhereFiltersAction(filter, onChanged)) override fun getSearchProviderId() = "Vcs.Git" override fun getGroupName() = GitBundle.message("search.everywhere.group.name") override fun getFullGroupName() = GitBundle.message("search.everywhere.group.full.name") // higher weight -> lower position override fun getSortWeight() = 500 override fun showInFindResults() = false override fun isShownInSeparateTab(): Boolean { return ProjectLevelVcsManager.getInstance(project).checkVcsIsActive(GitVcs.NAME) && VcsProjectLog.getInstance(project).logManager != null } override fun getDataForItem(element: Any, dataId: String): Any? = null companion object { class Factory : SearchEverywhereContributorFactory<Any> { override fun createContributor(initEvent: AnActionEvent): GitSearchEverywhereContributor { val project = initEvent.getRequiredData(CommonDataKeys.PROJECT) return GitSearchEverywhereContributor(project) } } } }
apache-2.0
26f9aa346273349bcc85376f2ab7143e
37.061404
131
0.720673
4.543455
false
false
false
false
algra/pact-jvm
pact-jvm-model/src/main/kotlin/au/com/dius/pact/model/PactSource.kt
1
1911
package au.com.dius.pact.model import java.io.File import java.util.function.Supplier /** * Represents the source of a Pact */ sealed class PactSource { open fun description() = toString() } /** * A source of a pact that comes from some URL */ sealed class UrlPactSource : PactSource() { abstract val url: String } data class DirectorySource<I> @JvmOverloads constructor( val dir: File, val pacts: MutableMap<File, Pact<I>> = mutableMapOf() ) : PactSource() where I: Interaction data class PactBrokerSource<I> @JvmOverloads constructor( val host: String, val port: String, val scheme: String = "http", val pacts: MutableMap<Consumer, List<Pact<I>>> = mutableMapOf() ) : PactSource() where I: Interaction data class FileSource<I> @JvmOverloads constructor(val file: File, val pact: Pact<I>? = null) : PactSource() where I: Interaction { override fun description() = "File $file" } data class UrlSource<I> @JvmOverloads constructor(override val url: String, val pact: Pact<I>? = null) : UrlPactSource() where I: Interaction { override fun description() = "URL $url" } data class UrlsSource<I> @JvmOverloads constructor( val url: List<String>, val pacts: MutableMap<String, Pact<I>> = mutableMapOf() ) : PactSource() where I: Interaction data class BrokerUrlSource @JvmOverloads constructor( override val url: String, val pactBrokerUrl: String, val attributes: Map<String, Map<String, Any>> = mapOf(), val options: Map<String, Any> = mapOf() ) : UrlPactSource() { override fun description() = "Pact Broker $url" } object InputStreamPactSource : PactSource() object ReaderPactSource : PactSource() object UnknownPactSource : PactSource() @Suppress("ClassNaming") data class S3PactSource(override val url: String) : UrlPactSource() { override fun description() = "S3 Bucket $url" } data class ClosurePactSource(val closure: Supplier<Any>) : PactSource()
apache-2.0
0e5b8c9813a10069f7b79b220161910d
26.695652
102
0.723182
3.75442
false
false
false
false
google/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/AbstractRenderingKDocTest.kt
2
1364
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.codeInsight import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.idea.KotlinDocumentationProvider import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils abstract class AbstractRenderingKDocTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE protected fun doTest(path: String) { myFixture.configureByFile(fileName()) val file = myFixture.file val kDocProvider = KotlinDocumentationProvider() val comments = mutableListOf<String>() kDocProvider.collectDocComments(file) { val rendered = kDocProvider.generateRenderedDoc(it) if (rendered != null) { comments.add(rendered.replace("\n", "")) } } val expectedRenders = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, "// RENDER: ") UsefulTestCase.assertOrderedEquals(comments, expectedRenders) } }
apache-2.0
d7d103a5eeaa1342736ef1fb29ac40d8
41.625
158
0.753666
5.412698
false
true
false
false
youdonghai/intellij-community
platform/platform-impl/src/com/intellij/openapi/actionSystem/ex/QuickListsManager.kt
1
4572
/* * 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.openapi.actionSystem.ex import com.intellij.configurationStore.LazySchemeProcessor import com.intellij.configurationStore.SchemeDataHolder import com.intellij.ide.IdeBundle import com.intellij.ide.actions.QuickSwitchSchemeAction import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.impl.BundledQuickListsProvider import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ApplicationComponent import com.intellij.openapi.options.SchemeManager import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.project.Project import gnu.trove.THashSet import java.util.function.Function class QuickListsManager(private val myActionManager: ActionManager, schemeManagerFactory: SchemeManagerFactory) : ApplicationComponent { private val mySchemeManager: SchemeManager<QuickList> init { mySchemeManager = schemeManagerFactory.create("quicklists", object : LazySchemeProcessor<QuickList, QuickList>(QuickList.DISPLAY_NAME_TAG) { override fun createScheme(dataHolder: SchemeDataHolder<QuickList>, name: String, attributeProvider: Function<String, String?>, isBundled: Boolean): QuickList { val item = QuickList() item.readExternal(dataHolder.read()) dataHolder.updateDigest(item) return item } }, presentableName = IdeBundle.message("quick.lists.presentable.name")) } companion object { @JvmStatic val instance: QuickListsManager get() = ApplicationManager.getApplication().getComponent(QuickListsManager::class.java) } override fun getComponentName() = "QuickListsManager" override fun initComponent() { for (provider in BundledQuickListsProvider.EP_NAME.extensions) { for (path in provider.bundledListsRelativePaths) { mySchemeManager.loadBundledScheme(path, provider) } } mySchemeManager.loadSchemes() registerActions() } override fun disposeComponent() { } val schemeManager: SchemeManager<QuickList> get() = mySchemeManager val allQuickLists: Array<QuickList> get() { return mySchemeManager.allSchemes.toTypedArray() } private fun registerActions() { // to prevent exception if 2 or more targets have the same name val registeredIds = THashSet<String>() for (scheme in mySchemeManager.allSchemes) { val actionId = scheme.actionId if (registeredIds.add(actionId)) { myActionManager.registerAction(actionId, InvokeQuickListAction(scheme)) } } } private fun unregisterActions() { for (oldId in myActionManager.getActionIds(QuickList.QUICK_LIST_PREFIX)) { myActionManager.unregisterAction(oldId) } } // used by external plugin fun setQuickLists(quickLists: List<QuickList>) { unregisterActions() mySchemeManager.setSchemes(quickLists) registerActions() } } private class InvokeQuickListAction(private val myQuickList: QuickList) : QuickSwitchSchemeAction() { init { myActionPlace = ActionPlaces.ACTION_PLACE_QUICK_LIST_POPUP_ACTION templatePresentation.description = myQuickList.description templatePresentation.setText(myQuickList.name, false) } override fun fillActions(project: Project, group: DefaultActionGroup, dataContext: DataContext) { val actionManager = ActionManager.getInstance() for (actionId in myQuickList.actionIds) { if (QuickList.SEPARATOR_ID == actionId) { group.addSeparator() } else { val action = actionManager.getAction(actionId) if (action != null) { group.add(action) } } } } }
apache-2.0
c982e1fbd71017e4c2cd5ba9db6cf1d0
34.71875
136
0.729003
5.013158
false
false
false
false
vhromada/Catalog
core/src/main/kotlin/com/github/vhromada/catalog/domain/filter/GameFilter.kt
1
568
package com.github.vhromada.catalog.domain.filter import com.github.vhromada.catalog.common.filter.FieldOperation import com.github.vhromada.catalog.domain.QGame /** * A class represents filter for games. * * @author Vladimir Hromada */ data class GameFilter( /** * Name */ val name: String? = null ) : JpaFilter() { override fun isEmpty(): Boolean { return name.isNullOrBlank() } override fun process() { val game = QGame.game add(field = name, path = game.name, operation = FieldOperation.LIKE) } }
mit
877ccbe695d1c4cf0dbac66fc8d5de9c
20.037037
76
0.65669
3.837838
false
false
false
false
allotria/intellij-community
platform/projectModel-impl/src/com/intellij/openapi/components/service.kt
2
1345
// 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.openapi.components import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.project.Project import com.intellij.project.ProjectStoreOwner inline fun <reified T : Any> service(): T { val serviceClass = T::class.java return ApplicationManager.getApplication().getService(serviceClass) ?: throw RuntimeException("Cannot find service ${serviceClass.name} (classloader=${serviceClass.classLoader})") } inline fun <reified T : Any> serviceOrNull(): T? = ApplicationManager.getApplication().getService(T::class.java) inline fun <reified T : Any> serviceIfCreated(): T? = ApplicationManager.getApplication().getServiceIfCreated(T::class.java) inline fun <reified T : Any> Project.service(): T = getService(T::class.java) inline fun <reified T : Any> Project.serviceIfCreated(): T? = getServiceIfCreated(T::class.java) val ComponentManager.stateStore: IComponentStore get() { return when (this) { is ProjectStoreOwner -> this.componentStore else -> { // module or application service getService(IComponentStore::class.java) } } }
apache-2.0
f77bf499fcf97e1b281347970d1de799
41.0625
140
0.750186
4.409836
false
false
false
false
ylemoigne/ReactKT
subprojects/material/src/main/kotlin/fr/javatic/reactkt/material/components/AbstractInputfieldProps.kt
1
1080
/* * Copyright 2015 Yann Le Moigne * * 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 fr.javatic.reactkt.material.components import fr.javatic.reactkt.core.Props abstract class AbstractInputfieldProps( val className: String? = null, val id: String? = null, val label: String? = null, val floatingLabel: Boolean? = null, val error: String? = null, val expandable: Boolean? = null, val button: Boolean? = null, val icon: Boolean? = null, val expandableHolder: Boolean? = null ) : Props()
apache-2.0
982c00592dae319bb7f27bf576b6ca55
33.870968
75
0.690741
4.044944
false
false
false
false
anthonycr/Lightning-Browser
app/src/main/java/acr/browser/lightning/extensions/ContextExtensions.kt
1
1835
@file:Suppress("NOTHING_TO_INLINE") package acr.browser.lightning.extensions import android.content.Context import android.graphics.drawable.Drawable import android.os.Build import android.view.LayoutInflater import android.widget.Toast import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.DimenRes import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.core.content.ContextCompat import java.util.Locale /** * Returns the dimension in pixels. * * @param dimenRes the dimension resource to fetch. */ inline fun Context.dimen(@DimenRes dimenRes: Int): Int = resources.getDimensionPixelSize(dimenRes) /** * Returns the [ColorRes] as a [ColorInt] */ @ColorInt inline fun Context.color(@ColorRes colorRes: Int): Int = ContextCompat.getColor(this, colorRes) /** * Shows a toast with the provided [StringRes]. */ inline fun Context.toast(@StringRes stringRes: Int) = Toast.makeText(this, stringRes, Toast.LENGTH_SHORT).show() /** * The [LayoutInflater] available on the [Context]. */ inline val Context.inflater: LayoutInflater get() = LayoutInflater.from(this) /** * Gets a drawable from the context. */ inline fun Context.drawable(@DrawableRes drawableRes: Int): Drawable = ContextCompat.getDrawable(this, drawableRes)!! inline fun Context.themedDrawable(@DrawableRes drawableRes: Int, @ColorInt colorInt: Int): Drawable { val drawable = ContextCompat.getDrawable(this, drawableRes)!! drawable.setTint(colorInt) return drawable } /** * The preferred locale of the user. */ val Context.preferredLocale: Locale get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { resources.configuration.locales[0] } else { @Suppress("DEPRECATION") resources.configuration.locale }
mpl-2.0
48362e3c8a4d15da1bffb16b990d24a0
27.671875
101
0.752589
4.189498
false
false
false
false
SmokSmog/smoksmog-android
app/src/main/kotlin/com/antyzero/smoksmog/ui/widget/StationWidget.kt
1
1896
package com.antyzero.smoksmog.ui.widget import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.widget.RemoteViews import com.antyzero.smoksmog.BuildConfig import com.antyzero.smoksmog.R import com.antyzero.smoksmog.dsl.setBackgroundColor import org.joda.time.DateTime import pl.malopolska.smoksmog.model.Station import smoksmog.air.AirQuality import smoksmog.air.AirQualityIndex class StationWidget : AppWidgetProvider() { override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { appWidgetIds.forEach { StationWidgetService.update(context, it) } } companion object { fun updateWidget(widgetId: Int, context: Context, appWidgetManager: AppWidgetManager, station: Station) { val airQualityIndex = AirQualityIndex.calculate(station) val airQuality = AirQuality.Companion.findByValue(airQualityIndex) val views = RemoteViews(context.packageName, R.layout.widget_station) var name = station.name if (BuildConfig.DEBUG) { name = "Stacja: ${station.name}\nPomiar: ${station.particulates[0].date}\nAktulizacja: ${DateTime.now()}" } views.setTextViewText(R.id.textViewStation, name) views.setTextViewText(R.id.textViewAirQuality, airQualityIndex.format(1)) views.setTextColor(R.id.textViewAirQuality, airQuality.getColor(context)) views.setBackgroundColor(R.id.airIndicator1, airQuality.getColor(context)) views.setBackgroundColor(R.id.airIndicator2, airQuality.getColor(context)) appWidgetManager.updateAppWidget(widgetId, views) } } } private fun Double.format(digits: Int): CharSequence { return java.lang.String.format("%.${digits}f", this) }
gpl-3.0
9c450ea9125ae088562c12b2a08d3d21
35.461538
121
0.721519
4.429907
false
false
false
false
leafclick/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/lang/references/MarkdownAnchorReferenceImpl.kt
1
2826
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.lang.references import com.intellij.codeInsight.daemon.EmptyResolveMessageProvider import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.stubs.StubIndex import com.intellij.util.Processor import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.lang.index.MarkdownHeadersIndex import org.intellij.plugins.markdown.lang.psi.impl.MarkdownHeaderImpl class MarkdownAnchorReferenceImpl internal constructor(private val myAnchor: String, private val myFileReference: FileReference?, private val myPsiElement: PsiElement, private val myOffset: Int) : MarkdownAnchorReference, PsiPolyVariantReferenceBase<PsiElement>( myPsiElement), EmptyResolveMessageProvider { private val file: PsiFile? get() = if (myFileReference != null) myFileReference.resolve() as? PsiFile else myPsiElement.containingFile.originalFile override fun getElement(): PsiElement = myPsiElement override fun getRangeInElement(): TextRange = TextRange(myOffset, myOffset + myAnchor.length) override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> { if (myAnchor.isEmpty()) return PsiElementResolveResult.createResults(myPsiElement) val project = myPsiElement.project return PsiElementResolveResult.createResults(MarkdownAnchorReference.getPsiHeaders(project, canonicalText, file)) } override fun getCanonicalText(): String = myAnchor override fun getVariants(): Array<Any> { val project = myPsiElement.project val list = mutableListOf<String>() StubIndex.getInstance().getAllKeys(MarkdownHeadersIndex.KEY, project) .forEach { key -> StubIndex.getInstance().processElements(MarkdownHeadersIndex.KEY, key, project, file?.let { GlobalSearchScope.fileScope(it) }, MarkdownHeaderImpl::class.java, Processor { list.add(MarkdownAnchorReference.dashed(key)) } ) } return list.toTypedArray() } override fun getUnresolvedMessagePattern(): String = if (file == null) MarkdownBundle.message("markdown.cannot.resolve.anchor.error.message", myAnchor) else MarkdownBundle.message("markdown.cannot.resolve.anchor.in.file.error.message", myAnchor, (file as PsiFile).name) }
apache-2.0
c218f26757eb559def790f0fa29c3536
48.578947
149
0.70736
5.046429
false
false
false
false
leafclick/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/details/CommitDetailsListPanel.kt
1
5162
// 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.vcs.log.ui.details import com.intellij.openapi.Disposable import com.intellij.openapi.editor.colors.EditorColorsListener import com.intellij.openapi.editor.colors.EditorColorsScheme import com.intellij.openapi.progress.util.ProgressWindow import com.intellij.openapi.ui.OnePixelDivider import com.intellij.openapi.ui.VerticalFlowLayout import com.intellij.openapi.vcs.ui.FontUtil import com.intellij.ui.SeparatorComponent import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBLoadingPanel import com.intellij.ui.components.JBScrollPane import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBUI import com.intellij.util.ui.StatusText import com.intellij.util.ui.components.BorderLayoutPanel import com.intellij.vcs.log.CommitId import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.ui.details.commit.CommitDetailsPanel import com.intellij.vcs.log.ui.details.commit.getCommitDetailsBackground import java.awt.* import javax.swing.JPanel import javax.swing.ScrollPaneConstants import kotlin.math.max import kotlin.math.min abstract class CommitDetailsListPanel<Panel : CommitDetailsPanel>(parent: Disposable) : BorderLayoutPanel(), EditorColorsListener { companion object { private const val MAX_ROWS = 50 private const val MIN_SIZE = 20 } private val commitDetailsList = mutableListOf<Panel>() private val mainContentPanel = MainContentPanel() private val loadingPanel = object : JBLoadingPanel(BorderLayout(), parent, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS) { override fun getBackground(): Color = getCommitDetailsBackground() } private val statusText: StatusText = object : StatusText(mainContentPanel) { override fun isStatusVisible(): Boolean = this.text.isNotEmpty() } private val scrollPane = JBScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER).apply { setViewportView(mainContentPanel) border = JBUI.Borders.empty() viewportBorder = JBUI.Borders.empty() } init { loadingPanel.add(scrollPane) addToCenter(loadingPanel) } fun startLoadingDetails() { loadingPanel.startLoading() } fun stopLoadingDetails() { loadingPanel.stopLoading() } fun setStatusText(text: String) { statusText.text = text } protected fun rebuildPanel(rows: Int): Int { val oldRowsCount = commitDetailsList.size val newRowsCount = min(rows, MAX_ROWS) for (i in oldRowsCount until newRowsCount) { val panel = getCommitDetailsPanel() if (i != 0) { mainContentPanel.add(SeparatorComponent(0, OnePixelDivider.BACKGROUND, null)) } mainContentPanel.add(panel) commitDetailsList.add(panel) } // clear superfluous items while (mainContentPanel.componentCount != 0 && mainContentPanel.componentCount > 2 * newRowsCount - 1) { mainContentPanel.remove(mainContentPanel.componentCount - 1) } while (commitDetailsList.size > newRowsCount) { commitDetailsList.removeAt(commitDetailsList.size - 1) } if (rows > MAX_ROWS) { mainContentPanel.add(SeparatorComponent(0, OnePixelDivider.BACKGROUND, null)) val label = JBLabel("(showing $MAX_ROWS of $rows selected commits)").apply { font = FontUtil.getCommitMetadataFont() border = JBUI.Borders.emptyLeft(CommitDetailsPanel.SIDE_BORDER) } mainContentPanel.add(label) } repaint() return newRowsCount } fun forEachPanelIndexed(f: (Int, Panel) -> Unit) { commitDetailsList.forEachIndexed(f) update() } fun setCommits(commits: List<VcsCommitMetadata>) { rebuildPanel(commits.size) if (commits.isEmpty()) { setStatusText(StatusText.getDefaultEmptyText()) return } setStatusText("") forEachPanelIndexed { i, panel -> val commit = commits[i] panel.setCommit(commit) } } fun update() { commitDetailsList.forEach { it.update() } } protected open fun navigate(commitId: CommitId) {} protected abstract fun getCommitDetailsPanel(): Panel override fun globalSchemeChange(scheme: EditorColorsScheme?) { update() } override fun getBackground(): Color = getCommitDetailsBackground() override fun getMinimumSize(): Dimension { val minimumSize = super.getMinimumSize() return Dimension(max(minimumSize.width, JBUIScale.scale(MIN_SIZE)), max(minimumSize.height, JBUIScale.scale(MIN_SIZE))) } private inner class MainContentPanel : JPanel() { init { layout = VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, false) isOpaque = false } // to fight ViewBorder override fun getInsets(): Insets = JBUI.emptyInsets() override fun getBackground(): Color = getCommitDetailsBackground() override fun paintChildren(g: Graphics) { if (statusText.text.isNotEmpty()) { statusText.paint(this, g) } else { super.paintChildren(g) } } } }
apache-2.0
d66f7798328719dd44453bbc47f6bf49
31.068323
140
0.734405
4.345118
false
false
false
false
romannurik/muzei
main/src/main/java/com/google/android/apps/muzei/ChooseProviderFragment.kt
1
23890
/* * 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.google.android.apps.muzei import android.annotation.SuppressLint import android.app.Activity import android.content.ActivityNotFoundException import android.content.ComponentName import android.content.Context import android.content.Intent import android.graphics.Color import android.graphics.Rect import android.net.Uri import android.os.Bundle import android.provider.Settings import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.result.contract.ActivityResultContract import androidx.core.view.GravityCompat import androidx.core.view.isGone import androidx.core.view.isInvisible import androidx.core.view.isVisible import androidx.core.view.updatePadding import androidx.drawerlayout.widget.DrawerLayout import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.ConcatAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import coil.load import com.google.android.apps.muzei.api.provider.MuzeiArtProvider import com.google.android.apps.muzei.api.provider.ProviderContract import com.google.android.apps.muzei.legacy.BuildConfig.LEGACY_AUTHORITY import com.google.android.apps.muzei.notifications.NotificationSettingsDialogFragment import com.google.android.apps.muzei.sync.ProviderManager import com.google.android.apps.muzei.util.collectIn import com.google.android.apps.muzei.util.toast import com.google.android.material.snackbar.Snackbar import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.analytics import com.google.firebase.analytics.ktx.logEvent import com.google.firebase.ktx.Firebase import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import net.nurik.roman.muzei.R import net.nurik.roman.muzei.databinding.ChooseProviderFragmentBinding import net.nurik.roman.muzei.databinding.ChooseProviderItemBinding private class StartActivityFromSettings : ActivityResultContract<ComponentName, Boolean>() { override fun createIntent(context: Context, input: ComponentName): Intent = Intent().setComponent(input) .putExtra(MuzeiArtProvider.EXTRA_FROM_MUZEI, true) override fun parseResult(resultCode: Int, intent: Intent?): Boolean = resultCode == Activity.RESULT_OK } class ChooseProviderFragment : Fragment(R.layout.choose_provider_fragment) { companion object { private const val TAG = "ChooseProviderFragment" private const val START_ACTIVITY_PROVIDER = "startActivityProvider" private const val PAYLOAD_HEADER = "HEADER" private const val PAYLOAD_DESCRIPTION = "DESCRIPTION" private const val PAYLOAD_CURRENT_IMAGE_URI = "CURRENT_IMAGE_URI" private const val PAYLOAD_SELECTED = "SELECTED" private const val PLAY_STORE_PACKAGE_NAME = "com.android.vending" } private val args: ChooseProviderFragmentArgs by navArgs() private var scrolledToProvider = false private val viewModel: ChooseProviderViewModel by viewModels() private var startActivityProvider: String? = null private val providerSetup = registerForActivityResult(StartActivityFromSettings()) { success -> val provider = startActivityProvider if (success && provider != null) { val context = requireContext() lifecycleScope.launch(NonCancellable) { Firebase.analytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM) { param(FirebaseAnalytics.Param.ITEM_LIST_ID, provider) param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "providers") param(FirebaseAnalytics.Param.CONTENT_TYPE, "after_setup") } ProviderManager.select(context, provider) } } startActivityProvider = null } private val providerSettings = registerForActivityResult(StartActivityFromSettings()) { startActivityProvider?.let { authority -> viewModel.refreshDescription(authority) } startActivityProvider = null } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) startActivityProvider = savedInstanceState?.getString(START_ACTIVITY_PROVIDER) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val binding = ChooseProviderFragmentBinding.bind(view) requireActivity().menuInflater.inflate(R.menu.choose_provider_fragment, binding.toolbar.menu) val context = requireContext() binding.toolbar.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.auto_advance_settings -> { if (binding.drawer.isDrawerOpen(GravityCompat.END)) { binding.drawer.closeDrawer(GravityCompat.END) } else { Firebase.analytics.logEvent("auto_advance_open", null) binding.drawer.openDrawer(GravityCompat.END) } true } R.id.auto_advance_disabled -> { Firebase.analytics.logEvent("auto_advance_disabled", null) context.toast(R.string.auto_advance_disabled_description, Toast.LENGTH_LONG) true } R.id.action_notification_settings -> { Firebase.analytics.logEvent("notification_settings_open") { param(FirebaseAnalytics.Param.CONTENT_TYPE, "overflow") } NotificationSettingsDialogFragment.showSettings(context, childFragmentManager) true } else -> false } } binding.drawer.setStatusBarBackgroundColor(Color.TRANSPARENT) binding.drawer.setScrimColor(Color.argb(68, 0, 0, 0)) viewModel.currentProvider.collectIn(viewLifecycleOwner) { provider -> val legacySelected = provider?.authority == LEGACY_AUTHORITY binding.toolbar.menu.findItem(R.id.auto_advance_settings).isVisible = !legacySelected binding.toolbar.menu.findItem(R.id.auto_advance_disabled).isVisible = legacySelected if (legacySelected) { binding.drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END) } else { binding.drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, GravityCompat.END) } } val spacing = resources.getDimensionPixelSize(R.dimen.provider_padding) binding.list.addItemDecoration(object : RecyclerView.ItemDecoration() { override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { outRect.set(spacing, spacing, spacing, spacing) } }) val adapter = ProviderListAdapter() val playStoreAdapter = PlayStoreProviderAdapter() binding.list.adapter = ConcatAdapter(adapter, playStoreAdapter) viewModel.providers.collectIn(viewLifecycleOwner) { adapter.submitList(it) { playStoreAdapter.shouldShow = true if (args.authority != null && !scrolledToProvider) { val index = it.indexOfFirst { providerInfo -> providerInfo.authority == args.authority } if (index != -1) { scrolledToProvider = true requireArguments().remove("authority") binding.list.smoothScrollToPosition(index) } } } } // Show a SnackBar whenever there are unsupported sources installed var snackBar: Snackbar? = null viewModel.unsupportedSources.map { it.size } .distinctUntilChanged().collectIn(viewLifecycleOwner) { count -> if (count > 0) { snackBar = Snackbar.make( binding.providerLayout, resources.getQuantityString(R.plurals.legacy_unsupported_text, count, count), Snackbar.LENGTH_INDEFINITE ).apply { addCallback(object : Snackbar.Callback() { override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { if (isAdded && event != DISMISS_EVENT_CONSECUTIVE) { // Reset the padding now that the SnackBar is dismissed binding.list.updatePadding(bottom = resources.getDimensionPixelSize( R.dimen.provider_padding)) } } }) setAction(R.string.legacy_action_learn_more) { val navController = findNavController() if (navController.currentDestination?.id == R.id.choose_provider_fragment) { navController.navigate(R.id.legacy_info) } } show() // Increase the padding when the SnackBar is shown to avoid // overlapping the last element binding.list.updatePadding(bottom = resources.getDimensionPixelSize( R.dimen.provider_padding_with_snackbar)) } } else { // There's no unsupported sources installed anymore, so just // dismiss any SnackBar that is being shown snackBar?.dismiss() } } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(START_ACTIVITY_PROVIDER, startActivityProvider) } private fun launchProviderSetup(provider: ProviderInfo) { try { startActivityProvider = provider.authority providerSetup.launch(provider.setupActivity) } catch (e: ActivityNotFoundException) { Log.e(TAG, "Can't launch provider setup.", e) } catch (e: SecurityException) { Log.e(TAG, "Can't launch provider setup.", e) } } private fun launchProviderSettings(provider: ProviderInfo) { try { startActivityProvider = provider.authority providerSettings.launch(provider.settingsActivity) } catch (e: ActivityNotFoundException) { Log.e(TAG, "Can't launch provider settings.", e) } catch (e: SecurityException) { Log.e(TAG, "Can't launch provider settings.", e) } } inner class ProviderViewHolder( private val binding: ChooseProviderItemBinding ) : RecyclerView.ViewHolder(binding.root) { private var isSelected = false fun bind( providerInfo: ProviderInfo, clickListener: (Boolean) -> Unit ) = providerInfo.run { itemView.setOnClickListener { clickListener(isSelected) } itemView.setOnLongClickListener { if (packageName == requireContext().packageName) { // Don't open Muzei's app info return@setOnLongClickListener false } // Otherwise open third party extensions try { startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", packageName, null))) Firebase.analytics.logEvent("app_settings_open") { param(FirebaseAnalytics.Param.ITEM_LIST_ID, authority) param(FirebaseAnalytics.Param.ITEM_NAME, title) param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "providers") } } catch (e: ActivityNotFoundException) { return@setOnLongClickListener false } true } setHeader(providerInfo) setDescription(providerInfo) setImage(providerInfo) setSelected(providerInfo) binding.settings.setOnClickListener { Firebase.analytics.logEvent("provider_settings_open") { param(FirebaseAnalytics.Param.ITEM_LIST_ID, authority) param(FirebaseAnalytics.Param.ITEM_NAME, title) param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "providers") } launchProviderSettings(this) } binding.browse.setOnClickListener { val navController = findNavController() if (navController.currentDestination?.id == R.id.choose_provider_fragment) { Firebase.analytics.logEvent("provider_browse_open") { param(FirebaseAnalytics.Param.ITEM_LIST_ID, authority) param(FirebaseAnalytics.Param.ITEM_NAME, title) param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "providers") } navController.navigate( ChooseProviderFragmentDirections.browse( ProviderContract.getContentUri(authority) ) ) } } } fun setHeader(providerInfo: ProviderInfo) = providerInfo.run { binding.icon.setImageDrawable(icon) binding.title.text = title } fun setDescription(providerInfo: ProviderInfo) = providerInfo.run { binding.description.text = description binding.description.isGone = description.isNullOrEmpty() } fun setImage(providerInfo: ProviderInfo) = providerInfo.run { binding.artwork.isVisible = currentArtworkUri != null binding.artwork.load(currentArtworkUri) { lifecycle(viewLifecycleOwner) listener( onError = { _, _ -> binding.artwork.isVisible = false }, onSuccess = { _, _ -> binding.artwork.isVisible = true } ) } } fun setSelected(providerInfo: ProviderInfo) = providerInfo.run { isSelected = selected binding.selected.isInvisible = !selected binding.settings.isVisible = selected && settingsActivity != null binding.browse.isVisible = selected } } inner class ProviderListAdapter : ListAdapter<ProviderInfo, ProviderViewHolder>( object : DiffUtil.ItemCallback<ProviderInfo>() { override fun areItemsTheSame( providerInfo1: ProviderInfo, providerInfo2: ProviderInfo ) = providerInfo1.authority == providerInfo2.authority override fun areContentsTheSame( providerInfo1: ProviderInfo, providerInfo2: ProviderInfo ) = providerInfo1 == providerInfo2 override fun getChangePayload(oldItem: ProviderInfo, newItem: ProviderInfo): Any? { return when { (oldItem.title != newItem.title || oldItem.icon != newItem.icon) && oldItem.copy(title = newItem.title, icon = newItem.icon) == newItem -> PAYLOAD_HEADER oldItem.description != newItem.description && oldItem.copy(description = newItem.description) == newItem -> PAYLOAD_DESCRIPTION oldItem.currentArtworkUri != newItem.currentArtworkUri && oldItem.copy(currentArtworkUri = newItem.currentArtworkUri) == newItem -> PAYLOAD_CURRENT_IMAGE_URI oldItem.selected != newItem.selected && oldItem.copy(selected = newItem.selected) == newItem -> PAYLOAD_SELECTED else -> null } } } ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ProviderViewHolder(ChooseProviderItemBinding.inflate(layoutInflater, parent, false)) override fun onBindViewHolder( holder: ProviderViewHolder, position: Int ) = getItem(position).run { holder.bind(this) { isSelected -> if (isSelected) { val context = context val parentFragment = parentFragment?.parentFragment if (context is Callbacks) { Firebase.analytics.logEvent("choose_provider_reselected", null) context.onRequestCloseActivity() } else if (parentFragment is Callbacks) { Firebase.analytics.logEvent("choose_provider_reselected", null) parentFragment.onRequestCloseActivity() } } else if (setupActivity != null) { Firebase.analytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM) { param(FirebaseAnalytics.Param.ITEM_LIST_ID, authority) param(FirebaseAnalytics.Param.ITEM_NAME, title) param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "providers") param(FirebaseAnalytics.Param.CONTENT_TYPE, "choose") } launchProviderSetup(this) } else { Firebase.analytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM) { param(FirebaseAnalytics.Param.ITEM_LIST_ID, authority) param(FirebaseAnalytics.Param.ITEM_NAME, title) param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "providers") param(FirebaseAnalytics.Param.CONTENT_TYPE, "choose") } val context = requireContext() lifecycleScope.launch(NonCancellable) { ProviderManager.select(context, authority) } } } } override fun onBindViewHolder( holder: ProviderViewHolder, position: Int, payloads: MutableList<Any> ) { when { payloads.isEmpty() -> super.onBindViewHolder(holder, position, payloads) payloads[0] == PAYLOAD_HEADER -> holder.setHeader(getItem(position)) payloads[0] == PAYLOAD_DESCRIPTION -> holder.setDescription(getItem(position)) payloads[0] == PAYLOAD_CURRENT_IMAGE_URI -> holder.setImage(getItem(position)) payloads[0] == PAYLOAD_SELECTED -> holder.setSelected(getItem(position)) else -> throw IllegalArgumentException("Forgot to handle ${payloads[0]}") } } } inner class PlayStoreProviderAdapter : RecyclerView.Adapter<ProviderViewHolder>() { @SuppressLint("InlinedApi") private val playStoreIntent: Intent = Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/search?q=Muzei&c=apps" + "&referrer=utm_source%3Dmuzei" + "%26utm_medium%3Dapp" + "%26utm_campaign%3Dget_more_sources")) .addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT) .setPackage(PLAY_STORE_PACKAGE_NAME) private val playStoreComponentName: ComponentName? = playStoreIntent.resolveActivity( requireContext().packageManager) private val playStoreAuthority: String? = if (playStoreComponentName != null) "play_store" else null private val playStoreProviderInfo = if (playStoreComponentName != null && playStoreAuthority != null) { val pm = requireContext().packageManager ProviderInfo( playStoreAuthority, playStoreComponentName.packageName, requireContext().getString(R.string.get_more_sources), requireContext().getString(R.string.get_more_sources_description), null, pm.getActivityLogo(playStoreIntent) ?: pm.getApplicationIcon(PLAY_STORE_PACKAGE_NAME), null, null, false) } else { null } /** * We want to wait for the main list to load before showing our item so that the * RecyclerView doesn't attempt to keep this footer on screen when the other * data loads, so we delay loading until that occurs. Changing this to true is * our signal */ var shouldShow = false set(value) { if (field != value) { field = value if (playStoreProviderInfo != null) { if (value) { notifyItemInserted(0) } else { notifyItemRemoved(0) } } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ProviderViewHolder(ChooseProviderItemBinding.inflate(layoutInflater, parent, false)) override fun getItemCount() = if (shouldShow && playStoreProviderInfo != null) 1 else 0 override fun onBindViewHolder(holder: ProviderViewHolder, position: Int) { holder.bind(playStoreProviderInfo!!) { Firebase.analytics.logEvent("more_sources_open", null) try { startActivity(playStoreIntent) } catch (e: ActivityNotFoundException) { requireContext().toast(R.string.play_store_not_found, Toast.LENGTH_LONG) } catch (e: SecurityException) { requireContext().toast(R.string.play_store_not_found, Toast.LENGTH_LONG) } } } } fun interface Callbacks { fun onRequestCloseActivity() } }
apache-2.0
7b79b221a4ca33abe4e3ebfc30b72864
44.162571
111
0.585559
5.650426
false
false
false
false
leafclick/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/JavadocHtmlLintInspectionTest.kt
1
3250
// 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.java.codeInsight.daemon import com.intellij.codeInspection.javaDoc.JavadocHtmlLintInspection import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.impl.JavaSdkImpl import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.fixtures.DefaultLightProjectDescriptor import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase import com.intellij.util.lang.JavaVersion import java.io.File private val DESCRIPTOR = object : DefaultLightProjectDescriptor() { override fun getSdk(): Sdk? { val jreHome = File(System.getProperty("java.home")) val jdkHome = if (jreHome.name == "jre") jreHome.parentFile else jreHome return (JavaSdk.getInstance() as JavaSdkImpl).createMockJdk("java version \"{${JavaVersion.current()}}\"", jdkHome.path, false) } } class JavadocHtmlLintInspectionTest : LightJavaCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor = DESCRIPTOR fun testNoComment() = doTest("class C { }") fun testEmptyComment() = doTest("/** */\nclass C { }") @Suppress("GrazieInspection") fun testCommonErrors() = doTest(""" package pkg; /** * <ul><error descr="Tag not allowed here: <p>"><p></error>Paragraph inside a list</p></ul> * * Empty paragraph: <error descr="Self-closing element not allowed"><p/></error> * * Line break: <error descr="Self-closing element not allowed"><br/></error> * Another one: <br><error descr="Invalid end tag: </br>"></br></error> * And the last one: <br> <error descr="Invalid end tag: </br>"></br></error> * * Missing open tag: <error descr="Unexpected end tag: </i>"></i></error> * * Unescaped angle brackets for generics: List<error descr="Unknown tag: String"><String></error> * (closing it here to avoid further confusion: <error descr="Unknown tag: String"></String></error>) * Correct: {@code List<String>} * * Unknown attribute: <br <error descr="Unknown attribute: a">a</error>=""> * * <p <error descr="Invalid name for anchor: \"1\"">id</error>="1" <error descr="Repeated attribute: id">id</error>="A">Some repeated attributes</p> * * <p>Empty ref: <a <error descr="Attribute lacks value">href</error>="">link</a></p> * * <error descr="Header used out of sequence: <H4>"><h4></error>Incorrect header</h4> * * Unknown entity: <error descr="Invalid entity &wtf;">&wtf;</error> * * @see bad_link should report no error */ class C { }""".trimIndent()) fun testPackageInfo() = doTest(""" /** * Another self-closed paragraph: <error descr="Self-closing element not allowed"><p/></error> */ package pkg;""".trimIndent(), "package-info.java") private fun doTest(text: String, name: String? = null) { myFixture.enableInspections(JavadocHtmlLintInspection()) myFixture.configureByText(name ?: "${getTestName(false)}.java", text) myFixture.checkHighlighting(true, false, false) } }
apache-2.0
d6293e8a1a27120b89b0a825eb95abb8
44.152778
152
0.691077
4.093199
false
true
false
false
muhrifqii/Maos
app/src/main/java/io/github/muhrifqii/maos/AppModule.kt
1
3957
/* * Copyright 2017 Muhammad Rifqi Fatchurrahman Putra Danar * * 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.github.muhrifqii.maos import android.app.Application import android.content.Context import android.content.SharedPreferences import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.content.res.AssetManager import android.content.res.Resources import android.preference.PreferenceManager import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import com.serjltt.moshi.adapters.FirstElementJsonAdapter import com.serjltt.moshi.adapters.WrappedJsonAdapter import com.squareup.moshi.Moshi import dagger.Module import dagger.Provides import io.github.muhrifqii.maos.libs.Secrets import io.github.muhrifqii.maos.libs.ViewModelParams import io.github.muhrifqii.maos.libs.qualifiers.ApplicationContext import io.github.muhrifqii.maos.libs.qualifiers.IsbndbRetrofit import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.HttpLoggingInterceptor.Level.BODY import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import javax.inject.Singleton /** * Created on : 23/01/17 * Author : muhrifqii * Name : Muhammad Rifqi Fatchurrahman Putra Danar * Github : https://github.com/muhrifqii * LinkedIn : https://linkedin.com/in/muhrifqii */ @Module class AppModule(val app: MaosApplication) { @Provides @Singleton @ApplicationContext fun provideContext(): Context = app @Provides @Singleton fun provideApplication(): Application = app @Provides @Singleton fun provideAssetManager(): AssetManager = app.assets @Provides @Singleton fun providePackageInfo(): PackageInfo = app.packageManager .getPackageInfo(app.packageName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) @Provides @Singleton fun provideResources(): Resources = app.resources @Provides @Singleton fun provideSharedPreferences(): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(app) @Provides @Singleton fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor = HttpLoggingInterceptor().setLevel(BODY) // log body and header @Provides @Singleton fun provideMoshi(): Moshi = Moshi.Builder().apply { add(WrappedJsonAdapter.FACTORY) add(FirstElementJsonAdapter.FACTORY) }.build() @Provides @Singleton fun provideOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient = OkHttpClient.Builder().apply { if (BuildConfig.DEBUG) addInterceptor(httpLoggingInterceptor) }.build() // network log ez @Provides @Singleton @IsbndbRetrofit fun provideIsbndbRetrofit(okHttpClient: OkHttpClient, moshi: Moshi): Retrofit = createRetrofit("http://isbndb.com/api/v2/json/${Secrets.ISBNDB_API_KEY}", okHttpClient, moshi) @Provides @Singleton fun provideViewModelParams(sharedPreferences: SharedPreferences): ViewModelParams = ViewModelParams( x = 0, sharedPreferences = sharedPreferences ) private fun createRetrofit(baseUrl: String, okHttpClient: OkHttpClient, moshi: Moshi): Retrofit = Retrofit.Builder().apply { client(okHttpClient) baseUrl(baseUrl) addConverterFactory(MoshiConverterFactory.create(moshi)) addCallAdapterFactory(RxJava2CallAdapterFactory.create()) }.build() }
apache-2.0
d8e36e124d711cd3016c0572b34e71bc
35.311927
100
0.767753
4.666274
false
false
false
false
android/compose-samples
Crane/app/src/main/java/androidx/compose/samples/crane/calendar/Calendar.kt
1
6292
/* * 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 * * 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 androidx.compose.samples.crane.calendar import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.EaseOutQuart import androidx.compose.animation.core.TweenSpec import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.consumedWindowInsets import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.windowInsetsBottomHeight import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.samples.crane.calendar.model.CalendarState import androidx.compose.samples.crane.calendar.model.CalendarUiState import androidx.compose.samples.crane.calendar.model.Month import androidx.compose.samples.crane.ui.CraneTheme import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import java.time.DayOfWeek import java.time.LocalDate import java.time.temporal.TemporalAdjusters import java.time.temporal.WeekFields @OptIn(ExperimentalLayoutApi::class) @Composable fun Calendar( calendarState: CalendarState, onDayClicked: (date: LocalDate) -> Unit, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues() ) { val calendarUiState = calendarState.calendarUiState.value val numberSelectedDays = calendarUiState.numberSelectedDays.toInt() val selectedAnimationPercentage = remember(numberSelectedDays) { Animatable(0f) } // Start a Launch Effect when the number of selected days change. // using .animateTo() we animate the percentage selection from 0f - 1f LaunchedEffect(numberSelectedDays) { if (calendarUiState.hasSelectedDates) { val animationSpec: TweenSpec<Float> = tween( durationMillis = (numberSelectedDays.coerceAtLeast(0) * DURATION_MILLIS_PER_DAY) .coerceAtMost(2000), easing = EaseOutQuart ) selectedAnimationPercentage.animateTo( targetValue = 1f, animationSpec = animationSpec ) } } LazyColumn( modifier = modifier.consumedWindowInsets(contentPadding), contentPadding = contentPadding ) { calendarState.listMonths.forEach { month -> itemsCalendarMonth( calendarUiState, onDayClicked, { selectedAnimationPercentage.value }, month ) } item(key = "bottomSpacer") { Spacer( modifier = Modifier.windowInsetsBottomHeight( WindowInsets.navigationBars ) ) } } } private fun LazyListScope.itemsCalendarMonth( calendarUiState: CalendarUiState, onDayClicked: (LocalDate) -> Unit, selectedPercentageProvider: () -> Float, month: Month ) { item(month.yearMonth.month.name + month.yearMonth.year + "header") { MonthHeader( modifier = Modifier.padding(start = 32.dp, end = 32.dp, top = 32.dp), month = month.yearMonth.month.name, year = month.yearMonth.year.toString() ) } // Expanding width and centering horizontally val contentModifier = Modifier .fillMaxWidth() .wrapContentWidth(Alignment.CenterHorizontally) item(month.yearMonth.month.name + month.yearMonth.year + "daysOfWeek") { DaysOfWeek(modifier = contentModifier) } // A custom key needs to be given to these items so that they can be found in tests that // need scrolling. The format of the key is ${year/month/weekNumber}. Thus, // the key for the fourth week of December 2020 is "2020/12/4" itemsIndexed(month.weeks, key = { index, _ -> month.yearMonth.year.toString() + "/" + month.yearMonth.month.value + "/" + (index + 1).toString() }) { _, week -> val beginningWeek = week.yearMonth.atDay(1).plusWeeks(week.number.toLong()) val currentDay = beginningWeek.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)) if (calendarUiState.hasSelectedPeriodOverlap( currentDay, currentDay.plusDays(6) ) ) { WeekSelectionPill( state = calendarUiState, currentWeekStart = currentDay, widthPerDay = CELL_SIZE, week = week, selectedPercentageTotalProvider = selectedPercentageProvider ) } Week( calendarUiState = calendarUiState, modifier = contentModifier, week = week, onDayClicked = onDayClicked ) Spacer(Modifier.height(8.dp)) } } internal val CALENDAR_STARTS_ON = WeekFields.ISO @Preview @Composable fun DayPreview() { CraneTheme { Calendar(CalendarState(), onDayClicked = { }) } }
apache-2.0
02cf12ef6232fcf3585f0115533f9370
35.16092
95
0.688334
4.723724
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/util/DescriptorMemberChooserObject.kt
3
3806
// 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.core.util import com.intellij.codeInsight.generation.ClassMemberWithElement import com.intellij.codeInsight.generation.MemberChooserObject import com.intellij.codeInsight.generation.PsiElementMemberChooserObject import com.intellij.openapi.util.Iconable import com.intellij.openapi.util.NlsSafe import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiMember import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.KotlinDescriptorIconProvider import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.renderer.ClassifierNamePolicy import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import javax.swing.Icon open class DescriptorMemberChooserObject( psiElement: PsiElement, open val descriptor: DeclarationDescriptor ) : PsiElementMemberChooserObject( psiElement, getText(descriptor), getIcon(psiElement, descriptor) ), ClassMemberWithElement { override fun getParentNodeDelegate(): MemberChooserObject { val parent = descriptor.containingDeclaration ?: error("No parent for $descriptor") val declaration = if (psiElement is KtDeclaration) { // kotlin PsiTreeUtil.getStubOrPsiParentOfType(psiElement, KtNamedDeclaration::class.java) ?: PsiTreeUtil.getStubOrPsiParentOfType(psiElement, KtFile::class.java) } else { // java or compiled (psiElement as PsiMember).containingClass } ?: error("No parent for $psiElement") return when (declaration) { is KtFile -> PsiElementMemberChooserObject(declaration, declaration.name) else -> DescriptorMemberChooserObject(declaration, parent) } } override fun equals(other: Any?) = this === other || other is DescriptorMemberChooserObject && descriptor == other.descriptor override fun hashCode() = descriptor.hashCode() override fun getElement() = psiElement companion object { private val MEMBER_RENDERER = DescriptorRenderer.withOptions { withDefinedIn = false modifiers = emptySet() startFromName = true classifierNamePolicy = ClassifierNamePolicy.SHORT } @NlsSafe fun getText(descriptor: DeclarationDescriptor): String { return if (descriptor is ClassDescriptor) descriptor.fqNameUnsafe.render() else MEMBER_RENDERER.render(descriptor) } fun getIcon(declaration: PsiElement?, descriptor: DeclarationDescriptor): Icon? = if (declaration != null && declaration.isValid) { val isClass = declaration is PsiClass || declaration is KtClass val flags = if (isClass) 0 else Iconable.ICON_FLAG_VISIBILITY if (declaration is KtDeclaration) { // kotlin declaration // visibility and abstraction better detect by a descriptor KotlinDescriptorIconProvider.getIcon(descriptor, declaration, flags) } else { // it is better to show java icons for java code declaration.getIcon(flags) } } else { KotlinDescriptorIconProvider.getIcon(descriptor, declaration, 0) } } }
apache-2.0
2b96865f6f0c5bb6f8d2def559ba53d4
41.764045
158
0.719128
5.353024
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/fromJavaToKotlin/removeOverrideInChildFromJava.kt
12
692
open class B: A() { override fun a() = Unit } open class B2: A() { override fun a() = Unit } class B3: A() { final override fun a() = Unit } class C : B() { override fun a() = Unit } class C2 : B() { override fun a() = Unit } interface KotlinInterface { fun a() } open class B3: A(), KotlinInterface { override fun a() = Unit } interface NextKotlinInterface : KotlinInterface open class B4: A(), NextKotlinInterface { override fun a() = Unit } abstract class B5 : A() { abstract override fun a() } class C3 : B5() { override fun a() = Unit } class C4 : B5() { final override fun a() = Unit } class B6 : A() { final fun a() = Unit }
apache-2.0
6f69d8f10af0925dc74edad453b76df6
13.122449
47
0.583815
3.048458
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/openapi/options/advanced/AdvancedSettingsImpl.kt
1
11013
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.options.advanced import com.intellij.BundleBase import com.intellij.DynamicBundle import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationBundle import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponentWithModificationTracker import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.extensions.* import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.KeyedExtensionCollector import com.intellij.serialization.MutableAccessor import com.intellij.util.KeyedLazyInstance import com.intellij.util.text.nullize import com.intellij.util.xmlb.XmlSerializerUtil import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Transient import org.jetbrains.annotations.Nls import org.jetbrains.annotations.TestOnly import java.util.* class AdvancedSettingBean : PluginAware, KeyedLazyInstance<AdvancedSettingBean> { private var pluginDescriptor: PluginDescriptor? = null val enumKlass: Class<Enum<*>>? by lazy { @Suppress("UNCHECKED_CAST") if (enumClass.isNotBlank()) (pluginDescriptor?.pluginClassLoader ?: javaClass.classLoader).loadClass(enumClass) as Class<Enum<*>> else null } @Transient override fun setPluginDescriptor(pluginDescriptor: PluginDescriptor) { this.pluginDescriptor = pluginDescriptor } fun getPluginDescriptor(): PluginDescriptor? { return this.pluginDescriptor } /** * The ID of the setting. Used to access its value from code; can also be used to search for the setting. If a registry value with the * same ID was changed by the user, the changed value will be migrated to the advanced settings. */ @Attribute("id") @RequiredElement @JvmField var id: String = "" /** * The default value of the setting. Also determines the type of control used to display the setting. If [enumClass] is specified, * the setting is shown as a combobox. If the default value is `true` or `false`, the setting is shown as a checkbox. Otherwise, the * setting is shown as a text field, and if the default value is an integer, only integers will be accepted as property values. */ @Attribute("default") @RequiredElement @JvmField var defaultValue = "" /** * Name of the property in the resource bundle [bundle] which holds the label for the setting displayed in the UI. * If not specified, the default is `advanced.setting.<id>` */ @Attribute("titleKey") @JvmField var titleKey: String = "" /** * Name of the property in the resource bundle [bundle] which holds the name of the group in which the setting is displayed in the UI. * If not specified, the setting will be shown in the "Other" group. */ @Attribute("groupKey") @JvmField var groupKey: String = "" /** * Name of the property in the resource bundle [bundle] which holds the comment displayed in the UI underneath the control for editing * the property. If not specified, the default is `advanced.setting.<id>.description`. */ @Attribute("descriptionKey") @JvmField var descriptionKey: String = "" /** * Name of the property in the resource bundle [bundle] which holds the trailing label displayed in the UI to the right of the * control for editing the setting value. If not specified, the default is `advanced.setting.<id>.trailingLabel`. */ @Attribute("trailingLabelKey") @JvmField var trailingLabelKey: String = "" /** * The resource bundle containing the label and other UI text for this option. If not specified, [ApplicationBundle] is used for settings * declared in the platform, and the plugin resource bundle is used for settings defined in plugins. */ @Attribute("bundle") @JvmField var bundle: String = "" @Attribute("enumClass") @JvmField var enumClass: String = "" /** * Fully-qualified name of the service class which stores the value of the setting. Should be used only when migrating regular * settings to advanced settings. */ @Attribute("service") @JvmField var service: String = "" /** * Name of the field or property of the class specified in [service] which stores the value of the setting. Should be used only when * migrating regular settings to advanced settings. */ @Attribute("property") @JvmField var property: String = "" fun type(): AdvancedSettingType { return when { enumClass.isNotBlank() -> AdvancedSettingType.Enum defaultValue.toIntOrNull() != null -> AdvancedSettingType.Int defaultValue == "true" || defaultValue == "false" -> AdvancedSettingType.Bool else -> AdvancedSettingType.String } } @Nls fun title(): String { return findBundle()?.let { BundleBase.message(it, titleKey.ifEmpty { "advanced.setting.$id" }) } ?: "!$id!" } @Nls fun group(): String? { if (groupKey.isEmpty()) return null return findBundle()?.let { BundleBase.message(it, groupKey) } } @Nls fun description(): String? { val descriptionKey = descriptionKey.ifEmpty { "advanced.setting.$id.description" } return findBundle()?.takeIf { it.containsKey(descriptionKey) }?.let { BundleBase.message(it, descriptionKey) } } @Nls fun trailingLabel(): String? { val trailingLabelKey = trailingLabelKey.ifEmpty { "advanced.setting.$id.trailingLabel" } return findBundle()?.takeIf { it.containsKey(trailingLabelKey) }?.let { BundleBase.message(it, trailingLabelKey) } } fun valueFromString(valueString: String): Any { return when (type()) { AdvancedSettingType.Int -> valueString.toInt() AdvancedSettingType.Bool -> valueString.toBoolean() AdvancedSettingType.String -> valueString AdvancedSettingType.Enum -> { try { java.lang.Enum.valueOf(enumKlass!!, valueString) } catch (e: IllegalArgumentException) { java.lang.Enum.valueOf(enumKlass!!, defaultValue) } } } } fun valueToString(value: Any): String { return if (type() == AdvancedSettingType.Enum) (value as Enum<*>).name else value.toString() } val defaultValueObject by lazy { valueFromString(defaultValue) } private fun findBundle(): ResourceBundle? { val bundleName = bundle.nullize() ?: pluginDescriptor?.takeIf { it.pluginId.idString == "com.intellij" } ?.let { ApplicationBundle.BUNDLE } ?: pluginDescriptor?.resourceBundleBaseName ?: return null val classLoader = pluginDescriptor?.pluginClassLoader ?: javaClass.classLoader return DynamicBundle.INSTANCE.getResourceBundle(bundleName, classLoader) } val serviceInstance: Any? by lazy { if (service.isEmpty()) null else { val classLoader = pluginDescriptor?.pluginClassLoader ?: javaClass.classLoader ApplicationManager.getApplication().getService(classLoader.loadClass(service)) } } val accessor: MutableAccessor? by lazy { if (property.isEmpty()) null else serviceInstance?.let { instance -> XmlSerializerUtil.getAccessors(instance.javaClass).find { it.name == property } } } companion object { @JvmField val EP_NAME = ExtensionPointName<AdvancedSettingBean>("com.intellij.advancedSetting") } override fun getKey(): String = id override fun getInstance(): AdvancedSettingBean = this } @State(name = "AdvancedSettings", storages = [Storage("advancedSettings.xml"), Storage(value = "ide.general.xml", deprecated = true)]) class AdvancedSettingsImpl : AdvancedSettings(), PersistentStateComponentWithModificationTracker<AdvancedSettingsImpl.AdvancedSettingsState>, Disposable { class AdvancedSettingsState { var settings = mutableMapOf<String, String>() } private val epCollector = KeyedExtensionCollector<AdvancedSettingBean, String>(AdvancedSettingBean.EP_NAME.name) private var state = mutableMapOf<String, Any>() private var defaultValueCache = mutableMapOf<String, Any>() private var modificationCount = 0L init { AdvancedSettingBean.EP_NAME.addExtensionPointListener(object : ExtensionPointListener<AdvancedSettingBean?> { override fun extensionRemoved(extension: AdvancedSettingBean, pluginDescriptor: PluginDescriptor) { defaultValueCache.remove(extension.id) } }, this) } override fun dispose() { } override fun getState(): AdvancedSettingsState { return AdvancedSettingsState().also { state.map { (k, v) -> k to getOption(k).valueToString(v) }.toMap(it.settings) } } override fun loadState(state: AdvancedSettingsState) { this.state.clear() state.settings.mapNotNull { (k, v) -> getOptionOrNull(k)?.let { option -> k to option.valueFromString(v) } }.toMap(this.state) } override fun getStateModificationCount() = modificationCount override fun setSetting(id: String, value: Any, expectType: AdvancedSettingType) { val option = getOption(id) if (option.type() != expectType) { throw IllegalArgumentException("Setting type ${option.type()} does not match parameter type $expectType") } val instance = option.serviceInstance if (instance != null) { option.accessor?.let { it.set(instance, value) return } } val oldValue = getSetting(id) if (option.defaultValueObject == value) { state.remove(id) } else { state.put(id, value) } modificationCount++ ApplicationManager.getApplication().messageBus.syncPublisher(AdvancedSettingsChangeListener.TOPIC) .advancedSettingChanged(id, oldValue, value) } override fun getSetting(id: String): Any { val option = getOption(id) val instance = option.serviceInstance if (instance != null) { option.accessor?.let { return it.read(instance) } } return state.get(id) ?: defaultValueCache.getOrPut(id) { getOption(id).defaultValueObject } } override fun getDefault(id: String): Any { return getOption(id).defaultValueObject } private fun getOption(id: String): AdvancedSettingBean { return getOptionOrNull(id) ?: throw IllegalArgumentException("Can't find advanced setting $id") } private fun getOptionOrNull(id: String): AdvancedSettingBean? = epCollector.findSingle(id) private fun getSettingAndType(id: String): Pair<Any, AdvancedSettingType> { val option = getOption(id) return getSetting(id) to option.type() } fun isNonDefault(id: String): Boolean { return id in state } @TestOnly fun setSetting(id: String, value: Any, revertOnDispose: Disposable) { val (oldValue, type) = getSettingAndType(id) setSetting(id, value, type) Disposer.register(revertOnDispose, Disposable { setSetting(id, oldValue, type )}) } }
apache-2.0
883a0ae14566ff3761fa43c8ee8014b5
34.525806
158
0.7157
4.528372
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/services/apiresponses/MessageThreadEnvelope.kt
1
1811
package com.kickstarter.services.apiresponses import android.os.Parcelable import com.kickstarter.models.Message import com.kickstarter.models.MessageThread import com.kickstarter.models.User import kotlinx.parcelize.Parcelize @Parcelize class MessageThreadEnvelope private constructor( private val messages: List<Message>?, private val messageThread: MessageThread?, private val participants: List<User>, ) : Parcelable { fun messages() = this.messages fun messageThread() = this.messageThread fun participants() = this.participants @Parcelize data class Builder( private var messages: List<Message>? = null, private var messageThread: MessageThread? = null, private var participants: List<User> = emptyList() ) : Parcelable { fun messages(messages: List<Message>?) = apply { this.messages = messages } fun messageThread(messageThread: MessageThread?) = apply { this.messageThread = messageThread } fun participants(participants: List<User>) = apply { this.participants = participants } fun build() = MessageThreadEnvelope( messages = messages, messageThread = messageThread, participants = participants ) } override fun equals(obj: Any?): Boolean { var equals = super.equals(obj) if (obj is MessageThreadEnvelope) { equals = messages() == obj.messages() && messageThread() == obj.messageThread() && participants() == obj.participants() } return equals } fun toBuilder() = Builder( messages = messages, messageThread = messageThread, participants = participants ) companion object { @JvmStatic fun builder() = Builder() } }
apache-2.0
3ffc4a920777833a54821489161bb5f3
31.927273
103
0.654887
4.921196
false
false
false
false
ingokegel/intellij-community
platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ActionManagerEx.kt
1
4617
// 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.actionSystem.ex import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.EDT import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.asContextElement import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.extensions.PluginId import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.jetbrains.annotations.ApiStatus import java.util.function.Consumer import javax.swing.KeyStroke @Suppress("DeprecatedCallableAddReplaceWith") abstract class ActionManagerEx : ActionManager() { companion object { @JvmStatic fun getInstanceEx(): ActionManagerEx = getInstance() as ActionManagerEx /** * Similar to [KeyStroke.getKeyStroke] but allows keys in lower case. * * I.e. "control x" is accepted and interpreted as "control X". * * @return null if string cannot be parsed. */ @JvmStatic fun getKeyStroke(s: String): KeyStroke? { var result = try { KeyStroke.getKeyStroke(s) } catch (ignore: Exception) { null } if (result == null && s.length >= 2 && s[s.length - 2] == ' ') { try { val s1 = s.substring(0, s.length - 1) + s[s.length - 1].uppercaseChar() result = KeyStroke.getKeyStroke(s1) } catch (ignored: Exception) { } } return result } @ApiStatus.Internal @JvmStatic fun doWithLazyActionManager(whatToDo: Consumer<ActionManager>) { withLazyActionManager(scope = null, task = whatToDo::accept) } @ApiStatus.Internal inline fun withLazyActionManager(scope: CoroutineScope?, crossinline task: (ActionManager) -> Unit) { val app = ApplicationManager.getApplication() val created = app.serviceIfCreated<ActionManager>() if (created == null) { // IO, because getInstance is blocking (there is no non-blocking API to get service yet) (scope ?: app.coroutineScope).launch(Dispatchers.IO) { val actionManager = getInstance() withContext(Dispatchers.EDT + ModalityState.any().asContextElement()) { task(actionManager) } } } else { task(created) } } } abstract fun createActionToolbar(place: String, group: ActionGroup, horizontal: Boolean, decorateButtons: Boolean): ActionToolbar /** * Do not call directly, prefer [ActionUtil] methods. */ @ApiStatus.Internal abstract fun fireBeforeActionPerformed(action: AnAction, event: AnActionEvent) /** * Do not call directly, prefer [ActionUtil] methods. */ @ApiStatus.Internal abstract fun fireAfterActionPerformed(action: AnAction, event: AnActionEvent, result: AnActionResult) @Deprecated("use {@link #fireBeforeActionPerformed(AnAction, AnActionEvent)} instead") fun fireBeforeActionPerformed(action: AnAction, dataContext: DataContext, event: AnActionEvent) { fireBeforeActionPerformed(action, event) } @Deprecated("use {@link #fireAfterActionPerformed(AnAction, AnActionEvent, AnActionResult)} instead") fun fireAfterActionPerformed(action: AnAction, dataContext: DataContext, event: AnActionEvent) { fireAfterActionPerformed(action, event, AnActionResult.PERFORMED) } abstract fun fireBeforeEditorTyping(c: Char, dataContext: DataContext) abstract fun fireAfterEditorTyping(c: Char, dataContext: DataContext) /** * For logging purposes */ abstract val lastPreformedActionId: String? abstract val prevPreformedActionId: String? /** * A comparator that compares action ids (String) by the order of action registration. * * @return a negative integer if the action that corresponds to the first id was registered earlier than the action that corresponds * to the second id; zero if both ids are equal; a positive number otherwise. */ abstract val registrationOrderComparator: Comparator<String> abstract fun getPluginActions(pluginId: PluginId): Array<String> abstract val isActionPopupStackEmpty: Boolean /** * Allows receiving notifications when popup menus created from action groups are shown and hidden. */ abstract fun addActionPopupMenuListener(listener: ActionPopupMenuListener, parentDisposable: Disposable) }
apache-2.0
6ad257091cb07f6037f26724f9ff804c
34.79845
134
0.725146
4.740246
false
false
false
false
siosio/intellij-community
plugins/kotlin/completion/tests/testData/weighers/smart/BooleanExpected.kt
2
525
// WITH_RUNTIME var nonNullable: Boolean = true var nullableX: Boolean? = null var nullableFoo: Boolean? = null fun foo(pFoo: Boolean, s: String) { val local = true foo(<caret>) } // ORDER: pFoo // ORDER: nullableFoo // ORDER: nullableFoo // ORDER: "pFoo, s" // ORDER: true // ORDER: false // ORDER: "pFoo = true" // ORDER: "pFoo = false" // ORDER: local // ORDER: nonNullable // ORDER: maxOf // ORDER: maxOf // ORDER: maxOf // ORDER: minOf // ORDER: minOf // ORDER: minOf // ORDER: nullableX // ORDER: nullableX
apache-2.0
95bc2709c60fd5342faf1bd236c19e8f
16.5
35
0.645714
3.088235
false
false
false
false
siosio/intellij-community
platform/service-container/src/com/intellij/serviceContainer/ComponentManagerImpl.kt
1
55285
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:Suppress("DeprecatedCallableAddReplaceWith", "ReplaceNegatedIsEmptyWithIsNotEmpty") package com.intellij.serviceContainer import com.intellij.diagnostic.* import com.intellij.diagnostic.StartUpMeasurer.startActivity import com.intellij.ide.plugins.* import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.idea.Main import com.intellij.openapi.Disposable import com.intellij.openapi.application.AccessToken import com.intellij.openapi.application.Application import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.components.* import com.intellij.openapi.components.ServiceDescriptor.PreloadMode import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.components.impl.stores.IComponentStoreOwner import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.* import com.intellij.openapi.extensions.impl.ExtensionPointImpl import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressIndicatorProvider import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.UserDataHolderBase import com.intellij.util.ArrayUtil import com.intellij.util.messages.* import com.intellij.util.messages.impl.MessageBusEx import com.intellij.util.messages.impl.MessageBusImpl import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.ApiStatus.Internal import org.jetbrains.annotations.TestOnly import org.picocontainer.ComponentAdapter import org.picocontainer.PicoContainer import java.lang.invoke.MethodHandles import java.lang.invoke.MethodType import java.lang.reflect.Constructor import java.lang.reflect.InvocationTargetException import java.lang.reflect.Modifier import java.util.* import java.util.concurrent.* import java.util.concurrent.atomic.AtomicReference internal val LOG = logger<ComponentManagerImpl>() private val constructorParameterResolver = ConstructorParameterResolver() private val methodLookup = MethodHandles.lookup() private val emptyConstructorMethodType = MethodType.methodType(Void.TYPE) @Internal abstract class ComponentManagerImpl @JvmOverloads constructor( internal val parent: ComponentManagerImpl?, setExtensionsRootArea: Boolean = parent == null ) : ComponentManager, Disposable.Parent, MessageBusOwner, UserDataHolderBase(), PicoContainer, ComponentManagerEx, IComponentStoreOwner { protected enum class ContainerState { PRE_INIT, COMPONENT_CREATED, DISPOSE_IN_PROGRESS, DISPOSED, DISPOSE_COMPLETED } companion object { @Internal @JvmField val fakeCorePluginDescriptor = DefaultPluginDescriptor(PluginManagerCore.CORE_ID, null) @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") @Internal @JvmField val badWorkspaceComponents: Set<String> = java.util.Set.of( "jetbrains.buildServer.codeInspection.InspectionPassRegistrar", "jetbrains.buildServer.testStatus.TestStatusPassRegistrar", "jetbrains.buildServer.customBuild.lang.gutterActions.CustomBuildParametersGutterActionsHighlightingPassRegistrar", ) // not as file level function to avoid scope cluttering @ApiStatus.Internal fun createAllServices(componentManager: ComponentManagerImpl, exclude: Set<String>) { for (o in componentManager.componentKeyToAdapter.values) { if (o !is ServiceComponentAdapter) { continue } val implementation = o.descriptor.serviceImplementation try { if (implementation == "org.jetbrains.plugins.groovy.mvc.MvcConsole") { // NPE in RunnerContentUi.setLeftToolbar continue } if (implementation == "org.jetbrains.plugins.grails.lang.gsp.psi.gsp.impl.gtag.GspTagDescriptorService") { // requires a read action continue } if (exclude.contains(implementation)) { invokeAndWaitIfNeeded { o.getInstance<Any>(componentManager, null) } } else { o.getInstance<Any>(componentManager, null) } } catch (e: Throwable) { LOG.error("Cannot create $implementation", e) } } } } private val componentKeyToAdapter = ConcurrentHashMap<Any, ComponentAdapter>() private val componentAdapters = LinkedHashSetWrapper<ComponentAdapter>() private val serviceInstanceHotCache = ConcurrentHashMap<Class<*>, Any?>() protected val containerState = AtomicReference(ContainerState.PRE_INIT) protected val containerStateName: String get() = containerState.get().name @Suppress("LeakingThis") private val _extensionArea by lazy { ExtensionsAreaImpl(this) } private var messageBus: MessageBusImpl? = null private var handlingInitComponentError = false @Volatile private var isServicePreloadingCancelled = false private var instantiatedComponentCount = 0 private var componentConfigCount = -1 @Suppress("LeakingThis") internal val serviceParentDisposable = Disposer.newDisposable("services of ${javaClass.name}@${System.identityHashCode(this)}") protected open val isLightServiceSupported = parent?.parent == null protected open val isMessageBusSupported = parent?.parent == null protected open val isComponentSupported = true protected open val isExtensionSupported = true @Volatile internal var componentContainerIsReadonly: String? = null override val componentStore: IComponentStore get() = getService(IComponentStore::class.java)!! init { if (setExtensionsRootArea) { Extensions.setRootArea(_extensionArea) } } @Deprecated("Use ComponentManager API", level = DeprecationLevel.ERROR) final override fun getPicoContainer(): PicoContainer { checkState() return this } private fun registerAdapter(componentAdapter: ComponentAdapter, pluginDescriptor: PluginDescriptor?) { if (componentKeyToAdapter.putIfAbsent(componentAdapter.componentKey, componentAdapter) != null) { val error = "Key ${componentAdapter.componentKey} duplicated" if (pluginDescriptor == null) { throw PluginException.createByClass(error, null, componentAdapter.javaClass) } else { throw PluginException(error, null, pluginDescriptor.pluginId) } } } @Internal fun forbidGettingServices(reason: String): AccessToken { val token = object : AccessToken() { override fun finish() { componentContainerIsReadonly = null } } componentContainerIsReadonly = reason return token } private fun checkState() { if (containerState.get() == ContainerState.DISPOSE_COMPLETED) { ProgressManager.checkCanceled() throw AlreadyDisposedException("Already disposed: $this") } } final override fun getMessageBus(): MessageBus { if (containerState.get() >= ContainerState.DISPOSE_IN_PROGRESS) { ProgressManager.checkCanceled() throw AlreadyDisposedException("Already disposed: $this") } val messageBus = messageBus if (messageBus == null || !isMessageBusSupported) { LOG.error("Do not use module level message bus") return getOrCreateMessageBusUnderLock() } return messageBus } fun getDeprecatedModuleLevelMessageBus(): MessageBus { if (containerState.get() >= ContainerState.DISPOSE_IN_PROGRESS) { ProgressManager.checkCanceled() throw AlreadyDisposedException("Already disposed: $this") } return messageBus ?: getOrCreateMessageBusUnderLock() } protected open fun setProgressDuringInit(indicator: ProgressIndicator) { indicator.fraction = getPercentageOfComponentsLoaded() } @Internal fun getPercentageOfComponentsLoaded(): Double { return instantiatedComponentCount.toDouble() / componentConfigCount } override fun getExtensionArea(): ExtensionsAreaImpl { if (!isExtensionSupported) { error("Extensions aren't supported") } return _extensionArea } @Internal open fun registerComponents(plugins: List<IdeaPluginDescriptorImpl>, app: Application?, precomputedExtensionModel: PrecomputedExtensionModel?, listenerCallbacks: List<Runnable>?) { val activityNamePrefix = activityNamePrefix() var newComponentConfigCount = 0 var map: ConcurrentMap<String, MutableList<ListenerDescriptor>>? = null val isHeadless = app == null || app.isHeadlessEnvironment val isUnitTestMode = app?.isUnitTestMode ?: false var activity = activityNamePrefix?.let { startActivity("${it}service and ep registration") } // register services before registering extensions because plugins can access services in their // extensions which can be invoked right away if the plugin is loaded dynamically val extensionPoints = if (precomputedExtensionModel == null) HashMap(extensionArea.extensionPoints) else null for (mainPlugin in plugins) { executeRegisterTask(mainPlugin) { pluginDescriptor -> val containerDescriptor = getContainerDescriptor(pluginDescriptor) registerServices(containerDescriptor.services, pluginDescriptor) } executeRegisterTask(mainPlugin) { pluginDescriptor -> val containerDescriptor = getContainerDescriptor(pluginDescriptor) newComponentConfigCount += registerComponents(pluginDescriptor, containerDescriptor, isHeadless) } executeRegisterTask(mainPlugin) { pluginDescriptor -> val containerDescriptor = getContainerDescriptor(pluginDescriptor) containerDescriptor.listeners?.let { listeners -> var m = map if (m == null) { m = ConcurrentHashMap() map = m } for (listener in listeners) { if ((isUnitTestMode && !listener.activeInTestMode) || (isHeadless && !listener.activeInHeadlessMode)) { continue } if (listener.os != null && !isSuitableForOs(listener.os)) { continue } listener.pluginDescriptor = pluginDescriptor m.computeIfAbsent(listener.topicClassName) { ArrayList() }.add(listener) } } } if (extensionPoints != null) { executeRegisterTask(mainPlugin) { pluginDescriptor -> val containerDescriptor = getContainerDescriptor(pluginDescriptor) containerDescriptor.extensionPoints?.let { ExtensionsAreaImpl.createExtensionPoints(it, this, extensionPoints, pluginDescriptor) } } } } if (activity != null) { activity = activity.endAndStart("${activityNamePrefix}extension registration") } if (precomputedExtensionModel == null) { val immutableExtensionPoints = if (extensionPoints!!.isEmpty()) Collections.emptyMap() else java.util.Map.copyOf(extensionPoints) extensionArea.setPoints(immutableExtensionPoints) for (mainPlugin in plugins) { executeRegisterTask(mainPlugin) { pluginDescriptor -> val containerDescriptor = getContainerDescriptor(pluginDescriptor) pluginDescriptor.registerExtensions(immutableExtensionPoints, containerDescriptor, listenerCallbacks) } } } else { registerExtensionPointsAndExtensionByPrecomputedModel(precomputedExtensionModel, listenerCallbacks) } activity?.end() if (componentConfigCount == -1) { componentConfigCount = newComponentConfigCount } // app - phase must be set before getMessageBus() if (parent == null && !LoadingState.COMPONENTS_REGISTERED.isOccurred /* loading plugin on the fly */) { StartUpMeasurer.setCurrentState(LoadingState.COMPONENTS_REGISTERED) } // ensure that messageBus is created, regardless of lazy listeners map state if (isMessageBusSupported) { val messageBus = getOrCreateMessageBusUnderLock() map?.let { (messageBus as MessageBusEx).setLazyListeners(it) } } } private fun registerExtensionPointsAndExtensionByPrecomputedModel(precomputedExtensionModel: PrecomputedExtensionModel, listenerCallbacks: List<Runnable>?) { assert(extensionArea.extensionPoints.isEmpty()) val n = precomputedExtensionModel.pluginDescriptors.size if (n == 0) { return } val result = HashMap<String, ExtensionPointImpl<*>>(precomputedExtensionModel.extensionPointTotalCount) for (i in 0 until n) { ExtensionsAreaImpl.createExtensionPoints(precomputedExtensionModel.extensionPoints[i], this, result, precomputedExtensionModel.pluginDescriptors[i]) } val immutableExtensionPoints = java.util.Map.copyOf(result) extensionArea.setPoints(immutableExtensionPoints) for ((name, pairs) in precomputedExtensionModel.nameToExtensions) { val point = immutableExtensionPoints.get(name) ?: continue for ((pluginDescriptor, list) in pairs) { if (!list.isEmpty()) { point.registerExtensions(list, pluginDescriptor, listenerCallbacks) } } } } private fun registerComponents(pluginDescriptor: IdeaPluginDescriptor, containerDescriptor: ContainerDescriptor, headless: Boolean): Int { var count = 0 for (descriptor in (containerDescriptor.components ?: return 0)) { var implementationClass = descriptor.implementationClass if (headless && descriptor.headlessImplementationClass != null) { if (descriptor.headlessImplementationClass.isEmpty()) { continue } implementationClass = descriptor.headlessImplementationClass } if (descriptor.os != null && !isSuitableForOs(descriptor.os)) { continue } if (!isComponentSuitable(descriptor)) { continue } try { registerComponent(interfaceClassName = descriptor.interfaceClass ?: descriptor.implementationClass!!, implementationClassName = implementationClass, config = descriptor, pluginDescriptor = pluginDescriptor) count++ } catch (e: Throwable) { handleInitComponentError(e, descriptor.implementationClass ?: descriptor.interfaceClass, pluginDescriptor.pluginId) } } return count } protected fun createComponents(indicator: ProgressIndicator?) { LOG.assertTrue(containerState.get() == ContainerState.PRE_INIT) if (indicator != null) { indicator.isIndeterminate = false } val activity = when (val activityNamePrefix = activityNamePrefix()) { null -> null else -> startActivity("$activityNamePrefix${StartUpMeasurer.Activities.CREATE_COMPONENTS_SUFFIX}") } for (componentAdapter in componentAdapters.getImmutableSet()) { if (componentAdapter is MyComponentAdapter) { componentAdapter.getInstance<Any>(this, keyClass = null, indicator = indicator) } } activity?.end() LOG.assertTrue(containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.COMPONENT_CREATED)) } @TestOnly fun registerComponentImplementation(componentKey: Class<*>, componentImplementation: Class<*>, shouldBeRegistered: Boolean) { checkState() var adapter = unregisterComponent(componentKey) as MyComponentAdapter? if (shouldBeRegistered) { LOG.assertTrue(adapter != null) } val pluginDescriptor = DefaultPluginDescriptor("test registerComponentImplementation") adapter = MyComponentAdapter(componentKey, componentImplementation.name, pluginDescriptor, this, componentImplementation) registerAdapter(adapter, adapter.pluginDescriptor) componentAdapters.add(adapter) } @TestOnly fun <T : Any> replaceComponentInstance(componentKey: Class<T>, componentImplementation: T, parentDisposable: Disposable?) { checkState() val adapter = getComponentAdapter(componentKey) as MyComponentAdapter adapter.replaceInstance(componentKey, componentImplementation, parentDisposable, null) } private fun registerComponent(interfaceClassName: String, implementationClassName: String?, config: ComponentConfig, pluginDescriptor: PluginDescriptor) { val interfaceClass = pluginDescriptor.pluginClassLoader.loadClass(interfaceClassName) val options = config.options if (config.overrides) { unregisterComponent(interfaceClass) ?: throw PluginException("$config does not override anything", pluginDescriptor.pluginId) } // implementationClass == null means we want to unregister this component if (implementationClassName == null) { return } if (options != null && java.lang.Boolean.parseBoolean(options.get("workspace")) && !badWorkspaceComponents.contains(implementationClassName)) { LOG.error("workspace option is deprecated (implementationClass=$implementationClassName)") } val adapter = MyComponentAdapter(interfaceClass, implementationClassName, pluginDescriptor, this, null) registerAdapter(adapter, adapter.pluginDescriptor) componentAdapters.add(adapter) } open fun getApplication(): Application? { return if (parent == null || this is Application) this as Application else parent.getApplication() } protected fun registerServices(services: List<ServiceDescriptor>, pluginDescriptor: IdeaPluginDescriptor) { checkState() val app = getApplication()!! for (descriptor in services) { if (!isServiceSuitable(descriptor) || descriptor.os != null && !isSuitableForOs(descriptor.os)) { continue } // Allow to re-define service implementations in plugins. // Empty serviceImplementation means we want to unregister service. val key = descriptor.getInterface() if (descriptor.overrides && componentKeyToAdapter.remove(key) == null) { throw PluginException("Service $key doesn't override anything", pluginDescriptor.pluginId) } // empty serviceImplementation means we want to unregister service val implementation = when { descriptor.testServiceImplementation != null && app.isUnitTestMode -> descriptor.testServiceImplementation descriptor.headlessImplementation != null && app.isHeadlessEnvironment -> descriptor.headlessImplementation else -> descriptor.serviceImplementation } if (implementation != null) { val componentAdapter = ServiceComponentAdapter(descriptor, pluginDescriptor, this) if (componentKeyToAdapter.putIfAbsent(key, componentAdapter) != null) { throw PluginException("Key $key duplicated", pluginDescriptor.pluginId) } } } } internal fun handleInitComponentError(error: Throwable, componentClassName: String, pluginId: PluginId) { if (handlingInitComponentError) { return } handlingInitComponentError = true try { // not logged but thrown PluginException means some fatal error if (error is StartupAbortedException || error is ProcessCanceledException || error is PluginException) { throw error } var effectivePluginId = pluginId if (effectivePluginId == PluginManagerCore.CORE_ID) { effectivePluginId = PluginManagerCore.getPluginOrPlatformByClassName(componentClassName) ?: PluginManagerCore.CORE_ID } throw PluginException("Fatal error initializing '$componentClassName'", error, effectivePluginId) } finally { handlingInitComponentError = false } } internal fun initializeComponent(component: Any, serviceDescriptor: ServiceDescriptor?, pluginId: PluginId?) { if (serviceDescriptor == null || !isPreInitialized(component)) { LoadingState.CONFIGURATION_STORE_INITIALIZED.checkOccurred() componentStore.initComponent(component, serviceDescriptor, pluginId) } } protected open fun isPreInitialized(component: Any): Boolean { return component is PathMacroManager || component is IComponentStore || component is MessageBusFactory } protected abstract fun getContainerDescriptor(pluginDescriptor: IdeaPluginDescriptorImpl): ContainerDescriptor final override fun <T : Any> getComponent(interfaceClass: Class<T>): T? { assertComponentsSupported() checkState() val adapter = getComponentAdapter(interfaceClass) if (adapter == null) { checkCanceledIfNotInClassInit() if (containerState.get() == ContainerState.DISPOSE_COMPLETED) { throwAlreadyDisposedError(interfaceClass.name, this, ProgressManager.getGlobalProgressIndicator()) } return null } if (adapter is ServiceComponentAdapter) { LOG.error("$interfaceClass it is a service, use getService instead of getComponent") } if (adapter is BaseComponentAdapter) { if (parent != null && adapter.componentManager !== this) { LOG.error("getComponent must be called on appropriate container (current: $this, expected: ${adapter.componentManager})") } val indicator = ProgressManager.getGlobalProgressIndicator() if (containerState.get() == ContainerState.DISPOSE_COMPLETED) { adapter.throwAlreadyDisposedError(this, indicator) } return adapter.getInstance(adapter.componentManager, interfaceClass, indicator = indicator) } else { @Suppress("UNCHECKED_CAST") return adapter.getComponentInstance(this) as T } } override fun <T : Any> getService(serviceClass: Class<T>): T? { // `computeIfAbsent` cannot be used because of recursive update var result = serviceInstanceHotCache.get(serviceClass) if (result == null) { result = doGetService(serviceClass, true) ?: return null serviceInstanceHotCache.putIfAbsent(serviceClass, result) } @Suppress("UNCHECKED_CAST") return result as T? } @Suppress("UNCHECKED_CAST") override fun <T : Any> getServiceIfCreated(serviceClass: Class<T>): T? = serviceInstanceHotCache.get(serviceClass) as T? protected open fun <T : Any> doGetService(serviceClass: Class<T>, createIfNeeded: Boolean): T? { val key = serviceClass.name val adapter = componentKeyToAdapter.get(key) if (adapter is ServiceComponentAdapter) { if (createIfNeeded && containerState.get() == ContainerState.DISPOSE_COMPLETED) { throwAlreadyDisposedError(adapter.toString(), this, ProgressIndicatorProvider.getGlobalProgressIndicator()) } return adapter.getInstance(this, serviceClass, createIfNeeded) } else if (adapter is LightServiceComponentAdapter) { if (createIfNeeded && containerState.get() == ContainerState.DISPOSE_COMPLETED) { throwAlreadyDisposedError(adapter.toString(), this, ProgressIndicatorProvider.getGlobalProgressIndicator()) } @Suppress("UNCHECKED_CAST") return adapter.getComponentInstance(null) as T } if (isLightServiceSupported && isLightService(serviceClass)) { return if (createIfNeeded) getOrCreateLightService(serviceClass) else null } checkCanceledIfNotInClassInit() // if the container is fully disposed, all adapters may be removed if (containerState.get() == ContainerState.DISPOSE_COMPLETED) { if (!createIfNeeded) { return null } throwAlreadyDisposedError(serviceClass.name, this, ProgressIndicatorProvider.getGlobalProgressIndicator()) } if (parent != null) { val result = parent.doGetService(serviceClass, createIfNeeded) if (result != null) { LOG.error("$key is registered as application service, but requested as project one") return result } } if (isLightServiceSupported && !serviceClass.isInterface && !Modifier.isFinal(serviceClass.modifiers) && serviceClass.isAnnotationPresent(Service::class.java)) { throw PluginException.createByClass("Light service class $serviceClass must be final", null, serviceClass) } val result = getComponent(serviceClass) ?: return null PluginException.logPluginError(LOG, "$key requested as a service, but it is a component - " + "convert it to a service or change call to " + if (parent == null) "ApplicationManager.getApplication().getComponent()" else "project.getComponent()", null, serviceClass) return result } private fun <T : Any> getOrCreateLightService(serviceClass: Class<T>): T { checkThatCreatingOfLightServiceIsAllowed(serviceClass) synchronized(serviceClass) { val adapter = componentKeyToAdapter.get(serviceClass.name) as LightServiceComponentAdapter? if (adapter != null) { @Suppress("UNCHECKED_CAST") return adapter.getComponentInstance(null) as T } LoadingState.COMPONENTS_REGISTERED.checkOccurred() var result: T? = null if (ProgressIndicatorProvider.getGlobalProgressIndicator() == null) { result = createLightService(serviceClass) } else { ProgressManager.getInstance().executeNonCancelableSection { result = createLightService(serviceClass) } } result!!.let { registerAdapter(LightServiceComponentAdapter(it), pluginDescriptor = null) return it } } } private fun checkThatCreatingOfLightServiceIsAllowed(serviceClass: Class<*>) { if (isDisposed) { throwAlreadyDisposedError("light service ${serviceClass.name}", this, ProgressIndicatorProvider.getGlobalProgressIndicator()) } // assertion only for non-platform plugins val classLoader = serviceClass.classLoader if (classLoader is PluginAwareClassLoader && !isGettingServiceAllowedDuringPluginUnloading(classLoader.pluginDescriptor)) { componentContainerIsReadonly?.let { val error = AlreadyDisposedException( "Cannot create light service ${serviceClass.name} because container in read-only mode (reason=$it, container=$this" ) throw if (ProgressIndicatorProvider.getGlobalProgressIndicator() == null) error else ProcessCanceledException(error) } } } @Synchronized private fun getOrCreateMessageBusUnderLock(): MessageBus { var messageBus = this.messageBus if (messageBus != null) { return messageBus } messageBus = getApplication()!!.getService(MessageBusFactory::class.java).createMessageBus(this, parent?.messageBus) as MessageBusImpl if (StartUpMeasurer.isMeasuringPluginStartupCosts()) { messageBus.setMessageDeliveryListener { topic, messageName, handler, duration -> if (!StartUpMeasurer.isMeasuringPluginStartupCosts()) { messageBus.setMessageDeliveryListener(null) return@setMessageDeliveryListener } logMessageBusDelivery(topic, messageName, handler, duration) } } registerServiceInstance(MessageBus::class.java, messageBus, fakeCorePluginDescriptor) this.messageBus = messageBus return messageBus } protected open fun logMessageBusDelivery(topic: Topic<*>, messageName: String, handler: Any, duration: Long) { val loader = handler.javaClass.classLoader val pluginId = if (loader is PluginAwareClassLoader) loader.pluginId.idString else PluginManagerCore.CORE_ID.idString StartUpMeasurer.addPluginCost(pluginId, "MessageBus", duration) } /** * Use only if approved by core team. */ @Internal fun registerComponent(key: Class<*>, implementation: Class<*>, pluginDescriptor: PluginDescriptor, override: Boolean) { assertComponentsSupported() checkState() val adapter = MyComponentAdapter(key, implementation.name, pluginDescriptor, this, implementation) if (override) { overrideAdapter(adapter, pluginDescriptor) componentAdapters.replace(adapter) } else { registerAdapter(adapter, pluginDescriptor) componentAdapters.add(adapter) } } private fun overrideAdapter(adapter: ComponentAdapter, pluginDescriptor: PluginDescriptor) { val componentKey = adapter.componentKey if (componentKeyToAdapter.put(componentKey, adapter) == null) { componentKeyToAdapter.remove(componentKey) throw PluginException("Key $componentKey doesn't override anything", pluginDescriptor.pluginId) } } /** * Use only if approved by core team. */ @Internal fun registerService(serviceInterface: Class<*>, implementation: Class<*>, pluginDescriptor: PluginDescriptor, override: Boolean, preloadMode: PreloadMode = PreloadMode.FALSE) { checkState() val descriptor = ServiceDescriptor(serviceInterface.name, implementation.name, null, null, false, null, preloadMode, null, null) val adapter = ServiceComponentAdapter(descriptor, pluginDescriptor, this, implementation) if (override) { overrideAdapter(adapter, pluginDescriptor) } else { registerAdapter(adapter, pluginDescriptor) } serviceInstanceHotCache.remove(serviceInterface) } /** * Use only if approved by core team. */ @Internal fun <T : Any> registerServiceInstance(serviceInterface: Class<T>, instance: T, pluginDescriptor: PluginDescriptor) { val serviceKey = serviceInterface.name checkState() val descriptor = ServiceDescriptor(serviceKey, instance.javaClass.name, null, null, false, null, PreloadMode.FALSE, null, null) componentKeyToAdapter.put(serviceKey, ServiceComponentAdapter(descriptor, pluginDescriptor, this, instance.javaClass, instance)) serviceInstanceHotCache.put(serviceInterface, instance) } @TestOnly @Internal fun <T : Any> replaceServiceInstance(serviceInterface: Class<T>, instance: T, parentDisposable: Disposable) { checkState() if (isLightService(serviceInterface)) { val adapter = LightServiceComponentAdapter(instance) val key = adapter.componentKey componentKeyToAdapter.put(key, adapter) Disposer.register(parentDisposable, Disposable { componentKeyToAdapter.remove(key) serviceInstanceHotCache.remove(serviceInterface) }) serviceInstanceHotCache.put(serviceInterface, instance) } else { val adapter = componentKeyToAdapter.get(serviceInterface.name) as ServiceComponentAdapter adapter.replaceInstance(serviceInterface, instance, parentDisposable, serviceInstanceHotCache) } } @Internal fun <T : Any> replaceRegularServiceInstance(serviceInterface: Class<T>, instance: T) { checkState() val adapter = componentKeyToAdapter.get(serviceInterface.name) as ServiceComponentAdapter (adapter.replaceInstance(serviceInterface, instance, serviceParentDisposable, serviceInstanceHotCache) as? Disposable)?.let { Disposer.dispose(it) } serviceInstanceHotCache.put(serviceInterface, instance) } private fun <T : Any> createLightService(serviceClass: Class<T>): T { val startTime = StartUpMeasurer.getCurrentTime() val pluginId = (serviceClass.classLoader as? PluginAwareClassLoader)?.pluginId ?: PluginManagerCore.CORE_ID val result = instantiateClass(serviceClass, pluginId) if (result is Disposable) { Disposer.register(serviceParentDisposable, result) } initializeComponent(result, null, pluginId) StartUpMeasurer.addCompletedActivity(startTime, serviceClass, getActivityCategory(isExtension = false), pluginId.idString) return result } final override fun <T : Any> loadClass(className: String, pluginDescriptor: PluginDescriptor): Class<T> { @Suppress("UNCHECKED_CAST") return doLoadClass(className, pluginDescriptor) as Class<T> } final override fun <T : Any> instantiateClass(aClass: Class<T>, pluginId: PluginId): T { checkCanceledIfNotInClassInit() try { if (parent == null) { @Suppress("UNCHECKED_CAST") return MethodHandles.privateLookupIn(aClass, methodLookup).findConstructor(aClass, emptyConstructorMethodType).invoke() as T } else { val constructors: Array<Constructor<*>> = aClass.declaredConstructors var constructor = if (constructors.size > 1) { // see ConfigurableEP - prefer constructor that accepts our instance constructors.firstOrNull { it.parameterCount == 1 && it.parameterTypes[0].isAssignableFrom(javaClass) } } else { null } if (constructor == null) { constructors.sortBy { it.parameterCount } constructor = constructors.first() } constructor.isAccessible = true @Suppress("UNCHECKED_CAST") if (constructor.parameterCount == 1) { return constructor.newInstance(getActualContainerInstance()) as T } else { @Suppress("UNCHECKED_CAST") return MethodHandles.privateLookupIn(aClass, methodLookup).unreflectConstructor(constructor).invoke() as T } } } catch (e: Throwable) { if (e is InvocationTargetException) { val targetException = e.targetException if (targetException is ControlFlowException) { throw targetException } } else if (e is ControlFlowException) { throw e } val message = "Cannot create class ${aClass.name} (classloader=${aClass.classLoader})" throw PluginException(message, e, pluginId) } } protected open fun getActualContainerInstance(): ComponentManager = this final override fun <T : Any> instantiateClassWithConstructorInjection(aClass: Class<T>, key: Any, pluginId: PluginId): T { return instantiateUsingPicoContainer(aClass, key, pluginId, this, constructorParameterResolver) } internal open val isGetComponentAdapterOfTypeCheckEnabled: Boolean get() = true final override fun <T : Any> instantiateClass(className: String, pluginDescriptor: PluginDescriptor): T { val pluginId = pluginDescriptor.pluginId try { @Suppress("UNCHECKED_CAST") return instantiateClass(doLoadClass(className, pluginDescriptor) as Class<T>, pluginId) } catch (e: Throwable) { when { e is PluginException || e is ExtensionNotApplicableException || e is ProcessCanceledException -> throw e e.cause is NoSuchMethodException || e.cause is IllegalArgumentException -> { throw PluginException("Class constructor must not have parameters: $className", e, pluginId) } else -> throw PluginException(e, pluginDescriptor.pluginId) } } } final override fun createListener(descriptor: ListenerDescriptor): Any { val pluginDescriptor = descriptor.pluginDescriptor val aClass = try { doLoadClass(descriptor.listenerClassName, pluginDescriptor) } catch (e: Throwable) { throw PluginException("Cannot create listener ${descriptor.listenerClassName}", e, pluginDescriptor.pluginId) } return instantiateClass(aClass, pluginDescriptor.pluginId) } final override fun logError(error: Throwable, pluginId: PluginId) { if (error is ProcessCanceledException || error is ExtensionNotApplicableException) { throw error } LOG.error(createPluginExceptionIfNeeded(error, pluginId)) } final override fun createError(error: Throwable, pluginId: PluginId): RuntimeException { return when (val effectiveError: Throwable = if (error is InvocationTargetException) error.targetException else error) { is ProcessCanceledException, is ExtensionNotApplicableException, is PluginException -> effectiveError as RuntimeException else -> PluginException(effectiveError, pluginId) } } final override fun createError(message: String, pluginId: PluginId) = PluginException(message, pluginId) final override fun createError(message: String, error: Throwable?, pluginId: PluginId, attachments: MutableMap<String, String>?): RuntimeException { return PluginException(message, error, pluginId, attachments?.map { Attachment(it.key, it.value) } ?: emptyList()) } @Internal open fun unloadServices(services: List<ServiceDescriptor>, pluginId: PluginId) { checkState() if (!services.isEmpty()) { val store = componentStore for (service in services) { val adapter = (componentKeyToAdapter.remove(service.`interface`) ?: continue) as ServiceComponentAdapter val instance = adapter.getInitializedInstance() ?: continue if (instance is Disposable) { Disposer.dispose(instance) } store.unloadComponent(instance) } } if (isLightServiceSupported) { val store = componentStore val iterator = componentKeyToAdapter.values.iterator() while (iterator.hasNext()) { val adapter = iterator.next() as? LightServiceComponentAdapter ?: continue val instance = adapter.getComponentInstance(null) if ((instance.javaClass.classLoader as? PluginAwareClassLoader)?.pluginId == pluginId) { if (instance is Disposable) { Disposer.dispose(instance) } store.unloadComponent(instance) iterator.remove() } } } serviceInstanceHotCache.clear() } @Internal open fun activityNamePrefix(): String? = null @ApiStatus.Internal open fun preloadServices(plugins: List<IdeaPluginDescriptorImpl>, activityPrefix: String, onlyIfAwait: Boolean = false): Pair<CompletableFuture<Void?>, CompletableFuture<Void?>> { val asyncPreloadedServices = mutableListOf<ForkJoinTask<*>>() val syncPreloadedServices = mutableListOf<ForkJoinTask<*>>() for (plugin in plugins) { serviceLoop@ for (service in getContainerDescriptor(plugin).services) { if (!isServiceSuitable(service) || service.os != null && !isSuitableForOs(service.os)) { continue@serviceLoop } val list: MutableList<ForkJoinTask<*>> = when (service.preload) { PreloadMode.TRUE -> { if (onlyIfAwait) { continue@serviceLoop } else { asyncPreloadedServices } } PreloadMode.NOT_HEADLESS -> { if (onlyIfAwait || getApplication()!!.isHeadlessEnvironment) { continue@serviceLoop } else { asyncPreloadedServices } } PreloadMode.NOT_LIGHT_EDIT -> { if (onlyIfAwait || Main.isLightEdit()) { continue@serviceLoop } else { asyncPreloadedServices } } PreloadMode.AWAIT -> syncPreloadedServices PreloadMode.FALSE -> continue@serviceLoop else -> throw IllegalStateException("Unknown preload mode ${service.preload}") } list.add(ForkJoinTask.adapt task@{ if (isServicePreloadingCancelled || isDisposed) { return@task } try { instantiateService(service) } catch (ignore: AlreadyDisposedException) { } catch (e: StartupAbortedException) { isServicePreloadingCancelled = true throw e } }) } } return Pair( CompletableFuture.runAsync({ runActivity("${activityPrefix}service async preloading") { ForkJoinTask.invokeAll(asyncPreloadedServices) } }, ForkJoinPool.commonPool()), CompletableFuture.runAsync({ runActivity("${activityPrefix}service sync preloading") { ForkJoinTask.invokeAll(syncPreloadedServices) } }, ForkJoinPool.commonPool()) ) } protected open fun instantiateService(service: ServiceDescriptor) { val adapter = componentKeyToAdapter.get(service.getInterface()) as ServiceComponentAdapter? ?: return val instance = adapter.getInstance<Any>(this, null) if (instance != null) { val implClass = instance.javaClass if (Modifier.isFinal(implClass.modifiers)) { serviceInstanceHotCache.putIfAbsent(implClass, instance) } } } override fun isDisposed(): Boolean { return containerState.get() >= ContainerState.DISPOSE_IN_PROGRESS } final override fun beforeTreeDispose() { stopServicePreloading() ApplicationManager.getApplication().assertIsWriteThread() if (!(containerState.compareAndSet(ContainerState.COMPONENT_CREATED, ContainerState.DISPOSE_IN_PROGRESS) || containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.DISPOSE_IN_PROGRESS))) { // disposed in a recommended way using ProjectManager return } // disposed directly using Disposer.dispose() // we don't care that state DISPOSE_IN_PROGRESS is already set, // and exceptions because of that possible - use ProjectManager to close and dispose project. startDispose() } @Internal fun startDispose() { stopServicePreloading() Disposer.disposeChildren(this, null) val messageBus = messageBus // There is a chance that someone will try to connect to the message bus and will get NPE because of disposed connection disposable, // because the container state is not yet set to DISPOSE_IN_PROGRESS. // So, 1) dispose connection children 2) set state DISPOSE_IN_PROGRESS 3) dispose connection messageBus?.disposeConnectionChildren() containerState.set(ContainerState.DISPOSE_IN_PROGRESS) messageBus?.disposeConnection() } override fun dispose() { if (!containerState.compareAndSet(ContainerState.DISPOSE_IN_PROGRESS, ContainerState.DISPOSED)) { throw IllegalStateException("Expected current state is DISPOSE_IN_PROGRESS, but actual state is ${containerState.get()} ($this)") } // dispose components and services Disposer.dispose(serviceParentDisposable) // release references to the service instances componentKeyToAdapter.clear() componentAdapters.clear() serviceInstanceHotCache.clear() val messageBus = messageBus if (messageBus != null) { // Must be after disposing of serviceParentDisposable, because message bus disposes child buses, so, we must dispose all services first. // For example, service ModuleManagerImpl disposes modules; each module, in turn, disposes module's message bus (child bus of application). Disposer.dispose(messageBus) this.messageBus = null } if (!containerState.compareAndSet(ContainerState.DISPOSED, ContainerState.DISPOSE_COMPLETED)) { throw IllegalStateException("Expected current state is DISPOSED, but actual state is ${containerState.get()} ($this)") } componentConfigCount = -1 } @Internal fun stopServicePreloading() { isServicePreloadingCancelled = true } @Suppress("DEPRECATION") final override fun getComponent(name: String): BaseComponent? { checkState() for (componentAdapter in componentKeyToAdapter.values) { if (componentAdapter is MyComponentAdapter) { val instance = componentAdapter.getInitializedInstance() if (instance is BaseComponent && name == instance.componentName) { return instance } } } return null } internal fun componentCreated(indicator: ProgressIndicator?) { instantiatedComponentCount++ if (indicator != null) { indicator.checkCanceled() setProgressDuringInit(indicator) } } final override fun <T : Any> getServiceByClassName(serviceClassName: String): T? { checkState() val adapter = componentKeyToAdapter.get(serviceClassName) as ServiceComponentAdapter? return adapter?.getInstance(this, keyClass = null) } @ApiStatus.Internal open fun isServiceSuitable(descriptor: ServiceDescriptor): Boolean { return descriptor.client == null } protected open fun isComponentSuitable(componentConfig: ComponentConfig): Boolean { val options = componentConfig.options ?: return true return !java.lang.Boolean.parseBoolean(options.get("internal")) || ApplicationManager.getApplication().isInternal } final override fun getDisposed(): Condition<*> = Condition<Any?> { isDisposed } @ApiStatus.Internal fun processInitializedComponentsAndServices(processor: (Any) -> Unit) { for (adapter in componentKeyToAdapter.values) { if (adapter is BaseComponentAdapter) { processor(adapter.getInitializedInstance() ?: continue) } else if (adapter is LightServiceComponentAdapter) { processor(adapter.getComponentInstance(null)) } } } @ApiStatus.Internal fun processAllImplementationClasses(processor: (componentClass: Class<*>, plugin: PluginDescriptor?) -> Unit) { for (adapter in componentKeyToAdapter.values) { if (adapter is ServiceComponentAdapter) { val aClass = try { adapter.getImplementationClass() } catch (e: Throwable) { // well, the component is registered, but the required jar is not added to the classpath (community edition or junior IDE) LOG.warn(e) continue } processor(aClass, adapter.pluginDescriptor) } else { val pluginDescriptor = if (adapter is BaseComponentAdapter) adapter.pluginDescriptor else null if (pluginDescriptor != null) { val aClass = try { adapter.componentImplementation } catch (e: Throwable) { LOG.warn(e) continue } processor(aClass, pluginDescriptor) } } } } final override fun getComponentAdapter(componentKey: Any): ComponentAdapter? { assertComponentsSupported() val adapter = getFromCache(componentKey) return if (adapter == null && parent != null) parent.getComponentAdapter(componentKey) else adapter } private fun getFromCache(componentKey: Any): ComponentAdapter? { val adapter = componentKeyToAdapter.get(componentKey) if (adapter == null) { return if (componentKey is Class<*>) componentKeyToAdapter.get(componentKey.name) else null } else { return adapter } } final fun unregisterComponent(componentKey: Any): ComponentAdapter? { assertComponentsSupported() val adapter = componentKeyToAdapter.remove(componentKey) ?: return null componentAdapters.remove(adapter) return adapter } final override fun getComponentInstance(componentKey: Any): Any? { assertComponentsSupported() val adapter = getFromCache(componentKey) if (adapter == null) { return parent?.getComponentInstance(componentKey) } else { return adapter.getComponentInstance(this) } } final override fun getComponentInstanceOfType(componentType: Class<*>): Any? { throw UnsupportedOperationException("Do not use getComponentInstanceOfType()") } final fun registerComponentInstance(componentKey: Any, componentInstance: Any): ComponentAdapter { assertComponentsSupported() val componentAdapter = object : ComponentAdapter { override fun getComponentInstance(container: PicoContainer) = componentInstance override fun getComponentKey() = componentKey override fun getComponentImplementation() = componentInstance.javaClass override fun toString() = "${javaClass.name}[$componentKey]" } if (componentKeyToAdapter.putIfAbsent(componentAdapter.componentKey, componentAdapter) != null) { throw IllegalStateException("Key ${componentAdapter.componentKey} duplicated") } componentAdapters.add(componentAdapter) return componentAdapter } private fun assertComponentsSupported() { if (!isComponentSupported) { error("components aren't support") } } // project level extension requires Project as constructor argument, so, for now, constructor injection is disabled only for app level final override fun isInjectionForExtensionSupported() = parent != null internal fun getComponentAdapterOfType(componentType: Class<*>): ComponentAdapter? { componentKeyToAdapter.get(componentType)?.let { return it } for (adapter in componentAdapters.getImmutableSet()) { val descendant = adapter.componentImplementation if (componentType === descendant || componentType.isAssignableFrom(descendant)) { return adapter } } return null } final override fun <T : Any> processInitializedComponents(aClass: Class<T>, processor: (T, PluginDescriptor) -> Unit) { // We must use instances only from our adapter (could be service or something else). // unsafeGetAdapters should be not used here as ProjectManagerImpl uses it to call projectOpened for (adapter in componentAdapters.getImmutableSet()) { if (adapter is MyComponentAdapter) { val component = adapter.getInitializedInstance() if (component != null && aClass.isAssignableFrom(component.javaClass)) { @Suppress("UNCHECKED_CAST") processor(component as T, adapter.pluginDescriptor) } } } } final override fun getActivityCategory(isExtension: Boolean): ActivityCategory { return when { parent == null -> if (isExtension) ActivityCategory.APP_EXTENSION else ActivityCategory.APP_SERVICE parent.parent == null -> if (isExtension) ActivityCategory.PROJECT_EXTENSION else ActivityCategory.PROJECT_SERVICE else -> if (isExtension) ActivityCategory.MODULE_EXTENSION else ActivityCategory.MODULE_SERVICE } } final override fun hasComponent(componentKey: Class<*>): Boolean { val adapter = componentKeyToAdapter.get(componentKey) ?: componentKeyToAdapter.get(componentKey.name) return adapter != null || (parent != null && parent.hasComponent(componentKey)) } @Deprecated(message = "Use extensions", level = DeprecationLevel.ERROR) final override fun <T : Any> getComponents(baseClass: Class<T>): Array<T> { checkState() val result = mutableListOf<T>() // we must use instances only from our adapter (could be service or something else) for (componentAdapter in componentAdapters.getImmutableSet()) { if (componentAdapter is MyComponentAdapter) { val implementationClass = componentAdapter.getImplementationClass() if (baseClass === implementationClass || baseClass.isAssignableFrom(implementationClass)) { val instance = componentAdapter.getInstance<T>(componentManager = this, keyClass = null, createIfNeeded = false) if (instance != null) { result.add(instance) } } } } @Suppress("DEPRECATION") return ArrayUtil.toObjectArray(result, baseClass) } final override fun isSuitableForOs(os: ExtensionDescriptor.Os): Boolean { return when (os) { ExtensionDescriptor.Os.mac -> SystemInfoRt.isMac ExtensionDescriptor.Os.linux -> SystemInfoRt.isLinux ExtensionDescriptor.Os.windows -> SystemInfoRt.isWindows ExtensionDescriptor.Os.unix -> SystemInfoRt.isUnix ExtensionDescriptor.Os.freebsd -> SystemInfoRt.isFreeBSD else -> throw IllegalArgumentException("Unknown OS '$os'") } } } /** * A linked hash set that's copied on write operations. */ private class LinkedHashSetWrapper<T : Any> { private val lock = Any() @Volatile private var immutableSet: Set<T>? = null private var synchronizedSet = LinkedHashSet<T>() fun add(element: T) { synchronized(lock) { if (!synchronizedSet.contains(element)) { copySyncSetIfExposedAsImmutable().add(element) } } } private fun copySyncSetIfExposedAsImmutable(): LinkedHashSet<T> { if (immutableSet != null) { immutableSet = null synchronizedSet = LinkedHashSet(synchronizedSet) } return synchronizedSet } fun remove(element: T) { synchronized(lock) { copySyncSetIfExposedAsImmutable().remove(element) } } fun replace(element: T) { synchronized(lock) { val set = copySyncSetIfExposedAsImmutable() set.remove(element) set.add(element) } } fun clear() { synchronized(lock) { immutableSet = null synchronizedSet = LinkedHashSet() } } fun getImmutableSet(): Set<T> { var result = immutableSet if (result == null) { synchronized(lock) { result = immutableSet if (result == null) { // Expose the same set as immutable. It should never be modified again. Next add/remove operations will copy synchronizedSet result = Collections.unmodifiableSet(synchronizedSet) immutableSet = result } } } return result!! } } private fun createPluginExceptionIfNeeded(error: Throwable, pluginId: PluginId): RuntimeException { return if (error is PluginException) error else PluginException(error, pluginId) } fun handleComponentError(t: Throwable, componentClassName: String?, pluginId: PluginId?) { if (t is StartupAbortedException) { throw t } val app = ApplicationManager.getApplication() if (app != null && app.isUnitTestMode) { throw t } var effectivePluginId = pluginId if (effectivePluginId == null || PluginManagerCore.CORE_ID == effectivePluginId) { if (componentClassName != null) { effectivePluginId = PluginManagerCore.getPluginByClassName(componentClassName) } } if (effectivePluginId != null && PluginManagerCore.CORE_ID != effectivePluginId) { throw StartupAbortedException("Fatal error initializing plugin $effectivePluginId", PluginException(t, effectivePluginId)) } else { throw StartupAbortedException("Fatal error initializing '$componentClassName'", t) } } private fun doLoadClass(name: String, pluginDescriptor: PluginDescriptor): Class<*> { // maybe null in unit tests val classLoader = pluginDescriptor.pluginClassLoader ?: ComponentManagerImpl::class.java.classLoader if (classLoader is PluginAwareClassLoader) { return classLoader.tryLoadingClass(name, true) ?: throw ClassNotFoundException("$name $classLoader") } else { return classLoader.loadClass(name) } } private class LightServiceComponentAdapter(private val initializedInstance: Any) : ComponentAdapter { override fun getComponentKey(): String = initializedInstance.javaClass.name override fun getComponentImplementation() = initializedInstance.javaClass override fun getComponentInstance(container: PicoContainer?) = initializedInstance override fun toString() = componentKey }
apache-2.0
f25e888747de114fcaa7d1db1a4a7c9a
36.789474
158
0.705815
5.21065
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/editor/quickDoc/OnEnumUsage.kt
4
440
/** * Enum of 1, 2 */ enum class SomeEnum(val i: Int) { One(1), Two(2); } fun use() { Some<caret>Enum.One } //INFO: <div class='definition'><pre><font color="808080"><i>OnEnumUsage.kt</i></font><br>public final enum class <b>SomeEnum</b> : <a href="psi_element://kotlin.Enum">Enum</a>&lt;<a href="psi_element://SomeEnum">SomeEnum</a>&gt;</pre></div><div class='content'><p>Enum of 1, 2</p></div><table class='sections'></table>
apache-2.0
218c9dc3e69b9fbaffbb2aacf89fb7f7
35.666667
319
0.627273
2.820513
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/copy/CopyKotlinDeclarationsHandler.kt
1
20393
// 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.copy import com.intellij.ide.util.EditorHelper import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.* import com.intellij.psi.* import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.copy.CopyFilesOrDirectoriesDialog import com.intellij.refactoring.copy.CopyFilesOrDirectoriesHandler import com.intellij.refactoring.copy.CopyHandlerDelegateBase import com.intellij.refactoring.util.MoveRenameUsageInfo import com.intellij.usageView.UsageInfo import com.intellij.util.IncorrectOperationException import com.intellij.util.containers.MultiMap import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix import org.jetbrains.kotlin.idea.core.packageMatchesDirectoryOrImplicit import org.jetbrains.kotlin.idea.core.quoteIfNeeded import org.jetbrains.kotlin.idea.core.util.toPsiDirectory import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively import org.jetbrains.kotlin.idea.refactoring.createKotlinFile import org.jetbrains.kotlin.idea.refactoring.move.* import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinDirectoryMoveTarget import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveConflictChecker import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.sourceRoot import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.UserDataProperty import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.utils.ifEmpty class CopyKotlinDeclarationsHandler : CopyHandlerDelegateBase() { companion object { private val commandName get() = RefactoringBundle.message("copy.handler.copy.files.directories") private val isUnitTestMode get() = ApplicationManager.getApplication().isUnitTestMode @set:TestOnly var Project.newName: String? by UserDataProperty(Key.create("NEW_NAME")) private fun PsiElement.getCopyableElement() = parentsWithSelf.firstOrNull { it is KtFile || (it is KtNamedDeclaration && it.parent is KtFile) } as? KtElement private fun PsiElement.getDeclarationsToCopy(): List<KtElement> = when (val declarationOrFile = getCopyableElement()) { is KtFile -> declarationOrFile.declarations.filterIsInstance<KtNamedDeclaration>().ifEmpty { listOf(declarationOrFile) } is KtNamedDeclaration -> listOf(declarationOrFile) else -> emptyList() } } private val copyFilesHandler by lazy { CopyFilesOrDirectoriesHandler() } private fun getSourceFiles(elements: Array<out PsiElement>): Array<PsiFileSystemItem>? { return elements .map { it.containingFile ?: it as? PsiFileSystemItem ?: return null } .toTypedArray() } private fun canCopyFiles(elements: Array<out PsiElement>, fromUpdate: Boolean): Boolean { val sourceFiles = getSourceFiles(elements) ?: return false if (!sourceFiles.any { it is KtFile }) return false return copyFilesHandler.canCopy(sourceFiles, fromUpdate) } private fun canCopyDeclarations(elements: Array<out PsiElement>): Boolean { val containingFile = elements .flatMap { it.getDeclarationsToCopy().ifEmpty { return false } } .distinctBy { it.containingFile } .singleOrNull() ?.containingFile ?: return false return containingFile.sourceRoot != null } override fun canCopy(elements: Array<out PsiElement>, fromUpdate: Boolean): Boolean { return canCopyDeclarations(elements) || canCopyFiles(elements, fromUpdate) } enum class ExistingFilePolicy { APPEND, OVERWRITE, SKIP } private fun getOrCreateTargetFile( originalFile: KtFile, targetDirectory: PsiDirectory, targetFileName: String ): KtFile? { val existingFile = targetDirectory.findFile(targetFileName) if (existingFile == originalFile) return null if (existingFile != null) when (getFilePolicy(existingFile, targetFileName, targetDirectory)) { ExistingFilePolicy.APPEND -> { } ExistingFilePolicy.OVERWRITE -> runWriteAction { existingFile.delete() } ExistingFilePolicy.SKIP -> return null } return runWriteAction { if (existingFile != null && existingFile.isValid) { existingFile as KtFile } else { createKotlinFile(targetFileName, targetDirectory) } } } private fun getFilePolicy( existingFile: PsiFile?, targetFileName: String, targetDirectory: PsiDirectory ): ExistingFilePolicy { val message = KotlinBundle.message( "text.file.0.already.exists.in.1", targetFileName, targetDirectory.virtualFile.path ) return if (existingFile !is KtFile) { if (isUnitTestMode) return ExistingFilePolicy.OVERWRITE val answer = Messages.showOkCancelDialog( message, commandName, KotlinBundle.message("action.text.overwrite"), KotlinBundle.message("action.text.cancel"), Messages.getQuestionIcon() ) if (answer == Messages.OK) ExistingFilePolicy.OVERWRITE else ExistingFilePolicy.SKIP } else { if (isUnitTestMode) return ExistingFilePolicy.APPEND val answer = Messages.showYesNoCancelDialog( message, commandName, KotlinBundle.message("action.text.append"), KotlinBundle.message("action.text.overwrite"), KotlinBundle.message("action.text.cancel"), Messages.getQuestionIcon() ) when (answer) { Messages.YES -> ExistingFilePolicy.APPEND Messages.NO -> ExistingFilePolicy.OVERWRITE else -> ExistingFilePolicy.SKIP } } } private data class TargetData( val openInEditor: Boolean, val newName: String, val targetDirWrapper: AutocreatingPsiDirectoryWrapper, val targetSourceRoot: VirtualFile? ) private data class SourceData( val project: Project, val singleElementToCopy: KtElement?, val elementsToCopy: List<KtElement>, val originalFile: KtFile, val initialTargetDirectory: PsiDirectory ) private fun getTargetDataForUnitTest(sourceData: SourceData): TargetData? { with(sourceData) { val targetSourceRoot: VirtualFile? = initialTargetDirectory.sourceRoot ?: return null val newName: String = project.newName ?: singleElementToCopy?.name ?: originalFile.name ?: return null if (singleElementToCopy != null && newName.isEmpty()) return null return TargetData( openInEditor = false, newName = newName, targetDirWrapper = initialTargetDirectory.toDirectoryWrapper(), targetSourceRoot = targetSourceRoot ) } } private fun getTargetDataForUX(sourceData: SourceData): TargetData? { val openInEditor: Boolean val newName: String? val targetDirWrapper: AutocreatingPsiDirectoryWrapper? val targetSourceRoot: VirtualFile? val singleNamedSourceElement = sourceData.singleElementToCopy as? KtNamedDeclaration if (singleNamedSourceElement !== null) { val dialog = CopyKotlinDeclarationDialog(singleNamedSourceElement, sourceData.initialTargetDirectory, sourceData.project) dialog.title = commandName if (!dialog.showAndGet()) return null openInEditor = dialog.openInEditor newName = dialog.newName ?: singleNamedSourceElement.name targetDirWrapper = dialog.targetDirectory?.toDirectoryWrapper() targetSourceRoot = dialog.targetSourceRoot } else { val dialog = CopyFilesOrDirectoriesDialog( arrayOf(sourceData.originalFile), sourceData.initialTargetDirectory, sourceData.project, /*doClone = */false ) if (!dialog.showAndGet()) return null openInEditor = dialog.openInEditor() newName = dialog.newName targetDirWrapper = dialog.targetDirectory?.toDirectoryWrapper() targetSourceRoot = dialog.targetDirectory?.sourceRoot } targetDirWrapper ?: return null newName ?: return null if (sourceData.singleElementToCopy != null && newName.isEmpty()) return null return TargetData( openInEditor = openInEditor, newName = newName, targetDirWrapper = targetDirWrapper, targetSourceRoot = targetSourceRoot ) } private fun collectInternalUsages(sourceData: SourceData, targetData: TargetData) = runReadAction { val targetPackageName = targetData.targetDirWrapper.getPackageName() val changeInfo = ContainerChangeInfo( ContainerInfo.Package(sourceData.originalFile.packageFqName), ContainerInfo.Package(FqName(targetPackageName)) ) sourceData.elementsToCopy.flatMapTo(LinkedHashSet()) { elementToCopy -> elementToCopy.getInternalReferencesToUpdateOnPackageNameChange(changeInfo).filter { val referencedElement = (it as? MoveRenameUsageInfo)?.referencedElement referencedElement == null || !elementToCopy.isAncestor(referencedElement) } } } private fun trackedCopyFiles(sourceFiles: Array<out PsiFileSystemItem>, initialTargetDirectory: PsiDirectory?): Set<VirtualFile> { if (!copyFilesHandler.canCopy(sourceFiles)) return emptySet() val mapper = object : VirtualFileListener { val filesCopied = mutableSetOf<VirtualFile>() override fun fileCopied(event: VirtualFileCopyEvent) { filesCopied.add(event.file) } override fun fileCreated(event: VirtualFileEvent) { filesCopied.add(event.file) } } with(VirtualFileManager.getInstance()) { try { addVirtualFileListener(mapper) copyFilesHandler.doCopy(sourceFiles, initialTargetDirectory) } finally { removeVirtualFileListener(mapper) } } return mapper.filesCopied } private fun doCopyFiles(filesToCopy: Array<out PsiFileSystemItem>, initialTargetDirectory: PsiDirectory?) { if (filesToCopy.isEmpty()) return val project = filesToCopy[0].project val psiManager = PsiManager.getInstance(project) project.executeCommand(commandName) { val copiedFiles = trackedCopyFiles(filesToCopy, initialTargetDirectory) copiedFiles.forEach { copiedFile -> val targetKtFile = psiManager.findFile(copiedFile) as? KtFile if (targetKtFile !== null) { runWriteAction { if (!targetKtFile.packageMatchesDirectoryOrImplicit()) { targetKtFile.containingDirectory?.getFqNameWithImplicitPrefix()?.quoteIfNeeded()?.let { targetDirectoryFqName -> targetKtFile.packageFqName = targetDirectoryFqName } } performDelayedRefactoringRequests(project) } } } } } override fun doCopy(elements: Array<out PsiElement>, defaultTargetDirectory: PsiDirectory?) { if (elements.isEmpty()) return if (!canCopyDeclarations(elements)) { getSourceFiles(elements)?.let { return doCopyFiles(it, defaultTargetDirectory) } } val elementsToCopy = elements.mapNotNull { it.getCopyableElement() } if (elementsToCopy.isEmpty()) return val singleElementToCopy = elementsToCopy.singleOrNull() val originalFile = elementsToCopy.first().containingFile as KtFile val initialTargetDirectory = defaultTargetDirectory ?: originalFile.containingDirectory ?: return val project = initialTargetDirectory.project val sourceData = SourceData( project = project, singleElementToCopy = singleElementToCopy, elementsToCopy = elementsToCopy, originalFile = originalFile, initialTargetDirectory = initialTargetDirectory ) val targetData = if (isUnitTestMode) getTargetDataForUnitTest(sourceData) else getTargetDataForUX(sourceData) targetData ?: return val internalUsages = collectInternalUsages(sourceData, targetData) markInternalUsages(internalUsages) val conflicts = collectConflicts(sourceData, targetData, internalUsages) project.checkConflictsInteractively(conflicts) { try { project.executeCommand(commandName) { doRefactor(sourceData, targetData) } } finally { cleanUpInternalUsages(internalUsages) } } } private data class RefactoringResult( val targetFile: PsiFile, val copiedDeclaration: KtNamedDeclaration?, val restoredInternalUsages: List<UsageInfo>? = null ) private fun getTargetFileName(sourceData: SourceData, targetData: TargetData) = if (targetData.newName.contains(".")) targetData.newName else targetData.newName + "." + sourceData.originalFile.virtualFile.extension private fun doRefactor(sourceData: SourceData, targetData: TargetData) { var refactoringResult: RefactoringResult? = null try { val targetDirectory = runWriteAction { targetData.targetDirWrapper.getOrCreateDirectory(sourceData.initialTargetDirectory) } val targetFileName = getTargetFileName(sourceData, targetData) val isSingleDeclarationInFile = sourceData.singleElementToCopy is KtNamedDeclaration && sourceData.originalFile.declarations.singleOrNull() == sourceData.singleElementToCopy val fileToCopy = when { sourceData.singleElementToCopy is KtFile -> sourceData.singleElementToCopy isSingleDeclarationInFile -> sourceData.originalFile else -> null } refactoringResult = if (fileToCopy !== null) { doRefactoringOnFile(fileToCopy, sourceData, targetDirectory, targetFileName, isSingleDeclarationInFile) } else { val targetFile = getOrCreateTargetFile(sourceData.originalFile, targetDirectory, targetFileName) ?: throw IncorrectOperationException("Could not create target file.") doRefactoringOnElement(sourceData, targetFile) } refactoringResult.copiedDeclaration?.let<KtNamedDeclaration, Unit> { newDeclaration -> if (targetData.newName == newDeclaration.name) return@let val selfReferences = ReferencesSearch.search(newDeclaration, LocalSearchScope(newDeclaration)).findAll() runWriteAction { selfReferences.forEach { it.handleElementRename(targetData.newName) } newDeclaration.setName(targetData.newName) } } if (targetData.openInEditor) { EditorHelper.openInEditor(refactoringResult.targetFile) } } catch (e: IncorrectOperationException) { Messages.showMessageDialog(sourceData.project, e.message, RefactoringBundle.message("error.title"), Messages.getErrorIcon()) } finally { refactoringResult?.restoredInternalUsages?.let { cleanUpInternalUsages(it) } } } private fun doRefactoringOnFile( fileToCopy: KtFile, sourceData: SourceData, targetDirectory: PsiDirectory, targetFileName: String, isSingleDeclarationInFile: Boolean ): RefactoringResult { val targetFile = runWriteAction { // implicit package prefix may change after copy val targetDirectoryFqName = targetDirectory.getFqNameWithImplicitPrefix() val copiedFile = targetDirectory.copyFileFrom(targetFileName, fileToCopy) if (copiedFile is KtFile && fileToCopy.packageMatchesDirectoryOrImplicit()) { targetDirectoryFqName?.quoteIfNeeded()?.let { copiedFile.packageFqName = it } } performDelayedRefactoringRequests(sourceData.project) copiedFile } val copiedDeclaration = if (isSingleDeclarationInFile && targetFile is KtFile) { targetFile.declarations.singleOrNull() as? KtNamedDeclaration } else null return RefactoringResult(targetFile, copiedDeclaration) } private fun doRefactoringOnElement( sourceData: SourceData, targetFile: KtFile ): RefactoringResult { val restoredInternalUsages = ArrayList<UsageInfo>() val oldToNewElementsMapping = HashMap<PsiElement, PsiElement>() runWriteAction { val newElements = sourceData.elementsToCopy.map { targetFile.add(it.copy()) as KtNamedDeclaration } sourceData.elementsToCopy.zip(newElements).toMap(oldToNewElementsMapping) oldToNewElementsMapping[sourceData.originalFile] = targetFile for (newElement in oldToNewElementsMapping.values) { restoredInternalUsages += restoreInternalUsages(newElement as KtElement, oldToNewElementsMapping, forcedRestore = true) postProcessMoveUsages(restoredInternalUsages, oldToNewElementsMapping) } performDelayedRefactoringRequests(sourceData.project) } val copiedDeclaration = oldToNewElementsMapping.values.filterIsInstance<KtNamedDeclaration>().singleOrNull() return RefactoringResult(targetFile, copiedDeclaration, restoredInternalUsages) } private fun collectConflicts( sourceData: SourceData, targetData: TargetData, internalUsages: HashSet<UsageInfo> ): MultiMap<PsiElement, String> { if (isUnitTestMode && BaseRefactoringProcessor.ConflictsInTestsException.isTestIgnore()) return MultiMap.empty() val targetSourceRootPsi = targetData.targetSourceRoot?.toPsiDirectory(sourceData.project) ?: return MultiMap.empty() if (sourceData.project != sourceData.originalFile.project) return MultiMap.empty() val conflictChecker = MoveConflictChecker( sourceData.project, sourceData.elementsToCopy, KotlinDirectoryMoveTarget(FqName.ROOT, targetSourceRootPsi.virtualFile), sourceData.originalFile ) return MultiMap<PsiElement, String>().also { conflictChecker.checkModuleConflictsInDeclarations(internalUsages, it) conflictChecker.checkVisibilityInDeclarations(it) } } override fun doClone(element: PsiElement) { } }
apache-2.0
bc4386850cf3c7a338d11cebe6eca0ad
40.618367
158
0.673123
6.044161
false
false
false
false
siosio/intellij-community
plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/compilerRunner/JpsKotlinCompilerRunner.kt
1
14750
// 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.compilerRunner import com.intellij.util.xmlb.XmlSerializerUtil import org.jetbrains.annotations.TestOnly import org.jetbrains.jps.api.GlobalOptions import org.jetbrains.kotlin.cli.common.CompilerSystemProperties import org.jetbrains.kotlin.cli.common.ExitCode import org.jetbrains.kotlin.cli.common.arguments.* import org.jetbrains.kotlin.cli.common.messages.MessageCollectorUtil import org.jetbrains.kotlin.config.CompilerSettings import org.jetbrains.kotlin.config.IncrementalCompilation import org.jetbrains.kotlin.config.additionalArgumentsAsList import org.jetbrains.kotlin.daemon.client.CompileServiceSession import org.jetbrains.kotlin.daemon.client.KotlinCompilerClient import org.jetbrains.kotlin.daemon.common.* import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts import org.jetbrains.kotlin.jps.build.KotlinBuilder import java.io.ByteArrayOutputStream import java.io.File import java.io.PrintStream class JpsKotlinCompilerRunner { private val log: KotlinLogger = JpsKotlinLogger(KotlinBuilder.LOG) private var compilerSettings: CompilerSettings? = null private inline fun withCompilerSettings(settings: CompilerSettings, fn: () -> Unit) { val old = compilerSettings try { compilerSettings = settings fn() } finally { compilerSettings = old } } companion object { @Volatile private var _jpsCompileServiceSession: CompileServiceSession? = null @TestOnly fun shutdownDaemon() { _jpsCompileServiceSession?.let { try { it.compileService.shutdown() } catch (_: Throwable) { } } _jpsCompileServiceSession = null } fun releaseCompileServiceSession() { _jpsCompileServiceSession?.let { try { it.compileService.releaseCompileSession(it.sessionId) } catch (_: Throwable) { } } _jpsCompileServiceSession = null } @Synchronized private fun getOrCreateDaemonConnection(newConnection: () -> CompileServiceSession?): CompileServiceSession? { // TODO: consider adding state "ping" to the daemon interface if (_jpsCompileServiceSession == null || _jpsCompileServiceSession!!.compileService.getDaemonOptions() !is CompileService.CallResult.Good<DaemonOptions>) { releaseCompileServiceSession() _jpsCompileServiceSession = newConnection() } return _jpsCompileServiceSession } const val FAIL_ON_FALLBACK_PROPERTY = "test.kotlin.jps.compiler.runner.fail.on.fallback" } fun classesFqNamesByFiles( environment: JpsCompilerEnvironment, files: Set<File> ): Set<String> = withDaemonOrFallback( withDaemon = { doWithDaemon(environment) { sessionId, daemon -> daemon.classesFqNamesByFiles( sessionId, files.toSet() // convert to standard HashSet to avoid serialization issues ) } }, fallback = { CompilerRunnerUtil.invokeClassesFqNames(environment, files) } ) fun runK2MetadataCompiler( commonArguments: CommonCompilerArguments, k2MetadataArguments: K2MetadataCompilerArguments, compilerSettings: CompilerSettings, environment: JpsCompilerEnvironment, destination: String, classpath: Collection<String>, sourceFiles: Collection<File> ) { val arguments = mergeBeans(commonArguments, XmlSerializerUtil.createCopy(k2MetadataArguments)) val classpathSet = arguments.classpath?.split(File.pathSeparator)?.toMutableSet() ?: mutableSetOf() classpathSet.addAll(classpath) arguments.classpath = classpath.joinToString(File.pathSeparator) arguments.freeArgs = sourceFiles.map { it.absolutePath } arguments.destination = arguments.destination ?: destination withCompilerSettings(compilerSettings) { runCompiler(KotlinCompilerClass.METADATA, arguments, environment) } } fun runK2JvmCompiler( commonArguments: CommonCompilerArguments, k2jvmArguments: K2JVMCompilerArguments, compilerSettings: CompilerSettings, environment: JpsCompilerEnvironment, moduleFile: File ) { val arguments = mergeBeans(commonArguments, XmlSerializerUtil.createCopy(k2jvmArguments)) setupK2JvmArguments(moduleFile, arguments) withCompilerSettings(compilerSettings) { runCompiler(KotlinCompilerClass.JVM, arguments, environment) } } fun runK2JsCompiler( commonArguments: CommonCompilerArguments, k2jsArguments: K2JSCompilerArguments, compilerSettings: CompilerSettings, environment: JpsCompilerEnvironment, allSourceFiles: Collection<File>, commonSources: Collection<File>, sourceMapRoots: Collection<File>, libraries: List<String>, friendModules: List<String>, outputFile: File ) { log.debug("K2JS: common arguments: " + ArgumentUtils.convertArgumentsToStringList(commonArguments)) log.debug("K2JS: JS arguments: " + ArgumentUtils.convertArgumentsToStringList(k2jsArguments)) val arguments = mergeBeans(commonArguments, XmlSerializerUtil.createCopy(k2jsArguments)) log.debug("K2JS: merged arguments: " + ArgumentUtils.convertArgumentsToStringList(arguments)) setupK2JsArguments(outputFile, allSourceFiles, commonSources, libraries, friendModules, arguments) if (arguments.sourceMap) { arguments.sourceMapBaseDirs = sourceMapRoots.joinToString(File.pathSeparator) { it.path } } log.debug("K2JS: arguments after setup" + ArgumentUtils.convertArgumentsToStringList(arguments)) withCompilerSettings(compilerSettings) { runCompiler(KotlinCompilerClass.JS, arguments, environment) } } private fun compileWithDaemonOrFallback( compilerClassName: String, compilerArgs: CommonCompilerArguments, environment: JpsCompilerEnvironment ) { log.debug("Using kotlin-home = " + KotlinArtifacts.instance.kotlincDirectory) withDaemonOrFallback( withDaemon = { compileWithDaemon(compilerClassName, compilerArgs, environment) }, fallback = { fallbackCompileStrategy(compilerArgs, compilerClassName, environment) } ) } private fun runCompiler(compilerClassName: String, compilerArgs: CommonCompilerArguments, environment: JpsCompilerEnvironment) { try { compileWithDaemonOrFallback(compilerClassName, compilerArgs, environment) } catch (e: Throwable) { MessageCollectorUtil.reportException(environment.messageCollector, e) reportInternalCompilerError(environment.messageCollector) } } private fun compileWithDaemon( compilerClassName: String, compilerArgs: CommonCompilerArguments, environment: JpsCompilerEnvironment ): Int? { val targetPlatform = when (compilerClassName) { KotlinCompilerClass.JVM -> CompileService.TargetPlatform.JVM KotlinCompilerClass.JS -> CompileService.TargetPlatform.JS KotlinCompilerClass.METADATA -> CompileService.TargetPlatform.METADATA else -> throw IllegalArgumentException("Unknown compiler type $compilerClassName") } val compilerMode = CompilerMode.JPS_COMPILER val verbose = compilerArgs.verbose val options = CompilationOptions( compilerMode, targetPlatform, reportCategories(verbose), reportSeverity(verbose), requestedCompilationResults = emptyArray() ) return doWithDaemon(environment) { sessionId, daemon -> environment.withProgressReporter { progress -> progress.compilationStarted() daemon.compile( sessionId, withAdditionalCompilerArgs(compilerArgs), options, JpsCompilerServicesFacadeImpl(environment), null ) } } } private fun <T> withDaemonOrFallback(withDaemon: () -> T?, fallback: () -> T): T = if (isDaemonEnabled()) { withDaemon() ?: fallback() } else { fallback() } private fun <T> doWithDaemon( environment: JpsCompilerEnvironment, fn: (sessionId: Int, daemon: CompileService) -> CompileService.CallResult<T> ): T? { log.debug("Try to connect to daemon") val connection = getDaemonConnection(environment) if (connection == null) { log.info("Could not connect to daemon") return null } val (daemon, sessionId) = connection val res = fn(sessionId, daemon) // TODO: consider implementing connection retry, instead of fallback here return res.takeUnless { it is CompileService.CallResult.Dying }?.get() } private fun withAdditionalCompilerArgs(compilerArgs: CommonCompilerArguments): Array<String> { val allArgs = ArgumentUtils.convertArgumentsToStringList(compilerArgs) + (compilerSettings?.additionalArgumentsAsList ?: emptyList()) return allArgs.toTypedArray() } private fun reportCategories(verbose: Boolean): Array<Int> { val categories = if (!verbose) { arrayOf(ReportCategory.COMPILER_MESSAGE, ReportCategory.EXCEPTION) } else { ReportCategory.values() } return categories.map { it.code }.toTypedArray() } private fun reportSeverity(verbose: Boolean): Int = if (!verbose) { ReportSeverity.INFO.code } else { ReportSeverity.DEBUG.code } private fun fallbackCompileStrategy( compilerArgs: CommonCompilerArguments, compilerClassName: String, environment: JpsCompilerEnvironment ) { if ("true" == System.getProperty("kotlin.jps.tests") && "true" == System.getProperty(FAIL_ON_FALLBACK_PROPERTY)) { error("Cannot compile with Daemon, see logs bellow. Fallback strategy is disabled in tests") } // otherwise fallback to in-process log.info("Compile in-process") val stream = ByteArrayOutputStream() val out = PrintStream(stream) // the property should be set at least for parallel builds to avoid parallel building problems (racing between destroying and using environment) // unfortunately it cannot be currently set by default globally, because it breaks many tests // since there is no reliable way so far to detect running under tests, switching it on only for parallel builds if (System.getProperty(GlobalOptions.COMPILE_PARALLEL_OPTION, "false").toBoolean()) CompilerSystemProperties.KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY.value = "true" val rc = environment.withProgressReporter { progress -> progress.compilationStarted() CompilerRunnerUtil.invokeExecMethod(compilerClassName, withAdditionalCompilerArgs(compilerArgs), environment, out) } // exec() returns an ExitCode object, class of which is loaded with a different class loader, // so we take it's contents through reflection val exitCode = ExitCode.valueOf(getReturnCodeFromObject(rc)) processCompilerOutput(environment.messageCollector, environment.outputItemsCollector, stream, exitCode) } private fun setupK2JvmArguments(moduleFile: File, settings: K2JVMCompilerArguments) { with(settings) { buildFile = moduleFile.absolutePath destination = null noStdlib = true noReflect = true noJdk = true } } private fun setupK2JsArguments( _outputFile: File, allSourceFiles: Collection<File>, _commonSources: Collection<File>, _libraries: List<String>, _friendModules: List<String>, settings: K2JSCompilerArguments ) { with(settings) { noStdlib = true freeArgs = allSourceFiles.map { it.path }.toMutableList() commonSources = _commonSources.map { it.path }.toTypedArray() outputFile = _outputFile.path metaInfo = true libraries = _libraries.joinToString(File.pathSeparator) friendModules = _friendModules.joinToString(File.pathSeparator) } } private fun getReturnCodeFromObject(rc: Any?): String = when { rc == null -> ExitCode.INTERNAL_ERROR.toString() ExitCode::class.java.name == rc::class.java.name -> rc.toString() else -> throw IllegalStateException("Unexpected return: " + rc) } private fun getDaemonConnection(environment: JpsCompilerEnvironment): CompileServiceSession? = getOrCreateDaemonConnection { environment.progressReporter.progress("connecting to daemon") val compilerPath = KotlinArtifacts.instance.kotlinCompiler val daemonJarPath = KotlinArtifacts.instance.kotlinDaemon val toolsJarPath = CompilerRunnerUtil.jdkToolsJar val compilerId = CompilerId.makeCompilerId(listOfNotNull(compilerPath, toolsJarPath, daemonJarPath)) val daemonOptions = configureDaemonOptions() val additionalJvmParams = mutableListOf<String>() IncrementalCompilation.toJvmArgs(additionalJvmParams) val clientFlagFile = KotlinCompilerClient.getOrCreateClientFlagFile(daemonOptions) val sessionFlagFile = makeAutodeletingFlagFile("compiler-jps-session-", File(daemonOptions.runFilesPathOrDefault)) environment.withProgressReporter { progress -> progress.progress("connecting to daemon") KotlinCompilerRunnerUtils.newDaemonConnection( compilerId, clientFlagFile, sessionFlagFile, environment.messageCollector, log.isDebugEnabled, daemonOptions, additionalJvmParams.toTypedArray() ) } } }
apache-2.0
1d649585b31c4345876907c5ee225f8e
39.858726
167
0.662373
5.301941
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/serialization/KonanMangler.kt
2
7409
package org.jetbrains.kotlin.backend.konan.serialization import org.jetbrains.kotlin.backend.common.serialization.mangle.MangleMode import org.jetbrains.kotlin.backend.common.serialization.mangle.descriptor.DescriptorBasedKotlinManglerImpl import org.jetbrains.kotlin.backend.common.serialization.mangle.descriptor.DescriptorExportCheckerVisitor import org.jetbrains.kotlin.backend.common.serialization.mangle.descriptor.DescriptorMangleComputer import org.jetbrains.kotlin.backend.common.serialization.mangle.ir.IrBasedKotlinManglerImpl import org.jetbrains.kotlin.backend.common.serialization.mangle.ir.IrExportCheckerVisitor import org.jetbrains.kotlin.backend.common.serialization.mangle.ir.IrMangleComputer import org.jetbrains.kotlin.backend.konan.* import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.types.getClass import org.jetbrains.kotlin.ir.util.hasAnnotation abstract class AbstractKonanIrMangler(private val withReturnType: Boolean) : IrBasedKotlinManglerImpl() { override fun getExportChecker(): IrExportCheckerVisitor = KonanIrExportChecker() override fun getMangleComputer(mode: MangleMode): IrMangleComputer = KonanIrManglerComputer(StringBuilder(256), mode, withReturnType) private class KonanIrExportChecker : IrExportCheckerVisitor() { override fun IrDeclaration.isPlatformSpecificExported(): Boolean { if (this is IrSimpleFunction) if (isFakeOverride) return false // TODO: revise if (annotations.hasAnnotation(RuntimeNames.symbolNameAnnotation)) { // Treat any `@SymbolName` declaration as exported. return true } if (annotations.hasAnnotation(RuntimeNames.exportForCppRuntime)) { // Treat any `@ExportForCppRuntime` declaration as exported. return true } if (annotations.hasAnnotation(RuntimeNames.cnameAnnotation)) { // Treat `@CName` declaration as exported. return true } if (annotations.hasAnnotation(RuntimeNames.exportForCompilerAnnotation)) { return true } return false } } private class KonanIrManglerComputer(builder: StringBuilder, mode: MangleMode, private val withReturnType: Boolean) : IrMangleComputer(builder, mode) { override fun copy(newMode: MangleMode): IrMangleComputer = KonanIrManglerComputer(builder, newMode, withReturnType) override fun addReturnType(): Boolean = withReturnType override fun IrFunction.platformSpecificFunctionName(): String? { (if (this is IrConstructor && this.isObjCConstructor) this.getObjCInitMethod() else this)?.getObjCMethodInfo() ?.let { return buildString { if (extensionReceiverParameter != null) { append(extensionReceiverParameter!!.type.getClass()!!.name) append(".") } append("objc:") append(it.selector) if (this@platformSpecificFunctionName is IrConstructor && [email protected]) append("#Constructor") if ((this@platformSpecificFunctionName as? IrSimpleFunction)?.correspondingPropertySymbol != null) { append("#Accessor") } } } return null } override fun IrFunction.specialValueParamPrefix(param: IrValueParameter): String { // TODO: there are clashes originating from ObjectiveC interop. // kotlinx.cinterop.ObjCClassOf<T>.create(format: kotlin.String): T defined in platform.Foundation in file Foundation.kt // and // kotlinx.cinterop.ObjCClassOf<T>.create(string: kotlin.String): T defined in platform.Foundation in file Foundation.kt return if (this.hasObjCMethodAnnotation || this.hasObjCFactoryAnnotation || this.isObjCClassMethod()) "${param.name}:" else "" } } } object KonanManglerIr : AbstractKonanIrMangler(false) abstract class AbstractKonanDescriptorMangler : DescriptorBasedKotlinManglerImpl() { override fun getExportChecker(): DescriptorExportCheckerVisitor = KonanDescriptorExportChecker() override fun getMangleComputer(mode: MangleMode): DescriptorMangleComputer = KonanDescriptorMangleComputer(StringBuilder(256), mode) private class KonanDescriptorExportChecker : DescriptorExportCheckerVisitor() { override fun DeclarationDescriptor.isPlatformSpecificExported(): Boolean { if (this is SimpleFunctionDescriptor) { if (kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) return false } // TODO: revise if (annotations.hasAnnotation(RuntimeNames.symbolNameAnnotation)) { // Treat any `@SymbolName` declaration as exported. return true } if (annotations.hasAnnotation(RuntimeNames.exportForCppRuntime)) { // Treat any `@ExportForCppRuntime` declaration as exported. return true } if (annotations.hasAnnotation(RuntimeNames.cnameAnnotation)) { // Treat `@CName` declaration as exported. return true } if (annotations.hasAnnotation(RuntimeNames.exportForCompilerAnnotation)) { return true } return false } } private class KonanDescriptorMangleComputer(builder: StringBuilder, mode: MangleMode) : DescriptorMangleComputer(builder, mode) { override fun copy(newMode: MangleMode): DescriptorMangleComputer = KonanDescriptorMangleComputer(builder, newMode) override fun FunctionDescriptor.platformSpecificFunctionName(): String? { (if (this is ConstructorDescriptor && this.isObjCConstructor) this.getObjCInitMethod() else this)?.getObjCMethodInfo() ?.let { return buildString { if (extensionReceiverParameter != null) { append(extensionReceiverParameter!!.type.constructor.declarationDescriptor!!.name) append(".") } append("objc:") append(it.selector) if (this@platformSpecificFunctionName is ConstructorDescriptor && [email protected]) append("#Constructor") if (this@platformSpecificFunctionName is PropertyAccessorDescriptor) { append("#Accessor") } } } return null } override fun FunctionDescriptor.specialValueParamPrefix(param: ValueParameterDescriptor): String { return if (this.hasObjCMethodAnnotation || this.hasObjCFactoryAnnotation || this.isObjCClassMethod()) "${param.name}:" else "" } } } object KonanManglerDesc : AbstractKonanDescriptorMangler()
apache-2.0
6a60040a252f951a221343edfabed840
49.067568
169
0.645566
5.638508
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/badges/models/BadgePreview.kt
1
2831
package org.thoughtcrime.securesms.badges.models import android.view.View import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.badges.BadgeImageView import org.thoughtcrime.securesms.components.AvatarImageView import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder /** * "Hero Image" for displaying an Avatar and badge. Allows the user to see what their profile will look like with a particular badge applied. */ object BadgePreview { fun register(mappingAdapter: MappingAdapter) { mappingAdapter.registerFactory(BadgeModel.FeaturedModel::class.java, LayoutFactory({ ViewHolder(it) }, R.layout.featured_badge_preview_preference)) mappingAdapter.registerFactory(BadgeModel.SubscriptionModel::class.java, LayoutFactory({ ViewHolder(it) }, R.layout.subscription_flow_badge_preview_preference)) mappingAdapter.registerFactory(BadgeModel.GiftedBadgeModel::class.java, LayoutFactory({ ViewHolder(it) }, R.layout.gift_badge_preview_preference)) } sealed class BadgeModel<T : BadgeModel<T>> : MappingModel<T> { companion object { const val PAYLOAD_BADGE = "badge" } abstract val badge: Badge? abstract val recipient: Recipient data class FeaturedModel(override val badge: Badge?) : BadgeModel<FeaturedModel>() { override val recipient: Recipient = Recipient.self() } data class SubscriptionModel(override val badge: Badge?) : BadgeModel<SubscriptionModel>() { override val recipient: Recipient = Recipient.self() } data class GiftedBadgeModel(override val badge: Badge?, override val recipient: Recipient) : BadgeModel<GiftedBadgeModel>() override fun areItemsTheSame(newItem: T): Boolean { return recipient.id == newItem.recipient.id } override fun areContentsTheSame(newItem: T): Boolean { return badge == newItem.badge && recipient.hasSameContent(newItem.recipient) } override fun getChangePayload(newItem: T): Any? { return if (recipient.hasSameContent(newItem.recipient) && badge != newItem.badge) { PAYLOAD_BADGE } else { null } } } class ViewHolder<T : BadgeModel<T>>(itemView: View) : MappingViewHolder<T>(itemView) { private val avatar: AvatarImageView = itemView.findViewById(R.id.avatar) private val badge: BadgeImageView = itemView.findViewById(R.id.badge) override fun bind(model: T) { if (payload.isEmpty()) { avatar.setRecipient(model.recipient) avatar.disableQuickContact() } badge.setBadge(model.badge) } } }
gpl-3.0
bd3c645333731af2a4881961d9e57212
37.256757
164
0.744966
4.362096
false
false
false
false
androidx/androidx
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/InputDispatcher.kt
3
29743
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.test import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.key.Key import androidx.compose.ui.node.RootForTest internal expect fun createInputDispatcher( testContext: TestContext, root: RootForTest ): InputDispatcher /** * Dispatcher to inject any kind of input. An [InputDispatcher] is created at the * beginning of [performMultiModalInput] or the single modality alternatives, and disposed at the * end of that method. The state of all input modalities is persisted and restored on the next * invocation of [performMultiModalInput] (or an alternative). * * Dispatching input happens in two stages. In the first stage, all events are generated * (enqueued), using the `enqueue*` methods, and in the second stage all events are injected. * Clients of [InputDispatcher] should only call methods for the first stage listed below, the * second stage is handled by [performMultiModalInput] and friends. * * Touch input: * * [getCurrentTouchPosition] * * [enqueueTouchDown] * * [enqueueTouchMove] * * [updateTouchPointer] * * [enqueueTouchUp] * * [enqueueTouchCancel] * * Mouse input: * * [currentMousePosition] * * [enqueueMousePress] * * [enqueueMouseMove] * * [updateMousePosition] * * [enqueueMouseRelease] * * [enqueueMouseCancel] * * [enqueueMouseScroll] * * Rotary input: * * [enqueueRotaryScrollHorizontally] * * [enqueueRotaryScrollVertically] * * Key input: * * [enqueueKeyDown] * * [enqueueKeyUp] * * Chaining methods: * * [advanceEventTime] */ internal abstract class InputDispatcher( private val testContext: TestContext, private val root: RootForTest ) { companion object { /** * The default time between two successively injected events, 16 milliseconds. Events are * normally sent on every frame and thus follow the frame rate. On a 60Hz screen this is * ~16ms per frame. */ var eventPeriodMillis = 16L internal set /** * The delay between a down event on a particular [Key] and the first repeat event on that * same key. */ const val InitialRepeatDelay = 500L /** * The interval between subsequent repeats (after the initial repeat) on a particular key. */ const val SubsequentRepeatDelay = 50L } /** * The eventTime of the next event. */ protected var currentTime = testContext.currentTime /** * The state of the current touch gesture. If `null`, no touch gesture is in progress. */ protected var partialGesture: PartialGesture? = null /** * The state of the mouse. The mouse state is always available. It starts at [Offset.Zero] in * not-entered state. */ protected var mouseInputState: MouseInputState = MouseInputState() /** * The state of the keyboard keys. The key input state is always available. * It starts with no keys pressed down and the [KeyInputState.downTime] set to zero. */ protected var keyInputState: KeyInputState = KeyInputState() /** * The state of the rotary button. */ protected var rotaryInputState: RotaryInputState = RotaryInputState() /** * Indicates if a gesture is in progress or not. A gesture is in progress if at least one * finger is (still) touching the screen. */ val isTouchInProgress: Boolean get() = partialGesture != null /** * Indicates whether caps lock is on or not. */ val isCapsLockOn: Boolean get() = keyInputState.capsLockOn /** * Indicates whether num lock is on or not. */ val isNumLockOn: Boolean get() = keyInputState.numLockOn /** * Indicates whether scroll lock is on or not. */ val isScrollLockOn: Boolean get() = keyInputState.scrollLockOn init { val rootHash = identityHashCode(root) val state = testContext.states.remove(rootHash) if (state != null) { partialGesture = state.partialGesture mouseInputState = state.mouseInputState keyInputState = state.keyInputState } } protected open fun saveState(root: RootForTest?) { if (root != null) { val rootHash = identityHashCode(root) testContext.states[rootHash] = InputDispatcherState( partialGesture, mouseInputState, keyInputState ) } } @OptIn(InternalTestApi::class) private val TestContext.currentTime get() = testOwner.mainClock.currentTime private val RootForTest.bounds get() = semanticsOwner.rootSemanticsNode.boundsInRoot protected fun isWithinRootBounds(position: Offset): Boolean = root.bounds.contains(position) /** * Increases the current event time by [durationMillis]. * * Depending on the [keyInputState], there may be repeat key events that need to be sent within * the given duration. If there are, the clock will be forwarded until it is time for the repeat * key event, the key event will be sent, and then the clock will be forwarded by the remaining * duration. * * @param durationMillis The duration of the delay. Must be positive */ fun advanceEventTime(durationMillis: Long = eventPeriodMillis) { require(durationMillis >= 0) { "duration of a delay can only be positive, not $durationMillis" } val endTime = currentTime + durationMillis keyInputState.sendRepeatKeysIfNeeded(endTime) currentTime = endTime } /** * During a touch gesture, returns the position of the last touch event of the given * [pointerId]. Returns `null` if no touch gesture is in progress for that [pointerId]. * * @param pointerId The id of the pointer for which to return the current position * @return The current position of the pointer with the given [pointerId], or `null` if the * pointer is not currently in use */ fun getCurrentTouchPosition(pointerId: Int): Offset? { return partialGesture?.lastPositions?.get(pointerId) } /** * The current position of the mouse. If no mouse event has been sent yet, will be * [Offset.Zero]. */ val currentMousePosition: Offset get() = mouseInputState.lastPosition /** * Indicates if the given [key] is pressed down or not. * * @param key The key to be checked. * @return true if given [key] is pressed, otherwise false. */ fun isKeyDown(key: Key): Boolean = keyInputState.isKeyDown(key) /** * Generates a down touch event at [position] for the pointer with the given [pointerId]. * Starts a new touch gesture if no other [pointerId]s are down. Only possible if the * [pointerId] is not currently being used, although pointer ids may be reused during a touch * gesture. * * @param pointerId The id of the pointer, can be any number not yet in use by another pointer * @param position The coordinate of the down event * * @see enqueueTouchMove * @see updateTouchPointer * @see enqueueTouchUp * @see enqueueTouchCancel */ fun enqueueTouchDown(pointerId: Int, position: Offset) { var gesture = partialGesture // Check if this pointer is not already down require(gesture == null || !gesture.lastPositions.containsKey(pointerId)) { "Cannot send DOWN event, a gesture is already in progress for pointer $pointerId" } if (mouseInputState.hasAnyButtonPressed) { // If mouse buttons are down, a touch gesture cancels the mouse gesture mouseInputState.enqueueCancel() } else if (mouseInputState.isEntered) { // If no mouse buttons were down, we may have been in hovered state mouseInputState.exitHover() } // Send a MOVE event if pointers have changed since the last event gesture?.flushPointerUpdates() // Start a new gesture, or add the pointerId to the existing gesture if (gesture == null) { gesture = PartialGesture(currentTime, position, pointerId) partialGesture = gesture } else { gesture.lastPositions[pointerId] = position } // Send the DOWN event gesture.enqueueDown(pointerId) } /** * Generates a move touch event without moving any of the pointers. Use this to commit all * changes in pointer location made with [updateTouchPointer]. The generated event will contain * the current position of all pointers. * * @see enqueueTouchDown * @see updateTouchPointer * @see enqueueTouchUp * @see enqueueTouchCancel * @see enqueueTouchMoves */ fun enqueueTouchMove() { val gesture = checkNotNull(partialGesture) { "Cannot send MOVE event, no gesture is in progress" } gesture.enqueueMove() gesture.hasPointerUpdates = false } /** * Enqueue the current time+coordinates as a move event, with the historical parameters * preceding it (so that they are ultimately available from methods like * MotionEvent.getHistoricalX). * * @see enqueueTouchMove * @see TouchInjectionScope.moveWithHistory */ fun enqueueTouchMoves( relativeHistoricalTimes: List<Long>, historicalCoordinates: List<List<Offset>> ) { val gesture = checkNotNull(partialGesture) { "Cannot send MOVE event, no gesture is in progress" } gesture.enqueueMoves(relativeHistoricalTimes, historicalCoordinates) gesture.hasPointerUpdates = false } /** * Updates the position of the touch pointer with the given [pointerId] to the given * [position], but does not generate a move touch event. Use this to move multiple pointers * simultaneously. To generate the next move touch event, which will contain the current * position of _all_ pointers (not just the moved ones), call [enqueueTouchMove]. If you move * one or more pointers and then call [enqueueTouchDown], without calling [enqueueTouchMove] * first, a move event will be generated right before that down event. * * @param pointerId The id of the pointer to move, as supplied in [enqueueTouchDown] * @param position The position to move the pointer to * * @see enqueueTouchDown * @see enqueueTouchMove * @see enqueueTouchUp * @see enqueueTouchCancel */ fun updateTouchPointer(pointerId: Int, position: Offset) { val gesture = partialGesture // Check if this pointer is in the gesture check(gesture != null) { "Cannot move pointers, no gesture is in progress" } require(gesture.lastPositions.containsKey(pointerId)) { "Cannot move pointer $pointerId, it is not active in the current gesture" } gesture.lastPositions[pointerId] = position gesture.hasPointerUpdates = true } /** * Generates an up touch event for the given [pointerId] at the current position of that * pointer. * * @param pointerId The id of the pointer to lift up, as supplied in [enqueueTouchDown] * * @see enqueueTouchDown * @see updateTouchPointer * @see enqueueTouchMove * @see enqueueTouchCancel */ fun enqueueTouchUp(pointerId: Int) { val gesture = partialGesture // Check if this pointer is in the gesture check(gesture != null) { "Cannot send UP event, no gesture is in progress" } require(gesture.lastPositions.containsKey(pointerId)) { "Cannot send UP event for pointer $pointerId, it is not active in the current gesture" } // First send the UP event gesture.enqueueUp(pointerId) // Then remove the pointer, and end the gesture if no pointers are left gesture.lastPositions.remove(pointerId) if (gesture.lastPositions.isEmpty()) { partialGesture = null } } /** * Generates a cancel touch event for the current touch gesture. Sent automatically when * mouse events are sent while a touch gesture is in progress. * * @see enqueueTouchDown * @see updateTouchPointer * @see enqueueTouchMove * @see enqueueTouchUp */ fun enqueueTouchCancel() { val gesture = checkNotNull(partialGesture) { "Cannot send CANCEL event, no gesture is in progress" } gesture.enqueueCancel() partialGesture = null } /** * Generates a move event with all pointer locations, if any of the pointers has been moved by * [updateTouchPointer] since the last move event. */ private fun PartialGesture.flushPointerUpdates() { if (hasPointerUpdates) { enqueueTouchMove() } } /** * Generates a mouse button pressed event for the given [buttonId]. This will generate all * required associated events as well, such as a down event if it is the first button being * pressed and an optional hover exit event. * * @param buttonId The id of the mouse button. This is platform dependent, use the values * defined by [MouseButton.buttonId]. */ fun enqueueMousePress(buttonId: Int) { val mouse = mouseInputState check(!mouse.isButtonPressed(buttonId)) { "Cannot send mouse button down event, button $buttonId is already pressed" } check(isWithinRootBounds(currentMousePosition) || mouse.hasAnyButtonPressed) { "Cannot start a mouse gesture outside the Compose root bounds, mouse position is " + "$currentMousePosition and bounds are ${root.bounds}" } if (partialGesture != null) { enqueueTouchCancel() } // Down time is when the first button is pressed if (mouse.hasNoButtonsPressed) { mouse.downTime = currentTime } mouse.setButtonBit(buttonId) // Exit hovering if necessary if (mouse.isEntered) { mouse.exitHover() } // down/move + press mouse.enqueuePress(buttonId) } /** * Generates a mouse move or hover event to the given [position]. If buttons are pressed, a * move event is generated, otherwise generates a hover event. * * @param position The new mouse position */ fun enqueueMouseMove(position: Offset) { val mouse = mouseInputState // Touch needs to be cancelled, even if mouse is out of bounds if (partialGesture != null) { enqueueTouchCancel() } updateMousePosition(position) val isWithinBounds = isWithinRootBounds(position) if (isWithinBounds && !mouse.isEntered && mouse.hasNoButtonsPressed) { // If not yet hovering and no buttons pressed, enter hover state mouse.enterHover() } else if (!isWithinBounds && mouse.isEntered) { // If hovering, exit now mouse.exitHover() } mouse.enqueueMove() } /** * Updates the mouse position without sending an event. Useful if down, up or scroll events * need to be injected on a different location than the preceding move event. * * @param position The new mouse position */ fun updateMousePosition(position: Offset) { mouseInputState.lastPosition = position // Contrary to touch input, we don't need to store that the position has changed, because // all events that are affected send the current position regardless. } /** * Generates a mouse button released event for the given [buttonId]. This will generate all * required associated events as well, such as an up and hover enter event if it is the last * button being released. * * @param buttonId The id of the mouse button. This is platform dependent, use the values * defined by [MouseButton.buttonId]. */ fun enqueueMouseRelease(buttonId: Int) { val mouse = mouseInputState check(mouse.isButtonPressed(buttonId)) { "Cannot send mouse button up event, button $buttonId is not pressed" } check(partialGesture == null) { "Touch gesture can't be in progress, mouse buttons are down" } mouse.unsetButtonBit(buttonId) mouse.enqueueRelease(buttonId) // When no buttons remaining, enter hover state immediately if (mouse.hasNoButtonsPressed && isWithinRootBounds(currentMousePosition)) { mouse.enterHover() mouse.enqueueMove() } } /** * Generates a mouse hover enter event on the given [position]. * * @param position The new mouse position */ fun enqueueMouseEnter(position: Offset) { val mouse = mouseInputState check(!mouse.isEntered) { "Cannot send mouse hover enter event, mouse is already hovering" } check(mouse.hasNoButtonsPressed) { "Cannot send mouse hover enter event, mouse buttons are down" } check(isWithinRootBounds(position)) { "Cannot send mouse hover enter event, $position is out of bounds" } updateMousePosition(position) mouse.enterHover() } /** * Generates a mouse hover exit event on the given [position]. * * @param position The new mouse position */ fun enqueueMouseExit(position: Offset) { val mouse = mouseInputState check(mouse.isEntered) { "Cannot send mouse hover exit event, mouse is not hovering" } updateMousePosition(position) mouse.exitHover() } /** * Generates a mouse cancel event. Can only be done if no mouse buttons are currently * pressed. Sent automatically if a touch event is sent while mouse buttons are down. */ fun enqueueMouseCancel() { val mouse = mouseInputState check(mouse.hasAnyButtonPressed) { "Cannot send mouse cancel event, no mouse buttons are pressed" } mouse.clearButtonState() mouse.enqueueCancel() } /** * Generates a scroll event on [scrollWheel] by [delta]. Negative values correspond to * rotating the scroll wheel leftward or upward, positive values correspond to rotating the * scroll wheel rightward or downward. */ // TODO(fresen): verify the sign of the horizontal scroll axis (is left negative or positive?) @OptIn(ExperimentalTestApi::class) fun enqueueMouseScroll(delta: Float, scrollWheel: ScrollWheel) { val mouse = mouseInputState // A scroll is always preceded by a move(/hover) event enqueueMouseMove(currentMousePosition) if (isWithinRootBounds(currentMousePosition)) { mouse.enqueueScroll(delta, scrollWheel) } } /** * Generates a key down event for the given [key]. * * @param key The keyboard key to be pushed down. Platform specific. */ fun enqueueKeyDown(key: Key) { val keyboard = keyInputState check(!keyboard.isKeyDown(key)) { "Cannot send key down event, Key($key) is already pressed down." } // TODO(Onadim): Figure out whether key input needs to enqueue a touch cancel. // Down time is the time of the most recent key down event, which is now. keyboard.downTime = currentTime // Add key to pressed keys. keyboard.setKeyDown(key) keyboard.enqueueDown(key) } /** * Generates a key up event for the given [key]. * * @param key The keyboard key to be released. Platform specific. */ fun enqueueKeyUp(key: Key) { val keyboard = keyInputState check(keyboard.isKeyDown(key)) { "Cannot send key up event, Key($key) is not pressed down." } // TODO(Onadim): Figure out whether key input needs to enqueue a touch cancel. // Remove key from pressed keys. keyboard.setKeyUp(key) // Send the up event keyboard.enqueueUp(key) } fun enqueueRotaryScrollHorizontally(horizontalScrollPixels: Float) { // TODO(b/214437966): figure out if ongoing scroll events need to be cancelled. rotaryInputState.enqueueRotaryScrollHorizontally(horizontalScrollPixels) } fun enqueueRotaryScrollVertically(verticalScrollPixels: Float) { // TODO(b/214437966): figure out if ongoing scroll events need to be cancelled. rotaryInputState.enqueueRotaryScrollHorizontally(verticalScrollPixels) } private fun MouseInputState.enterHover() { enqueueEnter() isEntered = true } private fun MouseInputState.exitHover() { enqueueExit() isEntered = false } /** * Sends any and all repeat key events that are required between [currentTime] and [endTime]. * * Mutates the value of [currentTime] in order to send each of the repeat events at exactly the * time it should be sent. * * @param endTime All repeats set to occur before this time will be sent. */ // TODO(b/236623354): Extend repeat key event support to [MainTestClock.advanceTimeBy]. private fun KeyInputState.sendRepeatKeysIfNeeded(endTime: Long) { // Return if there is no key to repeat or if it is not yet time to repeat it. if (repeatKey == null || endTime - downTime < InitialRepeatDelay) return // Initial repeat if (lastRepeatTime <= downTime) { // Not yet had a repeat on this key, but it needs at least the initial one. check(repeatCount == 0) { "repeatCount should be reset to 0 when downTime updates" } repeatCount = 1 lastRepeatTime = downTime + InitialRepeatDelay currentTime = lastRepeatTime enqueueRepeat() } // Subsequent repeats val numRepeats: Int = ((endTime - lastRepeatTime) / SubsequentRepeatDelay).toInt() repeat(numRepeats) { repeatCount += 1 lastRepeatTime += SubsequentRepeatDelay currentTime = lastRepeatTime enqueueRepeat() } } /** * Enqueues a key down event on the repeat key, if there is one. If the repeat key is null, * an [IllegalStateException] is thrown. */ private fun KeyInputState.enqueueRepeat() { val repKey = checkNotNull(repeatKey) { "A repeat key event cannot be sent if the repeat key is null." } keyInputState.enqueueDown(repKey) } /** * Sends all enqueued events and blocks while they are dispatched. If an exception is * thrown during the process, all events that haven't yet been dispatched will be dropped. */ abstract fun flush() protected abstract fun PartialGesture.enqueueDown(pointerId: Int) protected abstract fun PartialGesture.enqueueMove() protected abstract fun PartialGesture.enqueueMoves( relativeHistoricalTimes: List<Long>, historicalCoordinates: List<List<Offset>> ) protected abstract fun PartialGesture.enqueueUp(pointerId: Int) protected abstract fun PartialGesture.enqueueCancel() protected abstract fun MouseInputState.enqueuePress(buttonId: Int) protected abstract fun MouseInputState.enqueueMove() protected abstract fun MouseInputState.enqueueRelease(buttonId: Int) protected abstract fun MouseInputState.enqueueEnter() protected abstract fun MouseInputState.enqueueExit() protected abstract fun MouseInputState.enqueueCancel() protected abstract fun KeyInputState.enqueueDown(key: Key) protected abstract fun KeyInputState.enqueueUp(key: Key) @OptIn(ExperimentalTestApi::class) protected abstract fun MouseInputState.enqueueScroll(delta: Float, scrollWheel: ScrollWheel) protected abstract fun RotaryInputState.enqueueRotaryScrollHorizontally( horizontalScrollPixels: Float ) protected abstract fun RotaryInputState.enqueueRotaryScrollVertically( verticalScrollPixels: Float ) /** * Called when this [InputDispatcher] is about to be discarded, from * [InjectionScope.dispose]. */ fun dispose() { saveState(root) onDispose() } /** * Override this method to take platform specific action when this dispatcher is disposed. * E.g. to recycle event objects that the dispatcher still holds on to. */ protected open fun onDispose() {} } /** * The state of the current gesture. Contains the current position of all pointers and the * down time (start time) of the gesture. For the current time, see [InputDispatcher.currentTime]. * * @param downTime The time of the first down event of this gesture * @param startPosition The position of the first down event of this gesture * @param pointerId The pointer id of the first down event of this gesture */ internal class PartialGesture(val downTime: Long, startPosition: Offset, pointerId: Int) { val lastPositions = mutableMapOf(Pair(pointerId, startPosition)) var hasPointerUpdates: Boolean = false } /** * The current mouse state. Contains the current mouse position, which buttons are pressed, if it * is hovering over the current node and the down time of the mouse (which is the time of the * last mouse down event). */ internal class MouseInputState { var downTime: Long = 0 val pressedButtons: MutableSet<Int> = mutableSetOf() var lastPosition: Offset = Offset.Zero var isEntered: Boolean = false val hasAnyButtonPressed get() = pressedButtons.isNotEmpty() val hasOneButtonPressed get() = pressedButtons.size == 1 val hasNoButtonsPressed get() = pressedButtons.isEmpty() fun isButtonPressed(buttonId: Int): Boolean { return pressedButtons.contains(buttonId) } fun setButtonBit(buttonId: Int) { pressedButtons.add(buttonId) } fun unsetButtonBit(buttonId: Int) { pressedButtons.remove(buttonId) } fun clearButtonState() { pressedButtons.clear() } } /** * The current key input state. Contains the keys that are pressed, the down time of the * keyboard (which is the time of the last key down event), the state of the lock keys and * the device ID. */ internal class KeyInputState { private val downKeys: HashSet<Key> = hashSetOf() var downTime = 0L var repeatKey: Key? = null var repeatCount = 0 var lastRepeatTime = downTime var capsLockOn = false var numLockOn = false var scrollLockOn = false fun isKeyDown(key: Key): Boolean = downKeys.contains(key) fun setKeyUp(key: Key) { downKeys.remove(key) if (key == repeatKey) { repeatKey = null repeatCount = 0 } } fun setKeyDown(key: Key) { downKeys.add(key) repeatKey = key repeatCount = 0 updateLockKeys(key) } /** * Updates lock key state values. * * Note that lock keys may not be toggled in the same way across all platforms. * * Take caps lock as an example; consistently, all platforms turn caps lock on upon the first * key down event, and it stays on after the subsequent key up. However, on some platforms caps * lock will turn off immediately upon the next key down event (MacOS for example), whereas * other platforms (e.g. linux) wait for the next key up event before turning caps lock off. * * By calling this function whenever a lock key is pressed down, MacOS-like behaviour is * achieved. */ // TODO(Onadim): Investigate how lock key toggling is handled in Android, ChromeOS and Windows. @OptIn(ExperimentalComposeUiApi::class) private fun updateLockKeys(key: Key) { when (key) { Key.CapsLock -> capsLockOn = !capsLockOn Key.NumLock -> numLockOn = !numLockOn Key.ScrollLock -> scrollLockOn = !scrollLockOn } } } /** * We don't have any state associated with RotaryInput, but we use a RotaryInputState class for * consistency with the other APIs. */ internal class RotaryInputState /** * The state of an [InputDispatcher], saved when the [GestureScope] is disposed and restored * when the [GestureScope] is recreated. * * @param partialGesture The state of an incomplete gesture. If no gesture was in progress * when the state of the [InputDispatcher] was saved, this will be `null`. * @param mouseInputState The state of the mouse. * @param keyInputState The state of the keyboard. */ internal data class InputDispatcherState( val partialGesture: PartialGesture?, val mouseInputState: MouseInputState, val keyInputState: KeyInputState )
apache-2.0
64a18997947ee9fe3de33bead5f70f32
33.746495
100
0.660828
4.622785
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/util/ComponentUpdater.kt
3
1595
/* * 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.util /** * Stores the previous applied state, and provide ability to update component if the new state is * changed. */ internal class ComponentUpdater { private var updatedValues = mutableListOf<Any?>() fun update(body: UpdateScope.() -> Unit) { UpdateScope().body() } inner class UpdateScope { private var index = 0 /** * Compare [value] with the old one and if it is changed - store a new value and call * [update] */ fun <T : Any?> set(value: T, update: (T) -> Unit) { if (index < updatedValues.size) { if (updatedValues[index] != value) { update(value) updatedValues[index] = value } } else { check(index == updatedValues.size) update(value) updatedValues.add(value) } index++ } } }
apache-2.0
ab96a3b91cd447b0c4fab7a3986f60d2
29.692308
97
0.603762
4.442897
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/grid/LazyGridItemScopeImpl.kt
3
2099
/* * 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.foundation.lazy.grid import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ParentDataModifier import androidx.compose.ui.platform.InspectorInfo import androidx.compose.ui.platform.InspectorValueInfo import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntOffset @OptIn(ExperimentalFoundationApi::class) internal object LazyGridItemScopeImpl : LazyGridItemScope { @ExperimentalFoundationApi override fun Modifier.animateItemPlacement(animationSpec: FiniteAnimationSpec<IntOffset>) = this.then(AnimateItemPlacementModifier(animationSpec, debugInspectorInfo { name = "animateItemPlacement" value = animationSpec })) } private class AnimateItemPlacementModifier( val animationSpec: FiniteAnimationSpec<IntOffset>, inspectorInfo: InspectorInfo.() -> Unit, ) : ParentDataModifier, InspectorValueInfo(inspectorInfo) { override fun Density.modifyParentData(parentData: Any?): Any = animationSpec override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is AnimateItemPlacementModifier) return false return animationSpec != other.animationSpec } override fun hashCode(): Int { return animationSpec.hashCode() } }
apache-2.0
e4c0365d4566c983bfc2e6e007e37267
37.87037
95
0.766556
4.87007
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractFunction/ui/ExtractFunctionParameterTablePanel.kt
4
5468
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce.extractFunction.ui import com.intellij.openapi.util.NlsSafe import com.intellij.ui.components.JBComboBoxLabel import com.intellij.ui.components.editors.JBComboBoxTableCellEditorComponent import com.intellij.util.ui.AbstractTableCellEditor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.Parameter import org.jetbrains.kotlin.idea.refactoring.introduce.ui.AbstractParameterTablePanel import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.types.KotlinType import java.awt.Component import javax.swing.JTable import javax.swing.table.DefaultTableCellRenderer open class ExtractFunctionParameterTablePanel : AbstractParameterTablePanel<Parameter, ExtractFunctionParameterTablePanel.ParameterInfo>() { companion object { const val PARAMETER_TYPE_COLUMN = 2 } class ParameterInfo( originalParameter: Parameter, val isReceiver: Boolean ) : AbstractParameterTablePanel.AbstractParameterInfo<Parameter>(originalParameter) { var type = originalParameter.parameterType init { name = if (isReceiver) KotlinBundle.message("text.receiver") else originalParameter.name } override fun toParameter() = originalParameter.copy(name, type) } override fun createTableModel(): TableModelBase = MyTableModel() override fun createAdditionalColumns() { with(table.columnModel.getColumn(PARAMETER_TYPE_COLUMN)) { headerValue = KotlinBundle.message("text.type") cellRenderer = object : DefaultTableCellRenderer() { private val myLabel = JBComboBoxLabel() override fun getTableCellRendererComponent( table: JTable, value: Any, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int ): Component { @NlsSafe val renderType = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(value as KotlinType) myLabel.text = renderType myLabel.background = if (isSelected) table.selectionBackground else table.background myLabel.foreground = if (isSelected) table.selectionForeground else table.foreground if (isSelected) { myLabel.setSelectionIcon() } else { myLabel.setRegularIcon() } return myLabel } } cellEditor = object : AbstractTableCellEditor() { val myEditorComponent = JBComboBoxTableCellEditorComponent() override fun getCellEditorValue() = myEditorComponent.editorValue override fun getTableCellEditorComponent( table: JTable, value: Any, isSelected: Boolean, row: Int, column: Int ): Component { val info = parameterInfos[row] myEditorComponent.setCell(table, row, column) myEditorComponent.setOptions(*info.originalParameter.getParameterTypeCandidates().toTypedArray()) myEditorComponent.setDefaultValue(info.type) myEditorComponent.setToString { IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(it as KotlinType) } return myEditorComponent } } } } fun init(receiver: Parameter?, parameters: List<Parameter>) { parameterInfos = parameters.mapTo( if (receiver != null) arrayListOf(ParameterInfo(receiver, true)) else arrayListOf() ) { ParameterInfo(it, false) } super.init() } private inner class MyTableModel : TableModelBase() { override fun getColumnCount() = 3 override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? { if (columnIndex == PARAMETER_TYPE_COLUMN) return parameterInfos[rowIndex].type return super.getValueAt(rowIndex, columnIndex) } override fun setValueAt(aValue: Any?, rowIndex: Int, columnIndex: Int) { if (columnIndex == PARAMETER_TYPE_COLUMN) { parameterInfos[rowIndex].type = aValue as KotlinType updateSignature() return } super.setValueAt(aValue, rowIndex, columnIndex) } override fun isCellEditable(rowIndex: Int, columnIndex: Int): Boolean { val info = parameterInfos[rowIndex] return when (columnIndex) { PARAMETER_NAME_COLUMN -> super.isCellEditable(rowIndex, columnIndex) && !info.isReceiver PARAMETER_TYPE_COLUMN -> isEnabled && info.isEnabled && info.originalParameter.getParameterTypeCandidates().size > 1 else -> super.isCellEditable(rowIndex, columnIndex) } } } val selectedReceiverInfo: ParameterInfo? get() = parameterInfos.singleOrNull { it.isEnabled && it.isReceiver } val selectedParameterInfos: List<ParameterInfo> get() = parameterInfos.filter { it.isEnabled && !it.isReceiver } }
apache-2.0
53764165f3a682f780106fabac35fd3a
43.455285
158
0.654901
5.424603
false
false
false
false
krishnan-mani/idea-cloudformation
src/main/kotlin/com/intellij/aws/cloudformation/CloudFormationResolve.kt
1
2733
package com.intellij.aws.cloudformation import com.intellij.psi.PsiFile import com.intellij.psi.PsiElement import com.intellij.openapi.util.text.StringUtil import com.intellij.json.psi.JsonObject import com.intellij.json.psi.JsonStringLiteral import com.intellij.json.psi.JsonProperty public open class CloudFormationResolve() { companion object { public open fun getSectionNode(file: PsiFile, name: String): JsonObject? = CloudFormationPsiUtils.getObjectLiteralExpressionChild(CloudFormationPsiUtils.getRootExpression(file), name) public open fun getTargetName(element: JsonStringLiteral): String = StringUtil.unquoteString(element.text ?: "") public open fun resolveEntity(file: PsiFile, entityName: String, sections: Collection<String>): JsonProperty? { return sections .map { getSectionNode(file, it) } .filterNotNull() .map { it.findProperty(entityName) } .filterNotNull() .firstOrNull() } public open fun getEntities(file: PsiFile, sections: Collection<String>): Set<String> = sections.flatMap { sectionName -> getSectionNode(file, sectionName)?.propertyList?.map { it.name } ?: emptyList() }.toSet() public open fun resolveTopLevelMappingKey(file: PsiFile, mappingName: String, topLevelKey: String): JsonProperty? { val mappingExpression = resolveEntity(file, mappingName, CloudFormationSections.MappingsSingletonList)?.value as? JsonObject return mappingExpression?.findProperty(topLevelKey) } public open fun resolveSecondLevelMappingKey(file: PsiFile, mappingName: String, topLevelKey: String, secondLevelKey: String): PsiElement? { val topLevelKeyExpression = resolveTopLevelMappingKey(file, mappingName, topLevelKey)?.value as? JsonObject return topLevelKeyExpression?.findProperty(secondLevelKey) } public open fun getTopLevelMappingKeys(file: PsiFile, mappingName: String): Array<String>? { val mappingElement = resolveEntity(file, mappingName, CloudFormationSections.MappingsSingletonList) val objectLiteralExpression = mappingElement?.value as? JsonObject return getPropertiesName(objectLiteralExpression?.propertyList) } public open fun getSecondLevelMappingKeys(file: PsiFile, mappingName: String, topLevelKey: String): Array<String>? { val topLevelKeyElement = resolveTopLevelMappingKey(file, mappingName, topLevelKey) val objectLiteralExpression = topLevelKeyElement?.value as? JsonObject return getPropertiesName(objectLiteralExpression?.propertyList) } private fun getPropertiesName(properties: MutableList<JsonProperty>?): Array<String>? = properties?.map { it.name }?.toTypedArray() } }
apache-2.0
1515327c801bce676dc770078f117869
47.803571
144
0.755946
4.862989
false
false
false
false
GunoH/intellij-community
notebooks/notebook-ui/src/org/jetbrains/plugins/notebooks/ui/visualization/NotebookLineMarkerRenderer.kt
2
7272
// 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.plugins.notebooks.ui.visualization import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.VisualPosition import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.ex.RangeMarkerEx import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.impl.view.FontLayoutService import com.intellij.openapi.editor.markup.LineMarkerRendererEx import com.intellij.openapi.editor.markup.RangeHighlighter import java.awt.Graphics import java.awt.Point import java.awt.Rectangle import kotlin.math.max import kotlin.math.min abstract class NotebookLineMarkerRenderer(private val inlayId: Long? = null) : LineMarkerRendererEx { fun getInlayId(): Long? = inlayId override fun getPosition(): LineMarkerRendererEx.Position = LineMarkerRendererEx.Position.CUSTOM protected fun getInlayBounds(editor: EditorEx, linesRange: IntRange) : Rectangle? { val startOffset = editor.document.getLineStartOffset(linesRange.first) val endOffset = editor.document.getLineEndOffset(linesRange.last) val inlays = editor.inlayModel.getBlockElementsInRange(startOffset, endOffset) val inlay = inlays.firstOrNull { it is RangeMarkerEx && it.id == inlayId } return inlay?.bounds } } class NotebookAboveCodeCellGutterLineMarkerRenderer(private val highlighter: RangeHighlighter, inlayId: Long) : NotebookLineMarkerRenderer(inlayId) { override fun paint(editor: Editor, g: Graphics, r: Rectangle) { editor as EditorImpl val lines = IntRange(editor.document.getLineNumber(highlighter.startOffset), editor.document.getLineNumber(highlighter.endOffset)) val inlayBounds = getInlayBounds(editor, lines) ?: return val bottomRectHeight = editor.notebookAppearance.CELL_BORDER_HEIGHT / 2 paintNotebookCellBackgroundGutter(editor, g, r, lines, inlayBounds.y + inlayBounds.height - bottomRectHeight, bottomRectHeight) } } class NotebookBelowCellCellGutterLineMarkerRenderer(private val highlighter: RangeHighlighter, inlayId: Long) : NotebookLineMarkerRenderer(inlayId) { override fun paint(editor: Editor, g: Graphics, r: Rectangle) { editor as EditorImpl val lines = IntRange(editor.document.getLineNumber(highlighter.startOffset), editor.document.getLineNumber(highlighter.endOffset)) val inlayBounds = getInlayBounds(editor, lines) ?: return paintNotebookCellBackgroundGutter(editor, g, r, lines, inlayBounds.y, editor.notebookAppearance.SPACER_HEIGHT) } } class MarkdownCellGutterLineMarkerRenderer(private val highlighter: RangeHighlighter, inlayId: Long) : NotebookLineMarkerRenderer(inlayId) { override fun paint(editor: Editor, g: Graphics, r: Rectangle) { editor as EditorImpl val lines = IntRange(editor.document.getLineNumber(highlighter.startOffset), editor.document.getLineNumber(highlighter.endOffset)) val inlayBounds = getInlayBounds(editor, lines) ?: return paintCellGutter(inlayBounds, lines, editor, g, r) } } class NotebookCellLineNumbersLineMarkerRenderer(private val highlighter: RangeHighlighter) : NotebookLineMarkerRenderer() { override fun paint(editor: Editor, g: Graphics, r: Rectangle) { val lines = IntRange(editor.document.getLineNumber(highlighter.startOffset), editor.document.getLineNumber(highlighter.endOffset)) val visualLineStart = editor.xyToVisualPosition(Point(0, g.clip.bounds.y)).line val visualLineEnd = editor.xyToVisualPosition(Point(0, g.clip.bounds.run { y + height })).line val logicalLineStart = editor.visualToLogicalPosition(VisualPosition(visualLineStart, 0)).line val logicalLineEnd = editor.visualToLogicalPosition(VisualPosition(visualLineEnd, 0)).line g.font = editor.colorsScheme.getFont(EditorFontType.PLAIN).let { it.deriveFont(max(1f, it.size2D - 1f)) } g.color = editor.colorsScheme.getColor(EditorColors.LINE_NUMBERS_COLOR) val notebookAppearance = editor.notebookAppearance var previousVisualLine = -1 // The first line of the cell is the delimiter, don't draw the line number for it. for (logicalLine in max(logicalLineStart, lines.first + 1)..min(logicalLineEnd, lines.last)) { val visualLine = editor.logicalToVisualPosition(LogicalPosition(logicalLine, 0)).line if (previousVisualLine == visualLine) continue // If a region is folded, it draws only the first line number. previousVisualLine = visualLine if (visualLine < visualLineStart) continue if (visualLine > visualLineEnd) break // TODO conversions from document position to Y are expensive and should be cached. val yTop = editor.visualLineToY(visualLine) val lineNumber = logicalLine - lines.first val text: String = lineNumber.toString() val left = ( r.width - FontLayoutService.getInstance().stringWidth(g.fontMetrics, text) - notebookAppearance.LINE_NUMBERS_MARGIN - notebookAppearance.getLeftBorderWidth() ) g.drawString(text, left, yTop + editor.ascent) } } } class NotebookCodeCellBackgroundLineMarkerRenderer(private val highlighter: RangeHighlighter) : NotebookLineMarkerRenderer() { override fun paint(editor: Editor, g: Graphics, r: Rectangle) { editor as EditorImpl val lines = IntRange(editor.document.getLineNumber(highlighter.startOffset), editor.document.getLineNumber(highlighter.endOffset)) val top = editor.offsetToXY(editor.document.getLineStartOffset(lines.first)).y val height = editor.offsetToXY(editor.document.getLineEndOffset(lines.last)).y + editor.lineHeight - top paintNotebookCellBackgroundGutter(editor, g, r, lines, top, height) { paintCaretRow(editor, g, lines) } } } class NotebookTextCellBackgroundLineMarkerRenderer(private val highlighter: RangeHighlighter) : NotebookLineMarkerRenderer() { override fun paint(editor: Editor, g: Graphics, r: Rectangle) { editor as EditorImpl val lines = IntRange(editor.document.getLineNumber(highlighter.startOffset), editor.document.getLineNumber(highlighter.endOffset)) val top = editor.offsetToXY(editor.document.getLineStartOffset(lines.first)).y val height = editor.offsetToXY(editor.document.getLineEndOffset(lines.last)).y + editor.lineHeight - top paintCaretRow(editor, g, lines) val appearance = editor.notebookAppearance appearance.getCellStripeColor(editor, lines)?.let { paintCellStripe(appearance, g, r, it, top, height) } } } class NotebookCellToolbarGutterLineMarkerRenderer(private val highlighter: RangeHighlighter, inlayId: Long) : NotebookLineMarkerRenderer(inlayId) { override fun paint(editor: Editor, g: Graphics, r: Rectangle) { editor as EditorImpl val lines = IntRange(editor.document.getLineNumber(highlighter.startOffset), editor.document.getLineNumber(highlighter.endOffset)) val inlayBounds = getInlayBounds(editor, lines) ?: return paintNotebookCellBackgroundGutter(editor, g, r, lines, inlayBounds.y, inlayBounds.height) } }
apache-2.0
e4ba27a0ab8037c8e82308062dcc25ed
50.58156
149
0.77544
4.386007
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinUsageInfo.kt
4
1846
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.util.descendantsOfType import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.NotNullablePsiCopyableUserDataProperty abstract class KotlinUsageInfo<T : PsiElement> : UsageInfo { constructor(element: T) : super(element) constructor(reference: PsiReference) : super(reference) @Suppress("UNCHECKED_CAST") override fun getElement() = super.getElement() as T? open fun preprocessUsage() {} abstract fun processUsage(changeInfo: KotlinChangeInfo, element: T, allUsages: Array<out UsageInfo>): Boolean protected fun <T: KtElement> T.asMarkedForShortening(): T = apply { isMarked = true } protected fun KtElement.flushElementsForShorteningToWaitList(options: ShortenReferences.Options = ShortenReferences.Options.ALL_ENABLED) { for (element in descendantsOfType<KtElement>()) { if (element.isMarked) { element.isMarked = false element.addToShorteningWaitSet(options) } } } companion object { private var KtElement.isMarked: Boolean by NotNullablePsiCopyableUserDataProperty( key = Key.create("MARKER_FOR_SHORTENING"), defaultValue = false, ) } }
apache-2.0
aa9d28765be7a69ac2a143e517218a49
39.130435
158
0.742145
4.733333
false
false
false
false
rei-m/HBFav_material
app/src/main/kotlin/me/rei_m/hbfavmaterial/extension/RxExtension.kt
1
2025
/* * Copyright (c) 2017. Rei Matsushita * * 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 me.rei_m.hbfavmaterial.extension import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers fun Completable.subscribeAsync(onSuccess: () -> Unit, onFailure: (Throwable) -> Unit = {}, onEventFinished: () -> Unit = {}): Disposable { return subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .doFinally(onEventFinished) .subscribe(onSuccess, onFailure) } fun <T> Single<T>.subscribeAsync(onSuccess: (T) -> Unit, onFailure: (Throwable) -> Unit = {}, onEventFinished: () -> Unit = {}): Disposable { return subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .doFinally(onEventFinished) .subscribe(onSuccess, onFailure) } fun <T> Observable<T>.subscribeAsync(onSuccess: (T) -> Unit, onFailure: (Throwable) -> Unit = {}, onEventFinished: () -> Unit = {}): Disposable { return subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .doFinally(onEventFinished) .subscribe(onSuccess, onFailure) } fun <T> Observable<T>.subscribeBus(onSuccess: (T) -> Unit): Disposable { return observeOn(AndroidSchedulers.mainThread()) .subscribe(onSuccess) }
apache-2.0
c774db765e755794dac0007cb6dfd901
42.085106
145
0.710123
4.480088
false
false
false
false
nsk-mironov/sento
sento-compiler/src/main/kotlin/io/mironov/sento/compiler/SentoCompiler.kt
1
2061
package io.mironov.sento.compiler import io.mironov.sento.compiler.common.Naming import io.mironov.sento.compiler.generator.ContentGeneratorFactory import io.mironov.sento.compiler.model.BindingSpec import org.apache.commons.io.FileUtils import org.slf4j.LoggerFactory import java.io.File class SentoCompiler() { private val logger = LoggerFactory.getLogger(SentoCompiler::class.java) fun compile(options: SentoOptions) { logger.info("Starting sento compiler:").apply { options.libs.forEach { logger.info("Referenced classes - {}", it) } options.libs.forEach { logger.info("Input classes - {}", it) } logger.info("Output directory - {}", options.output) } val registry = ClassRegistryFactory.create(options) val environment = GenerationEnvironment(registry, Naming()) logger.info("Successfully created class registry:") logger.info("Referenced classes count: {}", registry.references.size) logger.info("Input classes count: {}", registry.inputs.size) options.inputs.forEach { logger.info("Copying files from {} to {}", it.absolutePath, options.output.absolutePath) FileUtils.copyDirectory(it, options.output) } val factory = ContentGeneratorFactory.from(environment) val bindings = registry.inputs.map { BindingSpec.from(registry.resolve(it, false), environment) }.filter { !it.bindings.isEmpty() || !it.listeners.isEmpty() || !it.views.isEmpty() } bindings.forEach { factory.createBinding(it).generate(environment).forEach { logger.info("Writing generated class {}", File(options.output, it.path)) FileUtils.writeByteArrayToFile(File(options.output, it.path), it.content) } } factory.createFactory(bindings).generate(environment).forEach { logger.info("Writing generated class - {}", File(options.output, it.path)) FileUtils.writeByteArrayToFile(File(options.output, it.path), it.content) } logger.info("Successfully created bindings for {} classes", bindings.size) } }
apache-2.0
0957be368198ce0235a85df2bdfc071d
35.157895
110
0.709364
4.189024
false
false
false
false
jwren/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/inspections/AbstractKotlinInspection.kt
3
2247
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.codeInspection.util.InspectionMessage import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.kotlin.asJava.unwrapped abstract class AbstractKotlinInspection : LocalInspectionTool() { fun ProblemsHolder.registerProblemWithoutOfflineInformation( element: PsiElement, @InspectionMessage description: String, isOnTheFly: Boolean, highlightType: ProblemHighlightType, vararg fixes: LocalQuickFix ) { registerProblemWithoutOfflineInformation(element, description, isOnTheFly, highlightType, null, *fixes) } fun ProblemsHolder.registerProblemWithoutOfflineInformation( element: PsiElement, @InspectionMessage description: String, isOnTheFly: Boolean, highlightType: ProblemHighlightType, range: TextRange?, vararg fixes: LocalQuickFix ) { if (!isOnTheFly && highlightType == ProblemHighlightType.INFORMATION) return val problemDescriptor = manager.createProblemDescriptor(element, range, description, highlightType, isOnTheFly, *fixes) registerProblem(problemDescriptor) } } @Suppress("unused") fun Array<ProblemDescriptor>.registerWithElementsUnwrapped( holder: ProblemsHolder, isOnTheFly: Boolean, quickFixSubstitutor: ((LocalQuickFix, PsiElement) -> LocalQuickFix?)? = null ) { forEach { problem -> @Suppress("UNCHECKED_CAST") val originalFixes = problem.fixes as? Array<LocalQuickFix> ?: LocalQuickFix.EMPTY_ARRAY val newElement = problem.psiElement.unwrapped ?: return@forEach val newFixes = quickFixSubstitutor?.let { subst -> originalFixes.mapNotNull { subst(it, newElement) }.toTypedArray() } ?: originalFixes val descriptor = holder.manager.createProblemDescriptor(newElement, problem.descriptionTemplate, isOnTheFly, newFixes, problem.highlightType) holder.registerProblem(descriptor) } }
apache-2.0
c9513fff94bd2c0b4aeea41298d24d03
41.396226
158
0.734312
5.375598
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/runtime/basic/simd.kt
4
2768
/* * Copyright 2010-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 runtime.basic.simd import kotlin.test.* @Test fun runTest() { testBoxingSimple() testBoxing() testSetGet() testString() testOOB() testEquals() testHash() testDefaultValue() } class Box<T>(t: T) { var value = t } class UnalignedC(t: Vector128) { var smth = 1 var value = t } fun testBoxingSimple() { val v = vectorOf(1f, 3.162f, 10f, 31f) val box: Box<Vector128> = Box<Vector128>(v) assertEquals(v, box.value, "testBoxingSimple FAILED") } fun testBoxing() { var u = UnalignedC(vectorOf(0, 1, 2, 3)) assertEquals(3, u.value.getIntAt(3)) u.value = vectorOf(0f, 1f, 2f, 3f) assertEquals(vectorOf(0f, 1f, 2f, 3f), u.value, "testBoxing FAILED") } fun testSetGet() { var v4any = vectorOf(0, 1, 2, 3) (0 until 4).forEach { assertEquals(it, v4any.getIntAt(it), "testSetGet FAILED for <4 x i32>") } // type punning: set the variable to another runtime type val a = arrayOf(1f, 3.162f, 10f, 31f) v4any = vectorOf(a[0], a[1], a[2], a[3]) (0 until 4).forEach { assertEquals(a[it], v4any.getFloatAt(it), "testSetGet FAILED for <4 x float>") } } fun testString() { val v4i = vectorOf(100, 1024, Int.MAX_VALUE, Int.MIN_VALUE) assertEquals("(0x64, 0x400, 0x7fffffff, 0x80000000)", v4i.toString(), "testString FAILED") } fun testOOB() { val f = vectorOf(1f, 3.162f, 10f, 31f) println("f.getByteAt(15) is OK ${f.getByteAt(15)}") assertFailsWith<IndexOutOfBoundsException>("f.getByteAt(16) should fail") { f.getByteAt(16) } assertFailsWith<IndexOutOfBoundsException>("f.getIntAt(-1) should fail") { f.getIntAt(-1) } assertFailsWith<IndexOutOfBoundsException>("f.getFloatAt(4) should fail") { f.getFloatAt(4) } } fun testEquals() { var v1 = vectorOf(-1f, 0f, 0f, -7f) var v2 = vectorOf(1f, 4f, 3f, 7f) assertEquals(false, v1 == v2) assertEquals(false, v1.equals(v2)) assertEquals(false, v1.equals(Any())) assertEquals(true, v2 == v2) v1 = v2 assertEquals(true, v1 == v2) } fun testHash() { val h1 = vectorOf(1f, 4f, 3f, 7f).hashCode() val h2 = vectorOf(3f, 7f, 1f, 4f).hashCode() assertEquals(false, h1 == h2) val i = 654687 assertEquals(true, vectorOf(0, 0, i, 0).hashCode() == i.hashCode()) // exploit little endianness assertEquals(true, vectorOf(1, 0, 0, 0).hashCode() == vectorOf(0, 0, 31, 0).hashCode()) } private fun funDefaultValue(v: Vector128 = vectorOf(1.0f, 2.0f, 3.0f, 4.0f)) = v fun testDefaultValue() { assertEquals(vectorOf(1.0f, 2.0f, 3.0f, 4.0f), funDefaultValue()) }
apache-2.0
3db3301731885e75de9265b4dd3055ab
25.615385
106
0.636922
2.904512
false
true
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/utils/junix/lspci/LsPci.kt
2
1071
package com.github.kerubistan.kerub.utils.junix.lspci import com.github.kerubistan.kerub.host.execute import com.github.kerubistan.kerub.model.hardware.PciDevice import org.apache.sshd.client.session.ClientSession object LsPci { @JvmStatic val doublequote = "\"" fun execute(session: ClientSession): List<PciDevice> { return parse(session.execute("lspci -mm")) } @JvmStatic fun parse(output: String): List<PciDevice> = output.trim().lines().toList().map { parseLine(it) } @JvmStatic fun parseLine(line: String): PciDevice { return PciDevice( address = line.substringBefore(" "), vendor = line.substringAfter(doublequote) .substringAfter(doublequote) .substringAfter(doublequote) .substringBefore(doublequote), devClass = line.substringAfter(doublequote) .substringBefore(doublequote), device = line.substringAfter(doublequote) .substringAfter(doublequote) .substringAfter(doublequote) .substringAfter(doublequote) .substringAfter(doublequote) .substringBefore(doublequote) ) } }
apache-2.0
27a7e563e136f02a61fd3fd4103d5d92
27.972973
59
0.733894
3.630508
false
false
false
false
vovagrechka/fucking-everything
1/global-menu/src/main/java/botinok.kt
1
40992
package vgrechka.botinok import javafx.application.Application import javafx.application.Platform import javafx.collections.FXCollections import javafx.event.EventHandler import javafx.geometry.Insets import javafx.geometry.Orientation import javafx.geometry.Pos import javafx.geometry.Rectangle2D import javafx.scene.Node import javafx.scene.Scene import javafx.scene.canvas.Canvas import javafx.scene.control.* import javafx.scene.input.* import javafx.scene.layout.* import javafx.scene.paint.Color import javafx.stage.Modality import javafx.stage.Stage import javafx.stage.WindowEvent import org.jnativehook.GlobalScreen import org.jnativehook.keyboard.NativeKeyAdapter import org.jnativehook.keyboard.NativeKeyEvent import org.jnativehook.mouse.NativeMouseEvent import org.springframework.context.annotation.AnnotationConfigApplicationContext import vgrechka.* import java.awt.Rectangle import java.awt.Robot import java.awt.Toolkit.getDefaultToolkit import java.awt.event.InputEvent import java.io.File import java.util.* import java.util.logging.Level import java.util.logging.Logger import javax.imageio.ImageIO import kotlin.concurrent.thread import kotlin.properties.Delegates.notNull import kotlin.system.exitProcess // TODO:vgrechka Sanity checks during model loading (e.g. that positions are correct) // Show a message if something is messed up class StartBotinok : Application() { var primaryStage by notNullOnce<Stage>() var bananas by notNullOnce<goBananas2>() var handleEnterKeyInPlaySelector by notNull<() -> Unit>() var afterPlayEditorOpened = {} @Volatile var running = false @Volatile var stopRequested = false val robot = Robot() val tmpImgPath = "${FilePile.tmpDirPath}/d2185122-750e-432d-8d88-fad71b5021b5.png".replace("\\", "/") override fun start(primaryStage: Stage) { run { backPlatform.springctx = AnnotationConfigApplicationContext(BotinokProdAppConfig::class.java) seed() } JFXPile.installUncaughtExceptionHandler_errorAlert() installKeyboardHook() primaryStage.addEventHandler(WindowEvent.WINDOW_HIDDEN) {e-> exitProcess(0) } this.primaryStage = primaryStage primaryStage.width = 1500.0 primaryStage.height = 750.0 openPlaySelector() primaryStage.setOnShown { simulateSomeUserActions() } primaryStage.setOnCloseRequest { if (maybeAskAndSave().cancelled) { it.consume() } } primaryStage.show() } var dirty = false set(value) { if (field != value) { field = value updateStageTitle() } } class MaybeAskAndSaveResult(val cancelled: Boolean) private fun maybeAskAndSave(): MaybeAskAndSaveResult { if (dirty) { exhaustive = when (JFXPile.yesNoCancel("Should I save your shit?")) { JFXPile.YesNoCancelResult.YES -> { action_save() } JFXPile.YesNoCancelResult.NO -> { } JFXPile.YesNoCancelResult.CANCEL -> { return MaybeAskAndSaveResult(cancelled = true) } } } return MaybeAskAndSaveResult(cancelled = false) } fun openPlaySelector() { backPlatform.tx { primaryStage.title = "Botinok" class Item(val play: BotinokPlay) { override fun toString() = play.name } val listView = ListView<Item>() val plays = botinokPlayRepo.findAll() listView.items = FXCollections.observableArrayList(plays.map {Item(it)}) handleEnterKeyInPlaySelector = { listView.selectionModel.selectedItem?.play?.let { action_openPlayEditor(it) } } listView.setOnKeyPressed { if (it.code == KeyCode.ENTER) { handleEnterKeyInPlaySelector() } } listView.setOnMouseClicked { if (it.button == MouseButton.PRIMARY && it.clickCount == 2) { handleEnterKeyInPlaySelector() } } JFXPile.later { listView.selectionModel.select(0) listView.requestFocus() } primaryStage.scene = Scene(listView) } } fun action_openPlayEditor(_play: BotinokPlay) { backPlatform.tx { bananas = goBananas2(botinokPlayRepo.findOne(_play.id)!!) updateStageTitle() val arenas = bananas.playNode.iplay.arenas arenas.sortBy {it.position} for (arena in arenas) { val arenaNode = PussyNode.newArena(arena, bananas.playNode.iplay) val regions = arena.regions regions.sortBy {it.position} for (region in regions) { PussyNode.newRegion(region, arenaNode.iarena) } val pointers = arena.pointers pointers.sortBy {it.position} for (pointer in pointers) { PussyNode.newPointer(pointer, arenaNode.iarena) } } val rootItems = bananas.playNode.treeItem.children if (rootItems.isNotEmpty()) { val arenaItem = rootItems.first() bananas.navigationTreeView.selectionModel.select(arenaItem) if (arenaItem.children.isNotEmpty()) { arenaItem.isExpanded = true } } afterPlayEditorOpened() } } private fun updateStageTitle() { primaryStage.title = "Botinok - ${bananas.playNode.iplay.entity.name}${dirty.thenElseEmpty{" *"}}" } private fun seed() { if (false) { backPlatform.tx { run { val playName = "Hamlet" if (botinokPlayRepo.findByName(playName) == null) { botinokPlayRepo.save(newBotinokPlay(name = playName, pile = "{}")) } } run { val playName = "Macbeth" if (botinokPlayRepo.findByName(playName) == null) { botinokPlayRepo.save(newBotinokPlay(name = playName, pile = "{}")) } } } } } inner class goBananas2(_play: BotinokPlay) { var someTextField by notNull<TextField>() var navigationTreeView by notNull<TreeView<Any>>() var mainSplitPane by notNull<SplitPane>() var detailsPane by notNull<AnchorPane>() var currentContextMenu: ContextMenu? = null var selectedRegionHandles = setOf<RegionHandle>() var nextInitialRegionLocationIndex = 0 var canvasContextMenu by notNull<ContextMenu>() var boxContextMenu by notNull<ContextMenu>() var operationStartRegionParams by notNull<Box>() var operationStartMouseX = 0.0 var operationStartMouseY = 0.0 // val rootTreeItem: FuckingTreeItem = TreeItem() var drawingAreaStackPane by notNull<StackPane>() val pointerWidth = 17 val pointerHeight = 25 var leftSplitPane: SplitPane val statusLabel: Label var runMenuItem by notNullOnce<MenuItem>() var stopMenuItem by notNullOnce<MenuItem>() val playNode: PussyNode inner class RegionLocation(val x: Int, val y: Int, val w: Int, val h: Int) val initialRegionLocations = listOf( RegionLocation(x = 20, y = 20, w = 150, h = 50), RegionLocation(x = 100, y = 100, w = 50, h = 150) ) fun isHit(r: BotinokRegion, testX: Double, testY: Double): Boolean { return testX >= r.x && testX <= r.x + r.w - 1 && testY >= r.y && testY <= r.y + r.h - 1 } fun isHit(p: BotinokPointer, testX: Double, testY: Double): Boolean { return testX >= p.x && testX <= p.x + pointerWidth - 1 && testY >= p.y && testY <= p.y + pointerWidth - 1 } val canvas by relazy { detailsPane.children.clear() val scrollPane = ScrollPane() stretch(scrollPane) detailsPane.children += scrollPane val canvas = Canvas(displayedArenaNode().image.width, displayedArenaNode().image.height) drawingAreaStackPane = StackPane() drawingAreaStackPane.children += canvas scrollPane.content = drawingAreaStackPane canvas.addEventHandler(MouseEvent.MOUSE_PRESSED) {e-> if (e.button == MouseButton.PRIMARY) { // noise("MOUSE_PRESSED: e.x = ${e.x}; e.y = ${e.y}") hideContextMenus() val hitRegionNode: PussyNode.IRegion? = run { o@for (iregion in displayedArenaNode().regionNodes) { for (handle in RegionHandle.values()) { if (handle.rectForRegion(iregion.entity).contains(e.x, e.y)) { selectedRegionHandles = setOf(handle) return@run iregion } } if (isHit(iregion.entity, e.x, e.y)) { selectedRegionHandles = RegionHandle.values().toSet() return@run iregion } } null } if (hitRegionNode != null) { selectTreeItem(hitRegionNode.node.treeItem) operationStartRegionParams = Box(hitRegionNode.entity.x, hitRegionNode.entity.y, hitRegionNode.entity.w, hitRegionNode.entity.h) operationStartMouseX = e.x operationStartMouseY = e.y // noise("operationStartMouseX = $operationStartMouseX; operationStartMouseY = $operationStartMouseY") } else { val hitPointerNode: PussyNode.IPointer? = displayedArenaNode().pointerNodes.find { val p = it.entity val pointerRect = Rectangle2D(p.x.toDouble(), p.y.toDouble(), pointerWidth.toDouble(), pointerHeight.toDouble()) pointerRect.contains(e.x, e.y) } if (hitPointerNode != null) { selectTreeItem(hitPointerNode.node.treeItem) operationStartRegionParams = Box(hitPointerNode.entity.x, hitPointerNode.entity.y, -123, -123) operationStartMouseX = e.x operationStartMouseY = e.y } else { selectTreeItem(displayedArenaNode().node.treeItem) } } } drawArena() } canvas.addEventHandler(MouseEvent.MOUSE_RELEASED) {e-> drawArena() } canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED) {e-> if (e.button == MouseButton.PRIMARY) { // noise("MOUSE_DRAGGED: e.x = ${e.x}; e.y = ${e.y}") fun updateShit() { dirty = true drawArena() } val dx = Math.round(e.x - operationStartMouseX).toInt() val dy = Math.round(e.y - operationStartMouseY).toInt() val selectedRegion = selectedRegionNode() if (selectedRegion != null) { // noise("dx = $dx; dy = $dy") val dragMutators = selectedRegionHandles.flatMap{it.dragMutators}.toSet() val points = BoxPoints(operationStartRegionParams.x, operationStartRegionParams.y, operationStartRegionParams.x + operationStartRegionParams.w - 1, operationStartRegionParams.y + operationStartRegionParams.h - 1) dragMutators.forEach {it.mutate(points, dx, dy)} val en = selectedRegion.entity en.x = points.minX en.y = points.minY en.w = points.maxX - points.minX + 1 en.h = points.maxY - points.minY + 1 updateShit() } else { val selectedPointer = selectedPointerNode() if (selectedPointer != null) { val en = selectedPointer.entity en.x = operationStartRegionParams.x + dx en.y = operationStartRegionParams.y + dy updateShit() } } } } canvas } init { val vbox = VBox() vbox.children += MenuBar()-{o-> o.menus += Menu("_File")-{o-> o.addItem("_Save") {action_save()} o.addItem("_Quit") {action_quit()} } o.menus += Menu("_Play")-{o-> runMenuItem = o.addItem("_Run") {action_run()} stopMenuItem = o.addItem("_Stop") {action_stop()} stopMenuItem.isDisable = true o.addItem("_Properties...") {action_playProperties()} } o.menus += Menu("_Tools")-{o-> o.addItem("_Mess Around") {action_messAround()} } } mainSplitPane = SplitPane() vbox.children += mainSplitPane statusLabel = Label() statusLabel.padding = Insets(5.0) resetStatusLabel() vbox.children += statusLabel VBox.setVgrow(mainSplitPane, Priority.ALWAYS) mainSplitPane.setDividerPosition(0, 0.2) leftSplitPane = SplitPane() leftSplitPane.orientation = Orientation.VERTICAL navigationTreeView = TreeView() leftSplitPane.items += navigationTreeView mainSplitPane.items += leftSplitPane detailsPane = AnchorPane() mainSplitPane.items += detailsPane navigationTreeView.setOnMouseClicked { currentContextMenu?.hide() currentContextMenu = null } navigationTreeView.setOnContextMenuRequested {e-> makeTreeContextMenu(e) } navigationTreeView.selectionModel.selectedItemProperty().addListener {_, oldValue, newValue -> handleTreeSelectionChanged(oldValue, newValue) } navigationTreeView.isShowRoot = false navigationTreeView.setCellFactory { object : TreeCell<Any>() { override fun updateItem(item: Any?, empty: Boolean) { super.updateItem(item, empty) if (item == null) { text = "" graphic = null return } // this.style = "-fx-text-fill: red; -fx-font-weight: bold;" text = item.toString() graphic = imf() //EmojiOneView(EmojiOne.AIRPLANE) } } } playNode = PussyNode.newPlay(_play) navigationTreeView.root = playNode.treeItem navigationTreeView.root.isExpanded = true primaryStage.scene = Scene(vbox) } fun resetStatusLabel() { statusLabel.text = "Fucking around? :)" } private fun makeTreeContextMenu(e: ContextMenuEvent) { val treeItem = navigationTreeView.selectionModel.selectedItem val menu = ContextMenu() val node = treeItem.value as PussyNode exhaustive=when (node.type) { PussyNode.Type.ARENA -> { addRenameMenuItem(menu, node) addMoveMenuItems(menu, node) menu.addItem("New Region", this::action_newRegion) menu.addItem("New Pointer", this::action_newPointer) menu.items += SeparatorMenuItem() addDeleteMenuItem(menu, node) } PussyNode.Type.REGION -> { addRenameMenuItem(menu, node) addDeleteMenuItem(menu, node) } PussyNode.Type.POINTER -> { addRenameMenuItem(menu, node) addDeleteMenuItem(menu, node) } PussyNode.Type.PLAY -> wtf("cff6704f-dee7-4ddb-92fd-fe0c0de0de50") } if (menu.items.isNotEmpty()) { menu.show(navigationTreeView, e.screenX, e.screenY) currentContextMenu = menu } } private fun addMoveMenuItems(menu: ContextMenu, node: PussyNode) { // TODO:vgrechka Generalize. Currently works only for arenas val iarena = node.iarena val treeItem = node.treeItem fun move(delta: Int) { run { // Entities val arena = iarena.entity val play = bananas.playNode.iplay.entity val index = play.arenas.indexOfOrNull(arena) ?: wtf("db8f6365-cf88-494f-8f6a-7a07b11c01f5") val a = play.arenas[index] play.arenas[index] = play.arenas[index + delta] play.arenas[index + delta] = a val p = play.arenas[index].position play.arenas[index].position = play.arenas[index + delta].position play.arenas[index + delta].position = p val n = playNode.childNodes[index] playNode.childNodes[index] = playNode.childNodes[index + delta] playNode.childNodes[index + delta] = n } run { // Tree val rootTreeItem = playNode.treeItem val index = rootTreeItem.children.indexOfOrNull(treeItem) ?: wtf("5df53fb4-534a-49df-832d-ee31043c7f19") val tmp = rootTreeItem.children[index] rootTreeItem.children[index] = rootTreeItem.children[index + delta] rootTreeItem.children[index + delta] = tmp navigationTreeView.selectionModel.clearSelection() selectTreeItem(treeItem) } dirty = true } if (treeItem !== treeItem.parent.children.first()) menu.addItem("Move Up") {move(-1)} if (treeItem !== treeItem.parent.children.last()) menu.addItem("Move Down") {move(+1)} } private fun addDeleteMenuItem(menu: ContextMenu, node: PussyNode) { menu.addItem("Delete") { val entity = node.entity val collection = when (entity) { is BotinokArena -> entity.play.arenas is BotinokRegion -> entity.arena.regions is BotinokPointer -> entity.arena.pointers else -> wtf("4e674ed4-423b-4bc5-9431-bc62692f968a") } val indexToDelete = collection.indexOf(entity) collection.removeAt(indexToDelete) for (index in indexToDelete..collection.lastIndex) { val x = collection[index] val positionProperty = when (x) { // `let` here is a workaround for https://youtrack.jetbrains.com/issue/KT-17799 is BotinokArena -> x.let {it::position} is BotinokRegion -> x.let {it::position} is BotinokPointer -> x.let {it::position} else -> wtf("22a2f24c-2395-4ad8-806e-70fc3f10c7ec") } positionProperty.set(positionProperty.get() - 1) } node.parent!!.childNodes.remove(node) node.treeItem.parent.children -= node.treeItem dirty = true } } fun addRenameMenuItem(menu: ContextMenu, node: PussyNode) { menu.addItem("Rename") { val entity = node.entity val nameProperty = BotinokPile.entityNameProperty(entity) JFXPile.inputBox("So, name?", nameProperty.get())?.let { nameProperty.set(it) val parentChildren = node.treeItem.parent.children val index = parentChildren.indexOf(node.treeItem) parentChildren.removeAt(index) parentChildren.add(index, node.treeItem) selectTreeItem(node.treeItem) dirty = true } } } private fun hideContextMenus() { // TODO:vgrechka ... // canvasContextMenu.hide() // boxContextMenu.hide() } fun selectTreeItem(treeItem: TreeItem<out Any>) { @Suppress("UNCHECKED_CAST") navigationTreeView.selectionModel.select(treeItem as BotinokTreeItem) } fun handleTreeSelectionChanged(oldItem: BotinokTreeItem?, newItem: BotinokTreeItem?) { if (leftSplitPane.items.size > 1) leftSplitPane.items.subList(1, leftSplitPane.items.size).clear() if (newItem == null) { detailsPane.children.clear() relazy.reset(this::canvas) return } if (oldItem?.regionNode != selectedRegionNode()) { selectedRegionHandles = RegionHandle.values().toSet() } val node = newItem.value as PussyNode val type = node.type if (type == PussyNode.Type.POINTER) { val pileTextArea = TextArea() leftSplitPane.items += pileTextArea leftSplitPane.setDividerPosition(0, 0.8) pileTextArea.text = node.ipointer.entity.pile pileTextArea.textProperty().addListener {_, _, newValue-> node.ipointer.entity.pile = newValue dirty = true } } drawArena() } fun drawArena() { val gc = canvas.graphicsContext2D gc.drawImage(displayedArenaNode().image, 0.0, 0.0) for (iregion in displayedArenaNode().regionNodes) { val darkPaint = Color(0.5, 0.0, 0.0, 1.0) val brightPaint = Color(1.0, 0.0, 0.0, 1.0) val isFocused = selectedRegionNode() === iregion gc.stroke = when { isFocused -> darkPaint else -> brightPaint } val b = BotinokPile gc.lineWidth = b.boxEdgeSize gc.strokeRect(iregion.entity.x.toDouble() - b.boxEdgeSize / 2, iregion.entity.y.toDouble() - b.boxEdgeSize / 2, iregion.entity.w.toDouble() + b.boxEdgeSize, iregion.entity.h.toDouble() + b.boxEdgeSize) if (isFocused) { for (handle in RegionHandle.values()) { gc.fill = when { handle in selectedRegionHandles -> brightPaint else -> darkPaint } val rect = handle.rectForRegion(iregion.entity) gc.fillRect(rect.minX, rect.minY, rect.width, rect.height) } } } for (ipointer in displayedArenaNode().pointerNodes) { val isFocused = selectedPointerNode() === ipointer val w = pointerWidth.toDouble() val h = pointerHeight.toDouble() val x0 = ipointer.entity.x.toDouble() val y0 = ipointer.entity.y.toDouble() val x1 = x0 + w - 1 val y1 = y0 + h - 1 // gc.fill = Color(0.0, 0.0, 1.0, 0.2) // gc.fillRect(x0, y0, w, h) val paint = when { isFocused -> Color(1.0, 0.0, 0.0, 1.0) else -> Color(1.0, 0.0, 0.0, 1.0) } gc.fill = paint gc.beginPath() gc.moveTo(x0, y0) gc.lineTo(x1, y0 + (y1 - y0) * 0.70) gc.lineTo(x0 + (x1 - x0) * 0.35, y0 + (y1 - y0) * 0.7) gc.lineTo(x0, y1) gc.closePath() gc.fill() gc.lineWidth = 4.0 gc.stroke = paint gc.beginPath() gc.lineTo(x0 + (x1 - x0) * 0.40, y0 + (y1 - y0) * 0.7) gc.lineTo(x0 + (x1 - x0) * 0.60, y1) gc.closePath() gc.fill() gc.stroke() } } fun action_newRegion() { try { val arenaNode = displayedArenaNode() val xywh = initialRegionLocations[nextInitialRegionLocationIndex] if (++nextInitialRegionLocationIndex > initialRegionLocations.lastIndex) nextInitialRegionLocationIndex = 0 val newRegion = newBotinokRegion(name = "Region ${arenaNode.entity.regions.size + 1}", x = xywh.x, y = xywh.y, w = xywh.w, h = xywh.h, arena = arenaNode.entity, position = arenaNode.entity.regions.size, pile = "{}") arenaNode.entity.regions.add(newRegion) dirty = true val regionNode = PussyNode.newRegion(newRegion, arenaNode) arenaNode.node.treeItem.expandedProperty().set(true) navigationTreeView.selectionModel.clearSelection() navigationTreeView.selectionModel.select(regionNode.treeItem) } catch (e: Throwable) { e.printStackTrace() } } fun action_newPointer() { // TODO:vgrechka Dedupe try { val arenaNode = displayedArenaNode() val newPointer = newBotinokPointer(name = "Pointer ${arenaNode.entity.pointers.size + 1}", x = 50, y = 50, pile = "{}", language = "JavaScript", script = "// Fuck you", arena = arenaNode.entity, position = arenaNode.entity.pointers.size) arenaNode.entity.pointers.add(newPointer) dirty = true val pointerNode = PussyNode.newPointer(newPointer, arenaNode) arenaNode.node.treeItem.expandedProperty().set(true) navigationTreeView.selectionModel.clearSelection() navigationTreeView.selectionModel.select(pointerNode.treeItem) } catch (e: Throwable) { e.printStackTrace() } } fun displayedArenaNode(): PussyNode.IArena { val treeItem = selectedTreeItem()!! val node = treeItem.value as PussyNode return when (node.type) { PussyNode.Type.ARENA -> node.iarena PussyNode.Type.REGION -> node.parent!!.iarena PussyNode.Type.POINTER -> node.parent!!.iarena PussyNode.Type.PLAY -> wtf("09eb5e83-448b-4b27-98fd-0ba002db4275") } } fun selectedRegionNode(): PussyNode.IRegion? { return selectedTreeItem()?.regionNode } fun selectedPointerNode(): PussyNode.IPointer? { return selectedTreeItem()?.pointerNode } val BotinokTreeItem.regionNode: PussyNode.IRegion? get() { val node = this.value as PussyNode? if (node != null) if (node.type == PussyNode.Type.REGION) return node.iregion return null } val BotinokTreeItem.pointerNode: PussyNode.IPointer? get() { val node = this.value as PussyNode? if (node != null) if (node.type == PussyNode.Type.POINTER) return node.ipointer return null } fun selectedTreeItem(): BotinokTreeItem? = navigationTreeView.selectionModel.selectedItem } private fun stretch(node: Node) { AnchorPane.setTopAnchor(node, 0.0) AnchorPane.setRightAnchor(node, 0.0) AnchorPane.setBottomAnchor(node, 0.0) AnchorPane.setLeftAnchor(node, 0.0) } private fun action_quit() { if (!maybeAskAndSave().cancelled) { primaryStage.close() } } private fun installKeyboardHook() { val logger = Logger.getLogger(GlobalScreen::class.java.`package`.name) logger.level = Level.WARNING logger.useParentHandlers = false GlobalScreen.registerNativeHook() GlobalScreen.addNativeKeyListener(object : NativeKeyAdapter() { override fun nativeKeyPressed(e: NativeKeyEvent) { try { if (e.modifiers.and(NativeMouseEvent.CTRL_L_MASK) == NativeMouseEvent.CTRL_L_MASK) { if (e.keyCode == NativeKeyEvent.VC_2) { action_takeScreenshot() } } } catch(e: Throwable) { e.printStackTrace() } } }) } private inner class simulateSomeUserActions { init {thread {fuck1()}} fun fuck1() { Thread.sleep(500) JFXPile.later {handleEnterKeyInPlaySelector()} } // fun fuck3() { // afterPlayEditorOpened = { // val pointerTreeItem = bananas.selectedArenaNode().treeItem.children // .find {it.asOfEntityType<BotinokPointer>() != null} // ?: wtf("228ade45-63d1-4aab-966d-2a8ddc0fedec") // bananas.navigationTreeView.selectionModel.select(pointerTreeItem as FuckingTreeItem) // } // Thread.sleep(500) // JFXStuff.later {handleEnterKeyInPlaySelector()} // } // fun fuck2() { // Thread.sleep(500) // JFXStuff.later {handleEnterKeyInPlaySelector()} // Thread.sleep(500) // action_takeScreenshot() // Thread.sleep(500) // JFXStuff.later {bananas.action_newRegion()} // Thread.sleep(500) // JFXStuff.later {bananas.action_newRegion()} // } } private fun action_takeScreenshot() { stopRequested = true JFXPile.later { run { val image = robot.createScreenCapture(Rectangle(getDefaultToolkit().screenSize)) ImageIO.write(image, "png", File(tmpImgPath)) noise("Saved screenshot") } val play = bananas.playNode.iplay.entity val arena = newBotinokArena(name = "Arena ${getArenaCount() + 1}", screenshot = File(tmpImgPath).readBytes(), play = play, position = play.arenas.size, pile = "{}") play.arenas.add(arena) dirty = true PussyNode.newArena(arena, bananas.playNode.iplay) bananas.navigationTreeView.scrollTo(bananas.playNode.treeItem.children.lastIndex) selectLastTreeItem() JFXPile.later { primaryStage.isIconified = true JFXPile.later { primaryStage.isIconified = false } } } } private fun selectLastTreeItem() { bananas.navigationTreeView.selectionModel.clearSelection() bananas.navigationTreeView.selectionModel.selectLast() } fun getArenaCount(): Int { return bananas.playNode.treeItem.children.size } fun action_save() { backPlatform.tx { val playNode = bananas.playNode var swappedEntities = 0 playNode.entity = botinokPlayRepo.save(playNode.iplay.entity) ++swappedEntities var arenaIndex = 0 for (arenaNode in playNode.childNodes) { check(arenaNode.type == PussyNode.Type.ARENA) arenaNode.entity = playNode.iplay.entity.arenas[arenaIndex++] ++swappedEntities for ((index, iregion) in arenaNode.iarena.regionNodes.withIndex()) { iregion.node.entity = arenaNode.iarena.entity.regions[index] ++swappedEntities } for ((index, ipointer) in arenaNode.iarena.pointerNodes.withIndex()) { ipointer.node.entity = arenaNode.iarena.entity.pointers[index] ++swappedEntities } } noise("swappedEntities = $swappedEntities") } dirty = false JFXPile.infoAlert("Your shit was saved OK") } fun action_run() { if (running) return bananas.runMenuItem.isDisable = true bananas.stopMenuItem.isDisable = false running = true bananas.statusLabel.text = "Running..." stopRequested = false thread { arenas@for (arena in bananas.playNode.iplay.entity.arenas) { if (arena.regions.isEmpty()) { noise("Arena ${arena.name}: no regions -- skipping") continue@arenas } if (arena.pointers.isEmpty()) { noise("Arena ${arena.name}: no pointers -- skipping") continue@arenas } if (arena.pointers.size > 1) { noise("Arena ${arena.name}: multiple pointers are not yet supported -- skipping") continue@arenas } noise("Arena ${arena.name}: waiting for match") val arenaImage = ImageIO.read(arena.screenshot.inputStream()) check(arenaImage.raster.numBands == 3) {"9332a09a-417e-4c3b-8867-9bf76af6b47f"} while (true) { val time0 = System.currentTimeMillis() val screenImage = robot.createScreenCapture(Rectangle(getDefaultToolkit().screenSize)) check(screenImage.raster.numBands == 3) {"99e06055-4be8-4c29-8ac9-6437663e5d8e"} var allRegionsMatched = true regions@for (region in arena.regions) { if (stopRequested) break@arenas for (x in region.x until region.x + region.w) { for (y in region.y until region.y + region.h) { val screenPixel = intArrayOf(-1, -1, -1) screenImage.raster.getPixel(x, y, screenPixel) // noise("Screen pixel: ${screenPixel[0]}, ${screenPixel[1]}, ${screenPixel[2]}") val arenaPixel = intArrayOf(-1, -1, -1) arenaImage.raster.getPixel(x, y, arenaPixel) // noise("Arena pixel: ${arenaPixel[0]}, ${arenaPixel[1]}, ${arenaPixel[2]}") if (!Arrays.equals(screenPixel, arenaPixel)) { allRegionsMatched = false break@regions } } } } if (allRegionsMatched) { noise("Arena ${arena.name}: matched") val pointer = arena.pointers.first() robot.mouseMove(pointer.x, pointer.y) Thread.sleep(250) robot.mousePress(InputEvent.BUTTON1_DOWN_MASK) robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK) // TODO:vgrechka Think about... // In many cases this time will be enough for UI to respond, // so next iteration will match right away, and we avoid longer waiting. Or not? Thread.sleep(250) continue@arenas } noise("Tick: ${System.currentTimeMillis() - time0}ms") Thread.sleep(1000) } } running = false JFXPile.later { bananas.runMenuItem.isDisable = false bananas.stopMenuItem.isDisable = true bananas.resetStatusLabel() noise("Stopped") } } } fun action_stop() { if (!running) return stopRequested = true bananas.statusLabel.text = "Stopping..." } fun action_messAround() { val pointer = findPointer(arenaIndex = 0) thread { robot.mouseMove(pointer.x, pointer.y) Thread.sleep(250) robot.mousePress(InputEvent.BUTTON1_DOWN_MASK) robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK) } } fun findPointer(arenaIndex: Int, pointerIndex: Int = 0): BotinokPointer { return bananas.playNode.iplay.entity.arenas[arenaIndex].pointers[pointerIndex] } fun action_playProperties() { val play = bananas.playNode.iplay.entity val dialog = Stage() dialog.title = "Play Properties" dialog.width = 500.0 dialog.height = 500.0 dialog.initOwner(primaryStage) dialog.initModality(Modality.APPLICATION_MODAL) val grid = GridPane() grid.hgap = 8.0 grid.vgap = 8.0 grid.padding = Insets(8.0, 8.0, 8.0, 8.0) val scene = Scene(grid) dialog.scene = scene grid.add(Label("Name"), 0, 0) val nameTextField = TextField() GridPane.setHgrow(nameTextField, Priority.ALWAYS) grid.add(nameTextField, 0, 1) nameTextField.text = play.name grid.add(Label("Pile"), 0, 2) val pileTextArea = TextArea() GridPane.setHgrow(pileTextArea, Priority.ALWAYS) GridPane.setVgrow(pileTextArea, Priority.ALWAYS) grid.add(pileTextArea, 0, 3) pileTextArea.style = "-fx-font-family: Consolas;" pileTextArea.text = play.pile val buttonHBox = HBox() buttonHBox.spacing = 8.0 buttonHBox.alignment = Pos.CENTER_RIGHT val okButton = Button("OK") buttonHBox.children += okButton fun onOK() { play.name = nameTextField.text play.pile = pileTextArea.text updateStageTitle() dirty = true dialog.close() } okButton.setOnAction {onOK()} val cancelButton = Button("Cancel") buttonHBox.children += cancelButton fun onCancel() { dialog.close() } cancelButton.setOnAction {onCancel()} grid.add(buttonHBox, 0, 4) dialog.addEventHandler(KeyEvent.KEY_PRESSED) {e-> if (e.code == KeyCode.ENTER && e.isControlDown) { onOK() } else if (e.code == KeyCode.ESCAPE) { onCancel() } } dialog.showAndWait() } companion object { @JvmStatic fun main(args: Array<String>) { TimePile.setSystemTimezoneGMT() launch(StartBotinok::class.java, *args) } } } private fun noise(s: String) { if (true) { clog(s) } }
apache-2.0
a41bc7213e9bd3ce7ab51d00ec0d1333
37.27451
236
0.516052
4.725847
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/asJava/KotlinLightClassInheritorTest.kt
5
2181
// 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.asJava import com.intellij.psi.JavaPsiFacade import com.intellij.psi.search.GlobalSearchScope import com.intellij.testFramework.LightProjectDescriptor import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinLightProjectDescriptor import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtFile import org.junit.Assert import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class KotlinLightClassInheritorTest11 : KotlinLightCodeInsightFixtureTestCase() { fun testAnnotation() { doTestInheritorByText("annotation class A", "java.lang.annotation.Annotation", false) } fun testEnum() { doTestInheritorByText("enum class A", "java.lang.Enum", false) } fun testIterable() { doTestInheritorByText("abstract class A<T> : Iterable<T>", "java.lang.Iterable", false) } fun testIterableDeep() { doTestInheritorByText("abstract class A<T> : List<T>", "java.lang.Iterable", true) } fun testObjectDeep() { doTestInheritorByText("abstract class A<T> : List<T>", "java.lang.Object", true) } fun testClassOnSelfDeep() { doTestInheritorByText("class A", "A", checkDeep = true, result = false) } private fun doTestInheritorByText(text: String, superQName: String, checkDeep: Boolean, result: Boolean = true) { val file = myFixture.configureByText("A.kt", text) as KtFile val ktClass = file.declarations.filterIsInstance<KtClass>().single() val psiClass = KotlinAsJavaSupport.getInstance(project).getLightClass(ktClass)!! val baseClass = JavaPsiFacade.getInstance(project).findClass(superQName, GlobalSearchScope.allScope(project))!! Assert.assertEquals(psiClass.isInheritor(baseClass, checkDeep), result) } override fun getProjectDescriptor(): LightProjectDescriptor = KotlinLightProjectDescriptor.INSTANCE }
apache-2.0
ea45c6abb69ef0005fa8fd5701d54534
41.764706
158
0.749656
4.660256
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/KotlinCreateFromTemplateHandler.kt
6
1133
// 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.actions import com.intellij.ide.fileTemplates.DefaultCreateFromTemplateHandler import com.intellij.ide.fileTemplates.FileTemplate import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded class KotlinCreateFromTemplateHandler : DefaultCreateFromTemplateHandler() { override fun handlesTemplate(template: FileTemplate) = template.isTemplateOfType(KotlinFileType.INSTANCE) override fun prepareProperties(props: MutableMap<String, Any>) { val packageName = props[FileTemplate.ATTRIBUTE_PACKAGE_NAME] as? String if (!packageName.isNullOrEmpty()) { props[FileTemplate.ATTRIBUTE_PACKAGE_NAME] = packageName.split('.').joinToString(".", transform = String::quoteIfNeeded) } val name = props[FileTemplate.ATTRIBUTE_NAME] as? String if (name != null) { props[FileTemplate.ATTRIBUTE_NAME] = name.quoteIfNeeded() } } }
apache-2.0
3f376af8c5c4ddaddaae6c4f78ccce8b
46.25
158
0.750221
4.662551
false
false
false
false
smmribeiro/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenJavaNewProjectWizard.kt
1
1625
// 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.idea.maven.wizards import com.intellij.ide.projectWizard.generators.BuildSystemJavaNewProjectWizard import com.intellij.ide.projectWizard.generators.JavaNewProjectWizard import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl import com.intellij.openapi.project.Project import com.intellij.util.io.systemIndependentPath import org.jetbrains.idea.maven.model.MavenId import org.jetbrains.idea.maven.utils.MavenUtil class MavenJavaNewProjectWizard : BuildSystemJavaNewProjectWizard { override val name = MAVEN override fun createStep(parent: JavaNewProjectWizard.Step) = Step(parent) class Step(parent: JavaNewProjectWizard.Step) : MavenNewProjectWizardStep<JavaNewProjectWizard.Step>(parent) { override fun setupProject(project: Project) { val builder = InternalMavenModuleBuilder().apply { moduleJdk = sdk name = parentStep.name contentEntryPath = parentStep.projectPath.systemIndependentPath parentProject = parentData aggregatorProject = parentData projectId = MavenId(groupId, artifactId, version) isInheritGroupId = parentData?.mavenId?.groupId == groupId isInheritVersion = parentData?.mavenId?.version == version } ExternalProjectsManagerImpl.setupCreatedProject(project) builder.commit(project) } } companion object { @JvmField val MAVEN = MavenUtil.SYSTEM_ID.readableName } }
apache-2.0
0ac2aef1dd2607bf1a80ba76a71b2667
39.65
158
0.776
4.924242
false
false
false
false
smmribeiro/intellij-community
platform/vcs-impl/src/com/intellij/codeInsight/hints/VcsCodeAuthorInlayHintsProvider.kt
1
6359
// 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.codeInsight.hints import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.hints.VcsCodeAuthorInlayHintsProvider.Companion.KEY import com.intellij.lang.Language import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.util.EditorUtil.disposeWithEditor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.actions.VcsAnnotateUtil import com.intellij.openapi.vcs.annotate.AnnotationsPreloader import com.intellij.openapi.vcs.annotate.FileAnnotation import com.intellij.openapi.vcs.annotate.LineAnnotationAspect import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.impl.PsiManagerEx import com.intellij.ui.layout.* import com.intellij.util.application import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.vcs.CacheableAnnotationProvider import javax.swing.JComponent private fun isCodeAuthorEnabledForApplication(): Boolean = !application.isUnitTestMode && Registry.`is`("vcs.code.author.inlay.hints") private fun isCodeAuthorEnabledInSettings(): Boolean = InlayHintsProviderExtension.findProviders() .filter { it.provider.key == KEY } .any { InlayHintsSettings.instance().hintsShouldBeShown(it.provider.key, it.language) } private fun isCodeAuthorEnabledInSettings(language: Language): Boolean { val hasProviderForLanguage = InlayHintsProviderExtension.allForLanguage(language).any { it.key == KEY } return hasProviderForLanguage && InlayHintsSettings.instance().hintsShouldBeShown(KEY, language) } internal fun isCodeAuthorInlayHintsEnabled(): Boolean = isCodeAuthorEnabledForApplication() && isCodeAuthorEnabledInSettings() @RequiresEdt internal fun refreshCodeAuthorInlayHints(project: Project, file: VirtualFile) { if (!isCodeAuthorEnabledForApplication()) return val psiFile = PsiManagerEx.getInstanceEx(project).fileManager.getCachedPsiFile(file) if (psiFile != null && !isCodeAuthorEnabledInSettings(psiFile.language)) return val editors = VcsAnnotateUtil.getEditors(project, file) val noCodeAuthorEditors = editors.filter { it.getUserData(VCS_CODE_AUTHOR_ANNOTATION) == null } if (noCodeAuthorEditors.isEmpty()) return for (editor in noCodeAuthorEditors) InlayHintsPassFactory.clearModificationStamp(editor) if (psiFile != null) DaemonCodeAnalyzer.getInstance(project).restart(psiFile) } abstract class VcsCodeAuthorInlayHintsProvider : InlayHintsProvider<NoSettings> { override val group: InlayGroup get() = InlayGroup.CODE_AUTHOR_GROUP override fun getCollectorFor(file: PsiFile, editor: Editor, settings: NoSettings, sink: InlayHintsSink): InlayHintsCollector? { if (!isCodeAuthorEnabledForApplication()) return null val virtualFile = file.virtualFile ?: return null val annotation = getAnnotation(file.project, virtualFile, editor) ?: return null val authorAspect = annotation.aspects.find { it.id == LineAnnotationAspect.AUTHOR } ?: return null return VcsCodeAuthorInlayHintsCollector(editor, authorAspect, this::isAccepted, this::getClickHandler) } override fun getPlaceholdersCollectorFor( file: PsiFile, editor: Editor, settings: NoSettings, sink: InlayHintsSink ): InlayHintsCollector? { if (!isCodeAuthorEnabledForApplication()) return null if (!AnnotationsPreloader.isEnabled()) return null val virtualFile = file.virtualFile ?: return null if (!AnnotationsPreloader.canPreload(file.project, virtualFile)) return null return VcsCodeAuthorPlaceholdersCollector(editor, this::isAccepted) } protected abstract fun isAccepted(element: PsiElement): Boolean protected open fun getClickHandler(element: PsiElement): () -> Unit = {} override fun createSettings(): NoSettings = NoSettings() override val isVisibleInSettings: Boolean get() = isCodeAuthorEnabledForApplication() override val name: String get() = message("label.code.author.inlay.hints") override val key: SettingsKey<NoSettings> get() = KEY override val previewText: String? get() = null override fun createConfigurable(settings: NoSettings): ImmediateConfigurable = object : ImmediateConfigurable { override fun createComponent(listener: ChangeListener): JComponent = panel {} } companion object { internal val KEY: SettingsKey<NoSettings> = SettingsKey("vcs.code.author") } } private val VCS_CODE_AUTHOR_ANNOTATION = Key.create<FileAnnotation>("Vcs.CodeAuthor.Annotation") private fun getAnnotation(project: Project, file: VirtualFile, editor: Editor): FileAnnotation? { editor.getUserData(VCS_CODE_AUTHOR_ANNOTATION)?.let { return it } val vcs = ProjectLevelVcsManager.getInstance(project).getVcsFor(file) ?: return null val provider = vcs.annotationProvider as? CacheableAnnotationProvider ?: return null val annotation = provider.getFromCache(file) ?: return null val annotationDisposable = Disposable { unregisterAnnotation(file, annotation) annotation.dispose() } annotation.setCloser { editor.putUserData(VCS_CODE_AUTHOR_ANNOTATION, null) Disposer.dispose(annotationDisposable) project.service<AnnotationsPreloader>().schedulePreloading(file) } annotation.setReloader { annotation.close() } editor.putUserData(VCS_CODE_AUTHOR_ANNOTATION, annotation) registerAnnotation(file, annotation) disposeWithEditor(editor, annotationDisposable) return annotation } private fun registerAnnotation(file: VirtualFile, annotation: FileAnnotation) = ProjectLevelVcsManager.getInstance(annotation.project).annotationLocalChangesListener.registerAnnotation(file, annotation) private fun unregisterAnnotation(file: VirtualFile, annotation: FileAnnotation) = ProjectLevelVcsManager.getInstance(annotation.project).annotationLocalChangesListener.unregisterAnnotation(file, annotation)
apache-2.0
d3359a9d514f02b897865d06e3b43ec0
43.468531
158
0.801541
4.614659
false
false
false
false
smmribeiro/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/externalSystemIntegration/output/importproject/quickfixes/DownloadArtifactBuildIssue.kt
1
2537
// 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.idea.maven.externalSystemIntegration.output.importproject.quickfixes import com.intellij.build.issue.BuildIssue import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.pom.Navigatable import org.jetbrains.idea.maven.project.MavenProjectBundle import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.utils.MavenLog import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.CompletableFuture object DownloadArtifactBuildIssue { fun getIssue(title: String, quickFix: BuildIssueQuickFix): BuildIssue { val quickFixes = listOf(quickFix) return object : BuildIssue { override val title: String = title override val description: String = MavenProjectBundle.message("maven.quickfix.cannot.artifact.download", title, quickFix.id) override val quickFixes = quickFixes override fun getNavigatable(project: Project): Navigatable? = null } } } class CleanBrokenArtifactsAndReimportQuickFix(val unresolvedArtifactFiles: Collection<Path?>) : BuildIssueQuickFix { override val id: String = ID override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> { unresolvedArtifactFiles.filterNotNull().forEach { deleteLastUpdatedFiles(it) } MavenProjectsManager.getInstance(project).forceUpdateProjects() return CompletableFuture.completedFuture(null) } private fun deleteLastUpdatedFiles(unresolvedArtifactDirectory: Path) { MavenLog.LOG.info("start deleting lastUpdated file from $unresolvedArtifactDirectory") val listUpdatedFiles = try { Files.list(unresolvedArtifactDirectory).filter { child -> child.fileName.toString().endsWith(".lastUpdated", true) } } catch (e: Exception) { MavenLog.LOG.warn("error deleting lastUpdated file from $unresolvedArtifactDirectory", e) return } for (childFiles in listUpdatedFiles) { try { FileUtil.delete(childFiles) } catch (e: IOException) { MavenLog.LOG.warn("$childFiles not deleted", e) } } } companion object { const val ID = "clean_broken_artifacts_and_reimport_quick_fix" } }
apache-2.0
79d01f1cd3a8d466bd81a7ce829609f0
36.308824
158
0.761924
4.587703
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/renderer/collectionRenderer.kt
10
864
package collectionRenderer private class MyList : AbstractList<String>() { private val implementationDetail = "should not be seen" override val size: Int = 2 override fun get(index: Int): String = when (index) { 0 -> "first" 1 -> "second" else -> throw IndexOutOfBoundsException(index) } } fun main() { val emptyList = emptyList<String>() val nonEmptyList = listOf("l1", "l2", "l3") val emptySet = emptySet<String>() val nonEmptySet = setOf("s1", "s2", "s3") val builtEmptyList = buildList<String> {} val builtNonEmptyList = buildList { add("bl1"); add("bl2"); add("bl3") } val builtEmptySet = buildSet<String> {} val builtNonEmptySet = buildSet { add("bs1") add("bs2") add("bs3") } val myList = MyList() //Breakpoint! run {} } // PRINT_FRAME
apache-2.0
5ae6844025d4a9a411b76806002ea438
21.763158
76
0.59838
3.806167
false
false
false
false
anastr/SpeedView
speedviewlib/src/main/java/com/github/anastr/speedviewlib/LinearGauge.kt
1
3021
package com.github.anastr.speedviewlib import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.util.AttributeSet /** * this Library build By Anas Altair * see it on [GitHub](https://github.com/anastr/SpeedView) */ abstract class LinearGauge @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, ) : Gauge(context, attrs, defStyleAttr) { private val paint = Paint(Paint.ANTI_ALIAS_FLAG) /** to draw part of bitmap */ private val rect = Rect() private var foregroundBitmap: Bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) /** * horizontal or vertical direction . * change fill orientation, * this will change view width and height. */ var orientation = Orientation.HORIZONTAL set(orientation) { field = orientation if (isAttachedToWindow) { requestLayout() invalidateGauge() } } init { initAttributeSet(context, attrs) } /** * update background and foreground bitmap, * this method called when change size, color, orientation... * * * must call [createBackgroundBitmapCanvas] and * [createForegroundBitmapCanvas] inside this method. * */ protected abstract fun updateFrontAndBackBitmaps() private fun initAttributeSet(context: Context, attrs: AttributeSet?) { if (attrs == null) return val a = context.theme.obtainStyledAttributes(attrs, R.styleable.LinearGauge, 0, 0) val orientation = a.getInt(R.styleable.LinearGauge_sv_orientation, -1) if (orientation != -1) this.orientation = Orientation.values()[orientation] a.recycle() } override fun onSizeChanged(w: Int, h: Int, oldW: Int, oldH: Int) { super.onSizeChanged(w, h, oldW, oldH) updateBackgroundBitmap() } override fun updateBackgroundBitmap() { updateFrontAndBackBitmaps() } protected fun createForegroundBitmapCanvas(): Canvas { if (widthPa == 0 || heightPa == 0) return Canvas() foregroundBitmap = Bitmap.createBitmap(widthPa, heightPa, Bitmap.Config.ARGB_8888) return Canvas(foregroundBitmap) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (this.orientation == Orientation.HORIZONTAL) rect.set(0, 0, (widthPa * getOffsetSpeed()).toInt(), heightPa) else rect.set(0, heightPa - (heightPa * getOffsetSpeed()).toInt(), widthPa, heightPa) canvas.translate(padding.toFloat(), padding.toFloat()) canvas.drawBitmap(foregroundBitmap, rect, rect, paint) canvas.translate((-padding).toFloat(), (-padding).toFloat()) drawSpeedUnitText(canvas) } enum class Orientation { HORIZONTAL, VERTICAL } }
apache-2.0
ed0a2adaabc10a0e081b7844bccf3262
29.21
93
0.643496
4.442647
false
false
false
false
SirWellington/alchemy-test
src/main/java/tech/sirwellington/alchemy/test/hamcrest/HamcrestMatchers.kt
1
3172
/* * Copyright © 2019. Sir Wellington. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("HamcrestMatchers") package tech.sirwellington.alchemy.test.hamcrest import com.natpryce.hamkrest.* import java.util.Objects /** * Fails if the object is not `null`. * @author SirWellington */ val isNull: Matcher<Any?> = Matcher(Objects::isNull) /** * Fails if the object is `null`. * * @author SirWellington */ val notNull: Matcher<Any?> = !isNull /** * Fails if the collection is empty and has no elements in it. * * @author SirWellington */ val notEmpty: Matcher<Collection<Any>?> = present(!isEmpty) /** * Fails if the collection is not empty (has elements present). * * @author SirWellington */ val isNullOrEmpty: Matcher<Collection<Any>?> = isNull.or(isEmpty as Matcher<Collection<Any>?>) /** * Fails if the collection is null or empty. * * @author SirWellington */ val notNullOrEmpty: Matcher<Collection<Any>?> = present(notEmpty) /** * Fails if the string is empty or `null`. * * @author SirWellington */ val emptyString: Matcher<CharSequence?> = notNull and isEmptyString as Matcher<CharSequence?> /** * Fails if the string is empty or null. * * @author SirWellington */ val nonEmptyString: Matcher<CharSequence?> = notNull and !emptyString val isNullOrEmptyString: Matcher<CharSequence?> = isNull or (isEmptyString as Matcher<CharSequence?>) val notNullOrEmptyString: Matcher<CharSequence?> = !tech.sirwellington.alchemy.test.hamcrest.isNullOrEmptyString /** * Fails if the [Boolean] value is `false`. */ val isTrue: Matcher<Boolean?> = notNull and equalTo(true) /** * Fails if the [Boolean] value is `true`. */ val isFalse: Matcher<Boolean?> = notNull and equalTo(false) /** * Fails if the [Collection] does not have a size of [size]. */ fun hasSize(size: Int): Matcher<Collection<*>?> = Matcher(Collection<*>?::hasSize, size) private fun Collection<*>?.hasSize(size: Int): Boolean { return this?.size == size } /** * Fails if the element is not in the [collection]. */ fun <T> isContainedIn(collection: Collection<T>) = object : Matcher.Primitive<T?>() { override fun invoke(actual: T?) = match(actual in collection) {"${describe(actual)} was not in ${describe(collection)}"} override val description: String get() = "is in ${describe(collection)}" override val negatedDescription: String get() = "is not in ${describe(collection)}" } private fun match(comparisonResult: Boolean, describeMismatch: () -> String): MatchResult { return if (comparisonResult) { MatchResult.Match } else { MatchResult.Mismatch(describeMismatch()) } }
apache-2.0
c7081631119468ee66205436d029a2ce
24.788618
124
0.70451
3.934243
false
false
false
false
prof18/RSS-Parser
rssparser/src/main/java/com/prof/rssparser/Channel.kt
1
1711
package com.prof.rssparser import java.io.Serializable data class Channel( val title: String?, val link: String?, val description: String?, val image: Image?, val lastBuildDate: String?, val updatePeriod: String?, val articles: List<Article>, val itunesChannelData: ItunesChannelData? ) : Serializable { internal data class Builder( private var title: String? = null, private var link: String? = null, private var description: String? = null, private var image: Image? = null, private var lastBuildDate: String? = null, private var updatePeriod: String? = null, private val articles: MutableList<Article> = mutableListOf(), private var itunesChannelData: ItunesChannelData? = null ) { fun title(title: String?) = apply { this.title = title } fun link(link: String?) = apply { this.link = link } fun description(description: String?) = apply { this.description = description } fun image(image: Image) = apply { this.image = image } fun lastBuildDate(lastBuildDate: String?) = apply { this.lastBuildDate = lastBuildDate } fun updatePeriod(updatePeriod: String?) = apply { this.updatePeriod = updatePeriod } fun addArticle(article: Article) = apply { this.articles.add(article) } fun itunesChannelData(itunesChannelData: ItunesChannelData?) = apply { this.itunesChannelData = itunesChannelData } fun build() = Channel( title, link, description, image, lastBuildDate, updatePeriod, articles, itunesChannelData ) } }
apache-2.0
109a3caa6815db3a16a3547f4eea08ae
35.425532
96
0.628288
4.331646
false
false
false
false
Softmotions/ncms
ncms-engine/ncms-engine-tests/src/main/java/com/softmotions/ncms/PostgresTestRunner.kt
1
3181
package com.softmotions.ncms import com.softmotions.kotlin.TimeSpec import com.softmotions.kotlin.toSeconds import com.softmotions.runner.ProcessRun import com.softmotions.runner.ProcessRunner import com.softmotions.runner.ProcessRunners import com.softmotions.runner.UnixSignal import org.slf4j.LoggerFactory import java.util.concurrent.atomic.AtomicBoolean /** * @author Adamansky Anton ([email protected]) */ @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") open class PostgresTestRunner : DatabaseTestRunner { private val log = LoggerFactory.getLogger(PostgresTestRunner::class.java) private val dbRunner: ProcessRunner = ProcessRunners.serial(verbose = true) private val dbBin: String = "/usr/lib/postgresql/10/bin" private val dbPort: Int = 9231 private var dbDir: String? = null protected fun outputLine(line: String): Unit { log.info(line) } protected fun checkExitCode(pr: ProcessRun) { val ecode = pr.process.exitValue() if (ecode != 0) { throw RuntimeException("Process failed with exit code: $ecode command: ${pr.command}") } } override fun setupDb(props: Map<String, Any>) { shutdownDb() System.setProperty("JDBC.env", "pgtest") System.setProperty("JDBC.url", "jdbc:postgresql://localhost:${dbPort}/postgres") System.setProperty("JDBC.driver", "org.postgresql.Driver") val started = AtomicBoolean(false) val locale = "en_US.UTF-8" dbDir = "/dev/shm/ncmsdb" + System.currentTimeMillis() log.info("Setup database, dir: $dbDir") with(dbRunner) { cmd("mkdir -p $dbDir") cmd("$dbBin/initdb" + " --lc-messages=C" + " --lc-collate=$locale --lc-ctype=$locale" + " --lc-monetary=$locale --lc-numeric=$locale --lc-time=$locale" + " -D $dbDir", env = mapOf("LC_ALL".to("C"))) { outputLine(it) }.waitFor { checkExitCode(it) } cmd("$dbBin/postgres -D $dbDir -p $dbPort -o \"-c fsync=off -c synchronous_commit=off -c full_page_writes=off\"", failOnTimeout = true) { outputLine(it) if (it.trim().contains("database system is ready to accept connections")) { synchronized(started) { started.set(true) (started as Object).notifyAll() } } } } synchronized(started) { if (!started.get()) { (started as Object).wait(30.toSeconds().toMillis()) } } if (!started.get()) { throw RuntimeException("Timeout of waiting for postgres server") } } override fun shutdownDb() { dbRunner.reset(TimeSpec.HALF_MIN, UnixSignal.SIGINT) dbDir?.let { log.info("Remove database dir: $dbDir") with(dbRunner) { cmd("rm -rf $dbDir") }.haltRunner(30.toSeconds()) dbDir = null } } }
apache-2.0
1cb3efbb2db4e57633599619264396ac
31.804124
125
0.572461
4.213245
false
false
false
false
h31/LibraryMigration
src/main/kotlin/ru/spbstu/kspt/librarymigration/migration.kt
1
34957
package ru.spbstu.kspt.librarymigration import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.github.javaparser.JavaParser import com.github.javaparser.ast.Node import com.github.javaparser.ast.NodeList import com.github.javaparser.ast.body.* import com.github.javaparser.ast.expr.* import com.github.javaparser.ast.stmt.BlockStmt import com.github.javaparser.ast.stmt.ExpressionStmt import com.github.javaparser.ast.stmt.ReturnStmt import com.github.javaparser.ast.stmt.Statement import com.github.javaparser.ast.type.ClassOrInterfaceType import mu.KotlinLogging import java.io.File import java.util.* /** * Created by artyom on 22.08.16. */ data class PendingExpression(val expression: Expression, val edge: Edge, val provides: Expression? = null, val name: String? = null, val hasReturnValue: Boolean = provides != null, var makeVariable: Boolean = false) data class Replacement(val oldNode: Node, val pendingExpressions: List<PendingExpression>, val removeOldNode: Boolean = pendingExpressions.isEmpty(), val finalizerExpressions: List<PendingExpression> = listOf()) data class Route(val oldNode: Node, val route: List<Edge>, val edge: Edge, var finalizerRoute: List<Edge> = listOf()) { val edgeInsertRules = mutableListOf<EdgeInsertRules>() } data class EdgeInsertRules(val edge: Edge, val hasReturnValue: Boolean, val makeStatement: Boolean) class Migration(val library1: Library, val library2: Library, val codeElements: CodeElements, val functionName: String, val sourceFile: File, val invocations: GroupedInvocation, val project: Project) { val dependencies: MutableMap<StateMachine, Expression> = mutableMapOf() var nameGeneratorCounter = 0 val replacements: MutableList<Replacement> = mutableListOf() val globalRoute: MutableList<Route> = mutableListOf() private val logger = KotlinLogging.logger {} val ui = UserInteraction(library1.name, library2.name, sourceFile) val extractor = RouteExtractor(library1, codeElements, functionName, sourceFile, project) val routeMaker = RouteMaker(globalRoute, extractor, invocations, library1, library2, dependencies, ui, functionName) val transformer = Transformer(replacements, routeMaker) fun doMigration() { logger.info("Function: $functionName") routeMaker.makeRoutes() makeInsertRules() // calcIfNeedToMakeVariable() for (route in globalRoute) { replacements += when (route.edge) { is CallEdge -> migrateMethodCall(route) is ConstructorEdge -> migrateConstructorCall(route) is LinkedEdge -> migrateLinkedEdge(route) is AutoEdge -> Replacement(route.oldNode, listOf()) else -> TODO() } } transformer.apply() } private fun makeInsertRules() { val steps = mutableListOf<Triple<Int, Int, Edge>>() for (route in globalRoute.withIndex()) { for (edge in route.value.route.withIndex()) { steps += Triple(route.index, edge.index, edge.value) } } for ((routeIndex, edgeIndex, step) in steps) { val nextSteps = steps.filter { it.first > routeIndex || (it.first == routeIndex && it.second > edgeIndex) }.map { it.third } val usageCount = nextSteps.count { usesEdge(it, step) } val hasReturnValue = edgeHasReturnValue(step) globalRoute[routeIndex].edgeInsertRules += EdgeInsertRules(edge = step, hasReturnValue = hasReturnValue, makeStatement = !hasReturnValue || (usageCount > 1)) } } private fun edgeHasReturnValue(edge: Edge): Boolean = when (edge) { is LinkedEdge, is ConstructorEdge, is TemplateEdge, is CastEdge -> true is CallEdge -> edge.hasReturnValue else -> false } private fun associateEdges(edges: Collection<Edge>, node: Node) = edges.map { edge -> edge to node } private fun usesEdge(current: Edge, step: Edge): Boolean { val usesAsThis = (current.src.machine == step.dst.machine) val usesAsParam = if (current is ExpressionEdge) current.param.any { it is EntityParam && it.machine == step.dst.machine } else false val usesAsLinkedEdge = if (current is LinkedEdge) usesEdge(current.edge, step) else false return usesAsThis || usesAsParam || usesAsLinkedEdge // current.src.machine == step.dst.machine || if (current is ExpressionEdge) current.param.any { it is EntityParam && it.machine == step.dst.machine } else false } private fun migrateLinkedEdge(route: Route): Replacement { val oldVarName = getVariableNameFromExpression(route.oldNode) val pendingExpressions = applySteps(route.route, route.edgeInsertRules, oldVarName) if (pendingExpressions.isNotEmpty()) { val finalizerExpressions = applySteps(route.finalizerRoute, listOf(), null) return Replacement(oldNode = route.oldNode, pendingExpressions = pendingExpressions, finalizerExpressions = finalizerExpressions) } else { val newNode = dependencies[route.edge.dst.machine] ?: error("No such dependency") return Replacement(oldNode = route.oldNode, pendingExpressions = listOf(PendingExpression(expression = newNode, edge = route.edge, provides = newNode))) } } private fun migrateMethodCall(route: Route): Replacement { val pendingExpressions = applySteps(route.route, route.edgeInsertRules, null) val finalizerExpressions = applySteps(route.finalizerRoute, listOf(), null) return Replacement(oldNode = route.oldNode, pendingExpressions = pendingExpressions, finalizerExpressions = finalizerExpressions, removeOldNode = true) } private fun migrateConstructorCall(route: Route): Replacement { val oldVarName = getVariableNameFromExpression(route.oldNode) val pendingExpressions = applySteps(route.route, route.edgeInsertRules, oldVarName) val finalizerExpressions = applySteps(route.finalizerRoute, listOf(), null) return Replacement(oldNode = route.oldNode, pendingExpressions = pendingExpressions, finalizerExpressions = finalizerExpressions) } private fun applySteps(steps: List<Edge>, rules: List<EdgeInsertRules>, oldVarName: String?): List<PendingExpression> { val pendingExpr = mutableListOf<PendingExpression>() for ((index, step) in steps.withIndex()) { logger.debug(" Step: " + step.label()) val newExpressions: List<PendingExpression> = makeStep(step) val variableDeclarationReplacement = (step == steps.last()) && (oldVarName != null) val name = if (variableDeclarationReplacement) oldVarName else generateVariableName(step) val rule = rules[index] val namedExpressions = newExpressions.map { when { rule.makeStatement || variableDeclarationReplacement -> it.copy(provides = NameExpr(name), name = name, hasReturnValue = rule.hasReturnValue, makeVariable = true) rule.hasReturnValue -> it.copy(provides = it.expression, hasReturnValue = true) else -> it } } logger.debug("Received expressions: " + namedExpressions.toString()) for (expr in namedExpressions) { addToContext(expr) } pendingExpr.addAll(namedExpressions) } return pendingExpr } private fun makeStep(step: Edge) = when (step) { is CallEdge, is LinkedEdge, is TemplateEdge, is ConstructorEdge, is CastEdge -> makeSimpleEdge(step) is UsageEdge, is AutoEdge -> emptyList() is MakeArrayEdge -> TODO() // makeArray(step.action) else -> TODO("Unknown action!") } private fun makeSimpleEdge(step: Edge): List<PendingExpression> { return listOf(PendingExpression(edge = step, expression = makeExpression(step))) } private fun generateVariableName(step: Edge) = "migration_${step.dst.machine.name}_${nameGeneratorCounter++}" private fun addToContext(pendingExpression: PendingExpression) { if (pendingExpression.hasReturnValue && pendingExpression.provides != null) { dependencies[pendingExpression.edge.dst.machine] = pendingExpression.provides } } private fun makeExpression(step: Edge): Expression = when (step) { is LinkedEdge -> makeExpression(step.edge) is TemplateEdge -> makeTemplateExpression(step) is ConstructorEdge -> makeConstructorExpression(step) is UsageEdge -> makeExpression(step.edge) is CallEdge -> makeCallExpression(step) is CastEdge -> makeCastExpression(step) else -> TODO() } private fun getVariableNameFromExpression(methodCall: Node): String? { val parent = methodCall.parentNode.unpack() return if (parent is VariableDeclarator) parent.name.identifier else null } private fun makeCallExpressionParams(edge: CallEdge): CallExpressionParams { val scope = if (edge.isStatic) { NameExpr(edge.machine.type()) } else { checkNotNull(dependencies[edge.machine]) } val args = edge.param.map { param -> when (param) { is EntityParam -> checkNotNull(dependencies[param.machine]) is ActionParam -> { val pair = routeMaker.srcProps.actionParams.first { param.propertyName == it.first } routeMaker.srcProps.actionParams.remove(pair) NameExpr(pair.second.toString()) } is ConstParam -> NameExpr(param.value) else -> TODO() } } return CallExpressionParams(scope, args) } private fun makeCallExpression(step: CallEdge): Expression { val callParams = makeCallExpressionParams(step) val expr = MethodCallExpr(callParams.scope, step.methodName).setArguments(callParams.args.toNodeList()) return expr } private fun makeTemplateExpression(step: TemplateEdge): Expression { val stringParams = step.templateParams.mapValues { state -> checkNotNull(dependencies[state.value.machine].toString()) } return templateIntoAST(fillPlaceholders(step.template, stringParams)) } private fun makeCastExpression(step: CastEdge): Expression { if (step.explicitCast) { val type = library2.getType(step.dst.machine, null) val expr = CastExpr(JavaParser.parseClassOrInterfaceType(type), dependencies[step.machine]) return EnclosedExpr(expr) } else { return checkNotNull(dependencies[step.machine]) } } private fun makeConstructorExpression(step: ConstructorEdge): Expression { val params = step.param.filterIsInstance<EntityParam>().map { param -> checkNotNull(dependencies[param.machine]) } val expr = ObjectCreationExpr(null, JavaParser.parseClassOrInterfaceType(library2.getType(step.dst.machine, routeMaker.props[step.dst.machine])), params.toNodeList()) return expr } fun migrateClassField(field: FieldDeclaration, variable: VariableDeclarator) { logger.info("Field: {}", variable.name) val fieldType = variable.type.toString() val machine = getMachineForType(fieldType, library1) ?: return val newType = getNewType(machine, library2, field) if (newType != null) { variable.type = newType } else { field.remove() return } if (variable.initializer.isPresent) { migrateFieldInitializer() } } fun migrateFunctionArguments(methodDecl: MethodOrConstructorDeclaration) { val node = methodDecl.get() if (node is ConstructorDeclaration) { val args = node.parameters for (arg in args) { val argType = arg.type.toString() val machine = getMachineForType(argType, library1) ?: continue arg.type = getNewType(machine, library2, arg) } } } fun migrateReturnValue(methodDecl: MethodOrConstructorDeclaration) { val node = methodDecl.get() if (node is MethodDeclaration) { val machine = getMachineForType(node.type.toString(), library1) ?: return node.type = getNewType(machine, library2, node) } } private fun getMachineForType(oldType: String, library1: Library): StateMachine? = library1.machineTypes.entries.firstOrNull { (_, type) -> library1.simpleType(type) == oldType }?.key private fun getNewType(machine: StateMachine, library2: Library, node: Node): ClassOrInterfaceType? { val replacementMachine = if (library2.machineTypes.contains(machine)) { machine } else { val replacements = library2.stateMachines.map { it.label() } + "Remove" val answer = ui.makeDecision("Replacement for ${machine.label()} at ${node.begin.get()}", replacements) if (answer == "Remove") { return null } library2.stateMachines.first { it.label() == answer } } val newType = library2.machineTypes[replacementMachine]?.replace('$', '.') // TODO: Without replace? return JavaParser.parseClassOrInterfaceType(newType) } fun migrateFieldInitializer() { routeMaker.makeRoutes() makeInsertRules() if (globalRoute.isEmpty()) { return } for (route in globalRoute) { replacements += when (route.edge) { is CallEdge -> migrateMethodCall(route) is ConstructorEdge -> migrateConstructorCall(route) is LinkedEdge -> migrateLinkedEdge(route) is AutoEdge -> Replacement(route.oldNode, listOf()) else -> TODO() } } val actualReplacements = replacements.filter { it.pendingExpressions.isNotEmpty() } if (actualReplacements.size != 1) TODO() transformer.replaceFieldInitializer(actualReplacements.single()) } } class Transformer(val replacements: List<Replacement>, val routeMaker: RouteMaker) { val removedStmts = mutableListOf<Statement>() private val logger = KotlinLogging.logger {} fun apply() { for (replacement in replacements) { applyReplacement(replacement) } for (stmt in removedStmts) { (stmt.parentNode.unpack() as? BlockStmt)?.statements?.remove(stmt) } } fun applyReplacement(replacement: Replacement) { val oldExpr = replacement.oldNode val (statement, blockStmt) = getBlockStmt(oldExpr) val statements = blockStmt.statements if (replacement.pendingExpressions.isNotEmpty()) { val pos = statements.indexOf(statement) val pushedPendingExpressions = replacement.pendingExpressions.filter { it.makeVariable } val pendingStatements = pushedPendingExpressions.map { pending -> makeNewStatement(pending) } statements.addAll(pos, pendingStatements) // for (stmt in pendingStatements) { // stmt.parentNode = blockStmt // } val lastExpr = replacement.pendingExpressions.last() if (lastExpr.hasReturnValue && oldExpr.parentNode.get() !is VariableDeclarator) { val expr = lastExpr.provides!! replaceNode(expr, oldExpr) } else { removedStmts += statement } } else if (oldExpr.parentNode.get() is ExpressionStmt || oldExpr.parentNode.get() is VariableDeclarator || oldExpr.parentNode.get() is AssignExpr) { logger.info("Remove $statement") removedStmts += statement } makeFinalizers(statements, replacement) } private fun makeFinalizers(statements: MutableList<Statement>, replacement: Replacement) { val lastNotReturnStatement = statements.indexOfLast { stmt -> stmt !is ReturnStmt } if (replacement.finalizerExpressions.isNotEmpty()) { val newStatements = replacement.finalizerExpressions.map { ExpressionStmt(it.expression) } statements.addAll(lastNotReturnStatement + 1, newStatements) } } private fun replaceNode(newExpr: Expression, oldExpr: Node) { val parent = oldExpr.parentNode.get() when (parent) { is AssignExpr -> parent.value = newExpr is BinaryExpr -> parent.left = newExpr is ObjectCreationExpr -> { val argsPos = parent.arguments.indexOf(oldExpr) parent.arguments.set(argsPos, newExpr) // newExpr.parentNode = parent } is MethodCallExpr -> { val argsPos = parent.arguments.indexOf(oldExpr) if (argsPos >= 0) { parent.arguments.set(argsPos, newExpr) } else { parent.setScope(newExpr) } // newExpr.parentNode = parent } is ReturnStmt -> parent.setExpression(newExpr) is CastExpr -> parent.expression = newExpr is ExpressionStmt -> parent.expression = newExpr is ConditionalExpr -> when (oldExpr) { parent.condition -> parent.condition = newExpr parent.thenExpr -> parent.thenExpr = newExpr parent.elseExpr -> parent.elseExpr = newExpr else -> TODO() } else -> error("Don't know how to insert into " + parent.toString()) } } private fun getBlockStmt(initialNode: Node): Pair<Statement, BlockStmt> { var node: Node var parent: Node = initialNode do { node = parent parent = node.parentNode.get() } while (parent is BlockStmt == false) return Pair(node as Statement, parent as BlockStmt) } // private fun getNewVarName(pendingStmts: List<PendingExpression>): String = pendingStmts.map { stmt -> stmt.provides }.lastOrNull() ?: error("New statement should provide a variable") private fun makeNewStatement(pendingExpression: PendingExpression): Statement { if (pendingExpression.hasReturnValue) { val machine = pendingExpression.edge.dst.machine return makeNewVariable( type = checkNotNull(machine.library.getType(machine, routeMaker.props[machine])), name = checkNotNull(pendingExpression.name), initExpr = pendingExpression.expression ) } else { return ExpressionStmt(pendingExpression.expression) } } private fun makeNewVariable(type: String, name: String, initExpr: Expression?): Statement { val newVariable = VariableDeclarationExpr(JavaParser.parseClassOrInterfaceType(type), name) if (initExpr != null) { newVariable.variables.first().setInitializer(initExpr) } return ExpressionStmt(newVariable) } fun replaceFieldInitializer(replacement: Replacement) { val oldNode = replacement.oldNode if (replacement.pendingExpressions.none { it.makeVariable }) { val pendingExpression = replacement.pendingExpressions.last() if (!pendingExpression.hasReturnValue) error("Incorrect replacement") val parent = oldNode.parentNode.get() as? VariableDeclarator ?: throw IllegalArgumentException() parent.setInitializer(pendingExpression.expression) } else { if (oldNode.parentNode.get() !is VariableDeclarator) TODO() val classDecl = oldNode.getAncestorOfType(ClassOrInterfaceDeclaration::class.java).get() val declarator = oldNode.getAncestorOfType(VariableDeclarator::class.java).get() declarator.setInitializer(null as Expression?) val block = classDecl.addInitializer() val fieldAccess = FieldAccessExpr(NameExpr("this"), NodeList(), declarator.name) block.addStatement(AssignExpr(fieldAccess, oldNode as Expression, AssignExpr.Operator.ASSIGN)) applyReplacement(replacement) } } } class RouteExtractor(val library1: Library, val codeElements: CodeElements, val functionName: String, val sourceFile: File, val project: Project) { private val logger = KotlinLogging.logger {} fun extractFromJSON(invocations: GroupedInvocation): List<LocatedEdge> { val localInvocations = invocations[sourceFile.name]?.get(functionName) ?: return emptyList() // invocations.filter { inv -> inv.callerName == functionName && inv.filename == this.sourceFile.name } // val events = codeElements.codeEvents.sortedBy { event -> event.end.get() } // for (event in events) { // try { // val type = project.javaParserFacade.getType(event) // println(type) // } catch (ex: RuntimeException) { // System.err.println(ex) // } // } val usedEdges: MutableList<LocatedEdge> = mutableListOf() val edges = library1.stateMachines.flatMap { machine -> machine.edges } for (invocation in localInvocations) { if (invocation.kind == "method-call") { val callEdge = edges.filterIsInstance<CallEdge>().firstOrNull { edge -> edge.methodName == invocation.name && edge.machine.describesType(invocation.simpleType()) && edge.param.size == invocation.args.size && if (edge.param.isNotEmpty() && edge.param.first() is ConstParam) (edge.param.first() as ConstParam).value == invocation.args.first() else true } if (callEdge == null) { logger.debug("Cannot find edge for $invocation") continue } val methodCall = codeElements.methodCalls.firstOrNull { call -> call.name.identifier == invocation.name && call.end.unpack()?.line == invocation.line } if (methodCall == null) { val decl = codeElements.methodDecls.first { it.name() == invocation.callerName } if (invocation.line < decl.node.begin.get().line || invocation.line > decl.node.end.get().line) { logger.debug("Outside of method declaration, skipping...") continue } logger.error("Cannot find node for $invocation") continue } usedEdges += LocatedEdge(callEdge, methodCall) if (methodCall.parentNode.get() is ExpressionStmt == false) { val linkedEdge = callEdge.linkedEdge if (linkedEdge != null) { usedEdges += LocatedEdge(linkedEdge, methodCall) // usedEdges += associateEdges(linkedEdge.getSubsequentAutoEdges(), methodCall) } else { logger.error("Missing linked node") } } } else if (invocation.kind == "constructor-call") { val constructorEdge = edges.filterIsInstance<ConstructorEdge>().firstOrNull { edge -> invocation.simpleType() == edge.machine.type() } if (constructorEdge == null) { // println("Cannot find edge for $invocation") continue } val constructorCall = codeElements.objectCreation.firstOrNull { objectCreation -> (objectCreation.type.toString() == invocation.simpleType()) && (objectCreation.end.get().line == invocation.line) } if (constructorCall == null) { val decl = codeElements.methodDecls.first { it.name() == invocation.callerName } if (invocation.line < decl.node.begin.get().line || invocation.line > decl.node.end.get().line) { logger.debug("Outside of method declaration, skipping...") continue } error("Cannot find node for $invocation") } usedEdges += LocatedEdge(constructorEdge, constructorCall) } } val usedEdgesCleanedUp = usedEdges.distinct() if (usedEdgesCleanedUp.isNotEmpty()) { logger.debug("--- Used edges:") for (edge in usedEdgesCleanedUp) { logger.debug(edge.edge.label()) } logger.debug("---") // DOTVisualization().makePicture(library1, "extracted_" + functionName, usedEdgesCleanedUp.map { usage -> usage.edge }) } return usedEdgesCleanedUp.distinct() } fun makeProps(edges: List<LocatedEdge>): PropsContext { val props: PropsContext = PropsContext() for (edge in edges) { props.addEdgeFromTrace(edge) } return props } fun checkRoute(route: List<Edge>) { route.filterNot { edge -> edge is UsageEdge }.fold(listOf<Edge>(), { visited, edge -> if (visited.isEmpty() || visited.any { prevEdge -> edge.src == prevEdge.dst }) { visited + edge } else { error("Unexpected edge! Visited: ${printRoute(visited)}, edge: ${edge.label()}") } }) } private fun printRoute(route: List<Edge>) { // logger.debug("Route from %s to %s: ".format(src.stateAndMachineName(), // dst.stateAndMachineName())) for (state in route.withIndex()) { logger.debug("%d: %s".format(state.index, state.value.label())) } } data class LocatedEdge( val edge: Edge, val node: Node, val nodeLine: Int = node.end.get().line, val nodeColumn: Int = node.end.get().column ) @JsonIgnoreProperties("node") data class Invocation( val name: String, val filename: String, val line: Int = 0, val type: String, val callerName: String, val kind: String, val args: List<String>, val id: String, val place: String) { fun simpleType() = type.substringAfterLast('.').replace('$', '.') } } class RouteMaker(val globalRoute: MutableList<Route>, val extractor: RouteExtractor, val invocations: GroupedInvocation, val library1: Library, val library2: Library, val dependencies: MutableMap<StateMachine, Expression>, val ui: UserInteraction, val functionName: String) { val context: MutableSet<State> = mutableSetOf() val props: MutableMap<StateMachine, Map<String, Any>> = mutableMapOf() val actionsQueue = mutableListOf<Action>() lateinit var srcProps: PropsContext private val logger = KotlinLogging.logger {} fun makeRoutes() { val path = extractor.extractFromJSON(invocations) srcProps = extractor.makeProps(path) props += library2.stateMachines.map { machine -> machine to machine.migrateProperties(srcProps.stateProps) } // checkRoute(path) fillContextWithInit() for (usage in path) { val edge = usage.edge logger.debug("Processing " + edge.label() + "... ") extractDependenciesFromNode(edge, usage.node) val actions = edge.actions if (edge.canBeSkipped()) { logger.debug(" Makes a loop, skipping") for (action in actions.filter { it.withSideEffects == false }) { actionsQueue += action } if (globalRoute.any { route -> route.oldNode == usage.node }) { continue } globalRoute += Route(oldNode = usage.node, route = listOf(), edge = AutoEdge(edge.machine)) // TODO continue } var dst: State? = edge.dst if (edge.dst.machine in library2.stateMachines == false) { if (actions.isNotEmpty()) { dst = null } else { if (globalRoute.any { route -> route.oldNode == usage.node }) { continue } globalRoute += Route(oldNode = usage.node, route = listOf(), edge = AutoEdge(edge.machine)) // TODO continue } } val route = findRoute(context, dst, actionsQueue + actions, functionName) if (route == null) { continue } actionsQueue.clear() props += route.stateProps for (step in route.path) { addToContext(step.dst) } globalRoute += Route(oldNode = usage.node, route = route.path, edge = edge) } // check(actionsQueue.isEmpty()) // addFinalizers() // TODO } private fun fillContextWithInit() { context += library2.stateMachines.flatMap { machine -> machine.states }.filter(State::isInit).toMutableSet() } private fun addFinalizers() { val contextMachines = context.map(State::machine) val needsFinalization = contextMachines.filter { machine -> library2.stateMachines.contains(machine) && machine.states.any(State::isFinal) } for (machine in needsFinalization) { val route = findRoute(context, machine.getFinalState(), listOf(), "")!!.path // TODO: Function name if (route.isNotEmpty()) { val firstOccurence = globalRoute.first { route -> route.route.any { edge -> edge.machine == machine } } firstOccurence.finalizerRoute = route } } } object IterationCounter { var iteration = 0 } private fun findRoute(src: Set<State>, dst: State?, actions: List<Action>, functionName: String): PathFinder.Model? { var states = src.filter { state -> library2.states().contains(state) }.toSet() logger.debug(" Searching route from ${states.joinToString(transform = State::stateAndMachineName)} to ${dst?.stateAndMachineName()} with ${actions.joinToString(transform = Action::name)}") val edges = library2.stateMachines.flatMap(StateMachine::edges).toSet() var iteration = 0 while (true) { try { val pathFinder = PathFinder(edges, states, props, actions.sorted()) pathFinder.findPath(dst) return pathFinder.resultModel } catch (ex: Exception) { val statesPool = library2.states() val response = ui.makeDecision("Add object to context, function name $functionName", statesPool.map { it.toString() } + "Skip") if (response == "Skip") { return null } val newState = statesPool.single { it.toString() == response } states -= states.filter { it.machine == newState.machine } states += newState val dependency = ui.makeDecision("Object name, function name $functionName", null) dependencies += Pair(newState.machine, IntegerLiteralExpr(dependency)) iteration++ } } } // private fun getUsages(methodName: String) = // codeElements.methodCalls.filter { methodCall -> methodCall.name == methodName } private fun extractDependenciesFromNode(edge: Edge, node: Node) = when { node is MethodCallExpr && edge is CallEdge -> extractDependenciesFromMethod(edge, node) node is MethodCallExpr && edge is LinkedEdge -> extractDependenciesFromMethod(edge.edge as CallEdge, node) node is ObjectCreationExpr && edge is ConstructorEdge -> extractDependenciesFromConstructor(edge, node) else -> TODO() } private fun extractDependenciesFromMethod(edge: CallEdge, methodCall: MethodCallExpr) { val args = edge.param.filterIsInstance<EntityParam>().mapIndexed { i, param -> param.state to methodCall.arguments[i] }.toMap() val scope = (edge.src to methodCall.scope.get()) val deps = args + scope addDependenciesToContext(deps) } private fun extractDependenciesFromConstructor(edge: ConstructorEdge, constructorCall: ObjectCreationExpr) { val args = edge.param.filterIsInstance<EntityParam>().mapIndexed { i, param -> param.state to constructorCall.arguments[i] }.toMap() // val scope = (edge.src to methodCall.scope) val deps = args // TODO: scope addDependenciesToContext(deps) } private fun addDependenciesToContext(deps: Map<State, Expression?>) { for ((dep, expr) in deps) { logger.debug("Machine ${dep.machine.label()} is now in state ${dep.label()}") if (context.contains(dep)) { continue } addToContext(dep) if (expr != null) { logger.debug("Machine ${dep.machine.label()} can be accessed by expr \"$expr\"") dependencies[dep.machine] = expr val autoDeps = library1.edges.filterIsInstance<AutoEdge>().filter { edge -> edge.src == dep } for (autoDep in autoDeps) { val dstMachine = autoDep.dst.machine logger.debug("Additionally machine ${dstMachine.label()} can be accessed by expr \"$expr\"") addToContext(autoDep.dst) dependencies[dstMachine] = expr } } } } private fun addToContext(state: State) { val removed = context.filter { it.machine == state.machine } context.removeAll(removed) context += state } private fun getDependencyStep(step: Edge) = library2.stateMachines.flatMap { machine -> machine.edges } .first { edge: Edge -> (edge.src != edge.dst) && (edge is UsageEdge == false) && (edge.dst == step.dst) } } fun <T> Optional<T>.unpack(): T? = orElse(null) fun <NodeT : Node> List<NodeT>.toNodeList() = NodeList.nodeList(this)
mit
95f0e963d88ae1bd077eb4bf34a4c9ab
44.755236
222
0.60952
4.802445
false
false
false
false
AVnetWS/Hentoid
app/src/main/java/me/devsaki/hentoid/notification/download/DownloadSuccessNotification.kt
1
2122
package me.devsaki.hentoid.notification.download import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.core.app.NotificationCompat import me.devsaki.hentoid.R import me.devsaki.hentoid.activities.LibraryActivity import me.devsaki.hentoid.receiver.DownloadNotificationDeleteReceiver import me.devsaki.hentoid.util.notification.Notification class DownloadSuccessNotification(private val completeCount: Int) : Notification { override fun onCreateNotification(context: Context): android.app.Notification = NotificationCompat.Builder(context, DownloadNotificationChannel.ID) .setSmallIcon(R.drawable.ic_hentoid_shape) .setContentTitle(getTitle(context)) .setContentIntent(getDefaultIntent(context)) .setDeleteIntent(getDeleteIntent(context)) .setLocalOnly(true) .setOngoing(false) .setAutoCancel(true) .build() private fun getTitle(context: Context): String { return context.resources .getQuantityString(R.plurals.download_completed, completeCount, completeCount) } private fun getDefaultIntent(context: Context): PendingIntent { val resultIntent = Intent(context, LibraryActivity::class.java) resultIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP val flags = if (Build.VERSION.SDK_INT > 30) PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE else PendingIntent.FLAG_UPDATE_CURRENT return PendingIntent.getActivity(context, 0, resultIntent, flags) } private fun getDeleteIntent(context: Context): PendingIntent { val intent = Intent(context, DownloadNotificationDeleteReceiver::class.java) val flags = if (Build.VERSION.SDK_INT > 30) PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE else PendingIntent.FLAG_CANCEL_CURRENT return PendingIntent.getBroadcast(context, 0, intent, flags) } }
apache-2.0
ba634b8b71e05f6191dbc7a91d528d4c
41.44
94
0.721489
4.866972
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/auth/LoginViewModel.kt
1
4941
package org.fossasia.openevent.general.auth import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.reactivex.Single import io.reactivex.disposables.CompositeDisposable import org.fossasia.openevent.general.R import io.reactivex.rxkotlin.plusAssign import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers import org.fossasia.openevent.general.common.SingleLiveEvent import org.fossasia.openevent.general.data.Network import org.fossasia.openevent.general.data.Resource import org.fossasia.openevent.general.event.EventService import timber.log.Timber class LoginViewModel( private val authService: AuthService, private val network: Network, private val resource: Resource, private val eventService: EventService ) : ViewModel() { private val compositeDisposable = CompositeDisposable() private val mutableProgress = MutableLiveData<Boolean>() val progress: LiveData<Boolean> = mutableProgress private val mutableUser = MutableLiveData<User>() val user: LiveData<User> = mutableUser private val mutableError = SingleLiveEvent<String>() val error: LiveData<String> = mutableError private val mutableShowNoInternetDialog = MutableLiveData<Boolean>() val showNoInternetDialog: LiveData<Boolean> = mutableShowNoInternetDialog private val mutableRequestTokenSuccess = MutableLiveData<Boolean>() val requestTokenSuccess: LiveData<Boolean> = mutableRequestTokenSuccess private val mutableLoggedIn = SingleLiveEvent<Boolean>() var loggedIn: LiveData<Boolean> = mutableLoggedIn private val mutableValidPassword = MutableLiveData<Boolean>() val validPassword: LiveData<Boolean> = mutableValidPassword fun isLoggedIn() = authService.isLoggedIn() fun login(email: String, password: String) { if (!isConnected()) return val loginObservable: Single<LoginResponse> = authService.login(email, password).flatMap { loginResponse -> eventService.loadFavoriteEvent().flatMap { favsList -> val favIds = favsList.filter { favEvent -> favEvent.event != null } eventService.saveFavoritesEventFromApi(favIds).flatMap { Single.just(loginResponse) } } } compositeDisposable += loginObservable .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true }.doFinally { mutableProgress.value = false }.subscribe({ mutableLoggedIn.value = true }, { mutableError.value = resource.getString(R.string.login_fail_message) }) } fun checkValidPassword(email: String, password: String) { compositeDisposable += authService.checkPasswordValid(email, password) .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true }.doFinally { mutableProgress.value = false }.subscribe({ mutableValidPassword.value = true }, { mutableValidPassword.value = false }) } fun sendResetPasswordEmail(email: String) { if (!isConnected()) return compositeDisposable += authService.sendResetPasswordEmail(email) .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true }.doFinally { mutableProgress.value = false }.subscribe({ mutableRequestTokenSuccess.value = verifyMessage(it.message) }, { mutableRequestTokenSuccess.value = verifyMessage(it.message.toString()) mutableError.value = resource.getString(R.string.email_not_in_server_message) }) } private fun verifyMessage(message: String): Boolean { if (message == resource.getString(R.string.email_sent)) { return true } return false } fun fetchProfile() { if (!isConnected()) return compositeDisposable += authService.getProfile() .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true }.doFinally { mutableProgress.value = false }.subscribe({ Timber.d("User Fetched") mutableUser.value = it }) { Timber.e(it, "Failure") mutableError.value = resource.getString(R.string.failure) } } override fun onCleared() { super.onCleared() compositeDisposable.clear() } private fun isConnected(): Boolean { val isConnected = network.isNetworkConnected() if (!isConnected) mutableShowNoInternetDialog.value = true return isConnected } }
apache-2.0
49b960775eabbbde4699c3189e553817
36.431818
114
0.649059
5.483907
false
false
false
false
AlexandrDrinov/kotlin-koans-edu
src/i_introduction/_9_Extension_Functions/ExtensionFunctions.kt
1
665
package i_introduction._9_Extension_Functions fun String.lastChar() = this.get(this.length - 1) // 'this' can be omitted fun String.lastChar1() = get(length - 1) fun use() { // try Ctrl+Space "default completion" after the dot: lastChar() is visible "abc".lastChar() } // 'lastChar' is compiled to a static function in the class ExtensionFunctionsKt (see JavaCode9.useExtension) fun todoTask9(param1:Int, param2: Int): RationalNumber = RationalNumber(param1, param2) data class RationalNumber(val numerator: Int, val denominator: Int) fun Int.r(): RationalNumber = todoTask9(this, 1) fun Pair<Int, Int>.r(): RationalNumber = todoTask9(first, second)
mit
0792d553472771645676caf7e8451e9a
32.25
109
0.735338
3.55615
false
false
false
false
duftler/clouddriver
cats/cats-sql/src/main/kotlin/com/netflix/spinnaker/config/SqlConstraints.kt
1
939
/* * Copyright 2019 Armory * * 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.netflix.spinnaker.config import org.springframework.boot.context.properties.ConfigurationProperties @ConfigurationProperties("sql.constraints") class SqlConstraints { var maxTableNameLength: Int = 64 // 352 * 2 + 64 (max rel_type length) == 768; 768 * 4 (utf8mb4) == 3072 == Aurora's max index length var maxIdLength: Int = 352 }
apache-2.0
dc82425620d9d5f1c237bd346f9a4085
35.115385
102
0.743344
4.030043
false
true
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/ui/notes/NoteItemViewBinder.kt
1
18366
package com.orgzly.android.ui.notes import android.content.Context import android.graphics.Typeface import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.annotation.ColorInt import androidx.constraintlayout.widget.ConstraintLayout import com.orgzly.R import com.orgzly.android.App import com.orgzly.android.db.entity.Note import com.orgzly.android.db.entity.NoteView import com.orgzly.android.prefs.AppPreferences import com.orgzly.android.ui.TimeType import com.orgzly.android.ui.util.TitleGenerator import com.orgzly.android.ui.util.styledAttributes import com.orgzly.android.usecase.NoteToggleFolding import com.orgzly.android.usecase.NoteToggleFoldingSubtree import com.orgzly.android.usecase.NoteUpdateContent import com.orgzly.android.usecase.UseCaseRunner import com.orgzly.android.util.UserTimeFormatter import com.orgzly.databinding.ItemAgendaDividerBinding import com.orgzly.databinding.ItemHeadBinding class NoteItemViewBinder(private val context: Context, private val inBook: Boolean) { private val attrs: Attrs = Attrs.obtain(context) private val titleGenerator: TitleGenerator private val userTimeFormatter: UserTimeFormatter init { val titleAttributes = TitleGenerator.TitleAttributes( attrs.todoColor, attrs.doneColor, attrs.postTitleTextSize, attrs.postTitleTextColor) titleGenerator = TitleGenerator(context, inBook, titleAttributes) userTimeFormatter = UserTimeFormatter(context) } fun bind(holder: NoteItemViewHolder, noteView: NoteView, agendaTimeType: TimeType? = null) { setupTitle(holder, noteView) setupBookName(holder, noteView) setupPlanningTimes(holder, noteView, agendaTimeType) setupContent(holder, noteView.note) setupIndent(holder, noteView.note) setupBullet(holder, noteView.note) setupFoldingButtons(holder, noteView.note) setupAlpha(holder, noteView) } private fun setupBookName(holder: NoteItemViewHolder, noteView: NoteView) { if (inBook) { holder.binding.itemHeadBookNameIcon.visibility = View.GONE holder.binding.itemHeadBookNameText.visibility = View.GONE holder.binding.itemHeadBookNameBeforeNoteText.visibility = View.GONE } else { when (Integer.valueOf(AppPreferences.bookNameInSearchResults(context))) { 0 -> { // Hide holder.binding.itemHeadBookNameIcon.visibility = View.GONE holder.binding.itemHeadBookNameText.visibility = View.GONE holder.binding.itemHeadBookNameBeforeNoteText.visibility = View.GONE } 1 -> { // Show before note holder.binding.itemHeadBookNameIcon.visibility = View.GONE holder.binding.itemHeadBookNameText.visibility = View.GONE holder.binding.itemHeadBookNameBeforeNoteText.text = noteView.bookName holder.binding.itemHeadBookNameBeforeNoteText.visibility = View.VISIBLE } 2 -> { // Show under note holder.binding.itemHeadBookNameText.text = noteView.bookName holder.binding.itemHeadBookNameText.visibility = View.VISIBLE holder.binding.itemHeadBookNameIcon.visibility = View.VISIBLE holder.binding.itemHeadBookNameBeforeNoteText.visibility = View.GONE } } } } private fun setupTitle(holder: NoteItemViewHolder, noteView: NoteView) { holder.binding.itemHeadTitle.setVisibleText(generateTitle(noteView)) } fun generateTitle(noteView: NoteView): CharSequence { return titleGenerator.generateTitle(noteView) } private fun setupContent(holder: NoteItemViewHolder, note: Note) { if (note.hasContent() && titleGenerator.shouldDisplayContent(note)) { if (AppPreferences.isFontMonospaced(context)) { holder.binding.itemHeadContent.setTypeface(Typeface.MONOSPACE) } holder.binding.itemHeadContent.setSourceText(note.content) /* If content changes (for example by toggling the checkbox), update the note. */ holder.binding.itemHeadContent.setOnUserTextChangeListener { str -> val useCase = NoteUpdateContent(note.position.bookId, note.id, str) App.EXECUTORS.diskIO().execute { UseCaseRunner.run(useCase) } } holder.binding.itemHeadContent.visibility = View.VISIBLE } else { holder.binding.itemHeadContent.visibility = View.GONE } } private fun setupPlanningTimes(holder: NoteItemViewHolder, noteView: NoteView, agendaTimeType: TimeType?) { fun setupPlanningTime(textView: TextView, iconView: ImageView, value: String?) { if (value != null && AppPreferences.displayPlanning(context)) { val range = com.orgzly.org.datetime.OrgRange.parse(value) textView.text = userTimeFormatter.formatAll(range) textView.visibility = View.VISIBLE iconView.visibility = View.VISIBLE } else { textView.visibility = View.GONE iconView.visibility = View.GONE } } var scheduled = noteView.scheduledRangeString var deadline = noteView.deadlineRangeString var event = noteView.eventString // In Agenda only display time responsible for item's presence when (agendaTimeType) { TimeType.SCHEDULED -> { deadline = null event = null } TimeType.DEADLINE -> { scheduled = null event = null } TimeType.EVENT -> { scheduled = null deadline = null } else -> { } } setupPlanningTime( holder.binding.itemHeadScheduledText, holder.binding.itemHeadScheduledIcon, scheduled) setupPlanningTime( holder.binding.itemHeadDeadlineText, holder.binding.itemHeadDeadlineIcon, deadline) setupPlanningTime( holder.binding.itemHeadEventText, holder.binding.itemHeadEventIcon, event) setupPlanningTime( holder.binding.itemHeadClosedText, holder.binding.itemHeadClosedIcon, noteView.closedRangeString) } /** Set alpha for done and archived items. */ private fun setupAlpha(holder: NoteItemViewHolder, noteView: NoteView) { val state = noteView.note.state val tags = noteView.note.getTagsList() val inheritedTags = noteView.getInheritedTagsList() val isDone = state != null && AppPreferences.doneKeywordsSet(context).contains(state) val isArchived = tags.contains(ARCHIVE_TAG) || inheritedTags.contains(ARCHIVE_TAG) val alphaValue = if (isDone || isArchived) { 0.45f } else { 1.0f } holder.binding.run { listOf( itemHeadTitle, itemHeadBookNameIcon, itemHeadBookNameText, itemHeadBookNameBeforeNoteText, itemHeadScheduledIcon, itemHeadScheduledText, itemHeadDeadlineIcon, itemHeadDeadlineText, itemHeadEventIcon, itemHeadEventText, itemHeadClosedText, itemHeadClosedIcon, itemHeadContent ).forEach { it.alpha = alphaValue } } } /** * Set indentation views, depending on note level. */ private fun setupIndent(holder: NoteItemViewHolder, note: Note) { val container = holder.binding.itemHeadIndentContainer val level = if (inBook) note.position.level - 1 else 0 when { container.childCount < level -> { // More levels needed // Make all existing levels visible for (i in 1..container.childCount) { container.getChildAt(i - 1).visibility = View.VISIBLE } // Inflate the rest for (i in container.childCount + 1..level) { View.inflate(container.context, R.layout.indent, container) } } level < container.childCount -> { // Too many levels // Make required levels visible for (i in 1..level) { container.getChildAt(i - 1).visibility = View.VISIBLE } // Hide the rest for (i in level + 1..container.childCount) { container.getChildAt(i - 1).visibility = View.GONE } } else -> // Make all visible for (i in 1..container.childCount) { container.getChildAt(i - 1).visibility = View.VISIBLE } } container.tag = level } /** * Change bullet appearance depending on folding state and number of descendants. */ private fun setupBullet(holder: NoteItemViewHolder, note: Note) { if (!inBook) { holder.binding.itemHeadBullet.visibility = View.GONE return } if (note.position.descendantsCount > 0) { // With descendants if (note.position.isFolded) { // Folded holder.binding.itemHeadBullet.setImageResource(R.drawable.bullet_folded) } else { // Not folded holder.binding.itemHeadBullet.setImageResource(R.drawable.bullet) } } else { // No descendants holder.binding.itemHeadBullet.setImageResource(R.drawable.bullet) } holder.binding.itemHeadBullet.visibility = View.VISIBLE } private fun setupFoldingButtons(holder: NoteItemViewHolder, note: Note) { if (updateFoldingButtons(context, note, holder)) { // Folding button holder.binding.itemHeadFoldButton.setOnClickListener { toggleFoldedState(note.id) } holder.binding.itemHeadFoldButton.setOnLongClickListener { toggleFoldedStateForSubtree(note.id) } // Bullet holder.binding.itemHeadBullet.setOnClickListener { toggleFoldedState(note.id) } holder.binding.itemHeadBullet.setOnLongClickListener { toggleFoldedStateForSubtree(note.id) } } else { // Folding button holder.binding.itemHeadFoldButton.setOnClickListener(null) holder.binding.itemHeadFoldButton.setOnLongClickListener(null) // Bullet holder.binding.itemHeadBullet.setOnClickListener(null) holder.binding.itemHeadBullet.setOnLongClickListener(null) } } /** * Change folding button appearance. */ private fun updateFoldingButtons(context: Context, note: Note, holder: NoteItemViewHolder): Boolean { var isVisible = false if (inBook) { val contentFoldable = note.hasContent() && AppPreferences.isNotesContentFoldable(context) && AppPreferences.isNotesContentDisplayedInList(context) if (note.position.descendantsCount > 0 || contentFoldable) { isVisible = true /* Type of the fold button. */ if (note.position.isFolded) { holder.binding.itemHeadFoldButtonText.setText(R.string.unfold_button_character) } else { holder.binding.itemHeadFoldButtonText.setText(R.string.fold_button_character) } } } if (isVisible) { holder.binding.itemHeadFoldButton.visibility = View.VISIBLE holder.binding.itemHeadFoldButtonText.visibility = View.VISIBLE } else { if (inBook) { // Leave invisible for padding holder.binding.itemHeadFoldButton.visibility = View.INVISIBLE holder.binding.itemHeadFoldButtonText.visibility = View.INVISIBLE } else { holder.binding.itemHeadFoldButton.visibility = View.GONE holder.binding.itemHeadFoldButtonText.visibility = View.GONE } } // Add horizontal padding when in search results (no bullet, no folding button) val horizontalPadding = context.resources.getDimension(R.dimen.screen_edge).toInt() if (!inBook) { holder.binding.itemHeadContainer.setPadding( horizontalPadding, holder.binding.itemHeadContainer.paddingTop, horizontalPadding, holder.binding.itemHeadContainer.paddingBottom) // (holder.binding.itemHeadContainer.layoutParams as ConstraintLayout.LayoutParams).apply { // val right = if (holder.binding.itemHeadFoldButtonText.visibility == View.GONE) { // context.resources.getDimension(R.dimen.screen_edge).toInt() // } else { // 0 // } // // setMargins(leftMargin, topMargin, right, bottomMargin) // } } else { holder.binding.itemHeadContainer.setPadding( horizontalPadding, holder.binding.itemHeadContainer.paddingTop, holder.binding.itemHeadContainer.paddingRight, holder.binding.itemHeadContainer.paddingBottom) } return isVisible } // TODO: Move out private fun toggleFoldedState(id: Long) { App.EXECUTORS.diskIO().execute { UseCaseRunner.run(NoteToggleFolding(id)) } } private fun toggleFoldedStateForSubtree(id: Long): Boolean { App.EXECUTORS.diskIO().execute { UseCaseRunner.run(NoteToggleFoldingSubtree(id)) } return true } companion object { const val ARCHIVE_TAG = "ARCHIVE" /** * Setup margins or padding for different list density settings. */ fun setupSpacingForDensitySetting(context: Context, binding: ItemAgendaDividerBinding) { val margins = getMarginsForListDensity(context) binding.root.setPadding( binding.root.paddingLeft, margins.first, binding.root.paddingRight, margins.first) } fun setupSpacingForDensitySetting(context: Context, binding: ItemHeadBinding) { val margins = getMarginsForListDensity(context) // Whole item margins listOf(binding.itemHeadTop, binding.itemHeadBottom).forEach { (it.layoutParams as ConstraintLayout.LayoutParams).apply { height = margins.first } } // Spacing for views inside the item val views = arrayOf( binding.itemHeadScheduledText, binding.itemHeadScheduledIcon, binding.itemHeadDeadlineText, binding.itemHeadDeadlineIcon, binding.itemHeadEventText, binding.itemHeadEventIcon, binding.itemHeadClosedIcon, binding.itemHeadClosedText, binding.itemHeadContent) for (view in views) { (view.layoutParams as ConstraintLayout.LayoutParams).apply { setMargins(leftMargin, margins.second, rightMargin, bottomMargin) } } } private fun getMarginsForListDensity(context: Context): Pair<Int, Int> { val itemMargins: Int val belowTitleMargins: Int val density = AppPreferences.notesListDensity(context) val res = context.resources when (density) { context.getString(R.string.pref_value_list_density_comfortable) -> { // Comfortable itemMargins = res.getDimension(R.dimen.item_head_padding_comfortable).toInt() belowTitleMargins = res.getDimension(R.dimen.item_head_below_title_padding_comfortable).toInt() } context.getString(R.string.pref_value_list_density_compact) -> { // Compact itemMargins = res.getDimension(R.dimen.item_head_padding_compact).toInt() belowTitleMargins = res.getDimension(R.dimen.item_head_below_title_padding_compact).toInt() } else -> { // Cozy itemMargins = res.getDimension(R.dimen.item_head_padding_cozy).toInt() belowTitleMargins = res.getDimension(R.dimen.item_head_below_title_padding_cozy).toInt() } } return Pair(itemMargins, belowTitleMargins) } } private data class Attrs( @ColorInt val todoColor: Int, @ColorInt val doneColor: Int, val postTitleTextSize: Int, @ColorInt val postTitleTextColor: Int ) { companion object { @SuppressWarnings("ResourceType") fun obtain(context: Context): Attrs { return context.styledAttributes( intArrayOf( R.attr.item_head_state_todo_color, R.attr.item_head_state_done_color, R.attr.item_head_post_title_text_size, android.R.attr.textColorTertiary)) { typedArray -> Attrs( typedArray.getColor(0, 0), typedArray.getColor(1, 0), typedArray.getDimensionPixelSize(2, 0), typedArray.getColor(3, 0)) } } } } }
gpl-3.0
efaed456abf330f80eda19d0e9962a8f
36.407332
115
0.59327
5.055326
false
false
false
false