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
EventFahrplan/EventFahrplan
app/src/main/java/nerd/tuxmobil/fahrplan/congress/serialization/ScheduleChanges.kt
1
6871
package nerd.tuxmobil.fahrplan.congress.serialization import nerd.tuxmobil.fahrplan.congress.models.Session as SessionAppModel @Suppress("DataClassPrivateConstructor") data class ScheduleChanges private constructor( val sessionsWithChangeFlags: List<SessionAppModel>, val oldCanceledSessions: List<SessionAppModel>, val foundChanges: Boolean ) { companion object { /** * Returns a pair of a new list of sessions and a boolean flag indicating whether changes have * been found. Each session is flagged as ["new"][SessionAppModel.changedIsNew], * ["canceled"][SessionAppModel.changedIsCanceled] or according to the changes detected when * comparing it to its equivalent from the [oldSessions] list. * * This function does not modify the given lists nor any of its elements. */ fun computeSessionsWithChangeFlags( newSessions: List<SessionAppModel>, oldSessions: List<SessionAppModel> ): ScheduleChanges { var foundChanges = false if (oldSessions.isEmpty()) { // Do not flag sessions as "new" when sessions are loaded for the first time. return ScheduleChanges(newSessions, emptyList(), foundChanges) } val oldNotCanceledSessions = oldSessions.filterNot { it.changedIsCanceled }.toMutableList() val oldCanceledSessions = oldSessions.filter { it.changedIsCanceled } val sessionsWithChangeFlags = mutableListOf<SessionAppModel>() var sessionIndex = 0 while (sessionIndex < newSessions.size) { val newSession = newSessions[sessionIndex] val oldSession = oldNotCanceledSessions.singleOrNull { oldNotCanceledSession -> newSession.sessionId == oldNotCanceledSession.sessionId } if (oldSession == null) { sessionsWithChangeFlags += SessionAppModel(newSession).apply { changedIsNew = true } foundChanges = true sessionIndex++ continue } if (oldSession.equalsSession(newSession)) { sessionsWithChangeFlags += newSession oldNotCanceledSessions -= oldSession sessionIndex++ continue } val sessionChange = SessionChange() if (newSession.title != oldSession.title) { sessionChange.changedTitle = true foundChanges = true } if (newSession.subtitle != oldSession.subtitle) { sessionChange.changedSubtitle = true foundChanges = true } if (newSession.speakers != oldSession.speakers) { sessionChange.changedSpeakers = true foundChanges = true } if (newSession.lang != oldSession.lang) { sessionChange.changedLanguage = true foundChanges = true } if (newSession.room != oldSession.room) { sessionChange.changedRoom = true foundChanges = true } if (newSession.track != oldSession.track) { sessionChange.changedTrack = true foundChanges = true } if (newSession.recordingOptOut != oldSession.recordingOptOut) { sessionChange.changedRecordingOptOut = true foundChanges = true } if (newSession.day != oldSession.day) { sessionChange.changedDayIndex = true foundChanges = true } if (newSession.startTime != oldSession.startTime) { sessionChange.changedStartTime = true foundChanges = true } if (newSession.duration != oldSession.duration) { sessionChange.changedDuration = true foundChanges = true } sessionsWithChangeFlags += SessionAppModel(newSession).apply { changedTitle = sessionChange.changedTitle changedSubtitle = sessionChange.changedSubtitle changedSpeakers = sessionChange.changedSpeakers changedLanguage = sessionChange.changedLanguage changedRoom = sessionChange.changedRoom changedTrack = sessionChange.changedTrack changedRecordingOptOut = sessionChange.changedRecordingOptOut changedDay = sessionChange.changedDayIndex changedTime = sessionChange.changedStartTime changedDuration = sessionChange.changedDuration } oldNotCanceledSessions -= oldSession sessionIndex++ } if (oldNotCanceledSessions.isNotEmpty()) { // Flag all "old" sessions which are not present in the "new" set as canceled // and append them to the "new" set. sessionsWithChangeFlags += oldNotCanceledSessions.map { it.toCanceledSession() } foundChanges = true } return ScheduleChanges(sessionsWithChangeFlags.toList(), oldCanceledSessions, foundChanges) } private data class SessionChange( var changedTitle: Boolean = false, var changedSubtitle: Boolean = false, var changedSpeakers: Boolean = false, var changedLanguage: Boolean = false, var changedRoom: Boolean = false, var changedDayIndex: Boolean = false, var changedTrack: Boolean = false, var changedRecordingOptOut: Boolean = false, var changedStartTime: Boolean = false, var changedDuration: Boolean = false ) private fun SessionAppModel.toCanceledSession() = SessionAppModel(this).apply { cancel() } private fun SessionAppModel.equalsSession(session: SessionAppModel): Boolean { return title == session.title && subtitle == session.subtitle && speakers == session.speakers && lang == session.lang && room == session.room && track == session.track && recordingOptOut == session.recordingOptOut && day == session.day && startTime == session.startTime && duration == session.duration } } }
apache-2.0
a5c927dbf092fe49b74fa5c3a414157d
43.044872
153
0.561054
6.032485
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/main/responses/ResponsesPresenter.kt
2
4073
package ru.fantlab.android.ui.modules.main.responses import android.view.View import io.reactivex.Single import io.reactivex.functions.Consumer import ru.fantlab.android.data.dao.model.Response import ru.fantlab.android.data.dao.response.ResponsesResponse import ru.fantlab.android.data.dao.response.UserResponse import ru.fantlab.android.data.dao.response.VoteResponse import ru.fantlab.android.helper.PrefGetter import ru.fantlab.android.provider.rest.DataManager import ru.fantlab.android.provider.rest.getLastResponsesPath import ru.fantlab.android.provider.rest.getUserPath import ru.fantlab.android.provider.storage.DbProvider import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter class ResponsesPresenter : BasePresenter<ResponsesMvp.View>(), ResponsesMvp.Presenter { private var page: Int = 1 private var previousTotal: Int = 0 private var lastPage = Int.MAX_VALUE override fun onFragmentCreated() { onCallApi(1) } override fun onCallApi(page: Int, parameter: String?): Boolean = onCallApi(page) override fun onCallApi(page: Int): Boolean { if (page == 1) { lastPage = Int.MAX_VALUE sendToView { it.getLoadMore().reset() } } if (page > lastPage || lastPage == 0) { sendToView { it.hideProgress() } return false } setCurrentPage(page) makeRestCall( getResponsesInternal().toObservable(), Consumer { (responses, lastPage) -> this.lastPage = lastPage sendToView { it.onNotifyAdapter(responses, page) } } ) return true } private fun getResponsesInternal() = getResponsesFromServer() .onErrorResumeNext { throwable -> if (page == 1) { getResponsesFromDb() } else { throw throwable } } private fun getResponsesFromServer(): Single<Pair<ArrayList<Response>, Int>> = DataManager.getLastResponses(page) .map { getResponses(it) } private fun getResponsesFromDb(): Single<Pair<ArrayList<Response>, Int>> = DbProvider.mainDatabase .responseDao() .get(getLastResponsesPath(page)) .map { it.response } .map { ResponsesResponse.Deserializer(perPage = 50).deserialize(it) } .map { getResponses(it) } private fun getResponses(response: ResponsesResponse): Pair<ArrayList<Response>, Int> = response.responses.items to response.responses.last override fun onSendVote(item: Response, position: Int, voteType: String) { makeRestCall(DataManager.sendResponseVote(item.id, voteType) .toObservable(), Consumer { response -> val result = VoteResponse.Parser().parse(response) if (result != null) { sendToView { it.onSetVote(position, result.votesCount.toString()) } } else { sendToView { it.showErrorMessage(response) } } }) } override fun onGetUserLevel(position: Int, item: Response) { makeRestCall( getUserLevelInternal().toObservable(), Consumer { level -> sendToView { it.onShowVotesDialog(level, position, item) } }) } private fun getUserLevelInternal() = getUserLevelFromServer() .onErrorResumeNext { getUserLevelFromDb() } private fun getUserLevelFromServer(): Single<Float> = DataManager.getUser(PrefGetter.getLoggedUser()?.id!!) .map { getUserLevel(it) } private fun getUserLevelFromDb(): Single<Float> = DbProvider.mainDatabase .responseDao() .get(getUserPath(PrefGetter.getLoggedUser()?.id!!)) .map { it.response } .map { UserResponse.Deserializer().deserialize(it) } .map { getUserLevel(it) } private fun getUserLevel(response: UserResponse): Float = response.user.level override fun getCurrentPage(): Int = page override fun getPreviousTotal(): Int = previousTotal override fun setCurrentPage(page: Int) { this.page = page } override fun setPreviousTotal(previousTotal: Int) { this.previousTotal = previousTotal } override fun onItemClick(position: Int, v: View?, item: Response) { sendToView { it.onItemClicked(item) } } override fun onItemLongClick(position: Int, v: View?, item: Response) { sendToView { it.onItemLongClicked(position, v, item) } } }
gpl-3.0
72fc1bb0477c654b23588b7a8d31d973
29.402985
88
0.720599
3.723035
false
false
false
false
ironjan/MensaUPB
app/src/main/java/de/ironjan/mensaupb/menus_ui/MenuDetailFragment.kt
1
8718
package de.ironjan.mensaupb.menus_ui import android.graphics.Bitmap import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import android.text.TextUtils import android.util.Log import android.view.View import android.widget.ImageView import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast import com.koushikdutta.ion.Ion import de.ironjan.mensaupb.BuildConfig import de.ironjan.mensaupb.R import de.ironjan.mensaupb.api.model.Allergen import de.ironjan.mensaupb.api.model.Badge import de.ironjan.mensaupb.api.model.Menu import de.ironjan.mensaupb.api.model.Restaurant import org.androidannotations.annotations.AfterViews import org.androidannotations.annotations.Background import org.androidannotations.annotations.EFragment import org.androidannotations.annotations.UiThread import org.androidannotations.annotations.ViewById import org.androidannotations.annotations.res.StringRes import org.slf4j.LoggerFactory import java.util.ArrayList import java.util.Locale import java.util.concurrent.ExecutionException @EFragment(R.layout.fragment_menu_detail) open class MenuDetailFragment : Fragment() { @ViewById internal lateinit var textName: TextView @ViewById internal lateinit var textCategory: TextView @ViewById internal lateinit var textAllergensHeader: TextView @ViewById internal lateinit var textAllergens: TextView @ViewById internal lateinit var textPrice: TextView @ViewById internal lateinit var textRestaurant: TextView @ViewById internal lateinit var textDate: TextView @ViewById internal lateinit var textBadges: TextView @ViewById internal lateinit var textDescription: TextView @ViewById internal lateinit var image: ImageView @ViewById internal lateinit var progressBar: ProgressBar @ViewById(android.R.id.progress) internal lateinit var indefiniteProgressBar: ProgressBar @StringRes internal lateinit var localizedDatePattern: String @AfterViews internal fun bindData() { if (BuildConfig.DEBUG) LOGGER.debug("bindData()") val menu: Menu = arguments!!.getParcelable(PARCEL_MENU)!! showMenu(menu) if (BuildConfig.DEBUG) LOGGER.debug("bindData() done") } @UiThread internal open fun showError(s: String) { Toast.makeText(context, s, Toast.LENGTH_LONG).show() } private fun showMenu(menu: Menu) { bindMenuDataToViews(menu) } @UiThread internal open fun bindMenuDataToViews(menu: Menu) { val isEnglish = Locale.getDefault().language.startsWith(Locale.ENGLISH.toString()) textName.text = menu.localizedName(isEnglish) textCategory.text = menu.localizedCategory(isEnglish) bindDescription(menu.localizedDescription(isEnglish)) val activity = activity as AppCompatActivity? if (activity != null) { val supportActionBar = activity.supportActionBar if (supportActionBar != null) supportActionBar.title = "" } bindRestaurant(menu) bindDate(menu) bindPrice(menu) bindAllergens(menu) bindBadges(menu) loadImage(menu, false) } private fun bindDescription(description: String?) { if (TextUtils.isEmpty(description)) { textDescription.visibility = View.GONE } else { textDescription.text = description } } private fun bindBadges(stwMenu: Menu) { val badges = ArrayList<Badge>() val badgesAsString = stwMenu.badges for (badgeKey in badgesAsString) { badges.add(Badge.fromString(badgeKey)) } if (badges.isEmpty()) { textBadges.visibility = View.GONE return } textBadges.visibility = View.VISIBLE val stringBuilder = StringBuilder(activity!!.getString(badges[0].stringId)) for (i in 1 until badges.size) { val badgeString = activity!!.getString(badges[i].stringId) stringBuilder.append(", ") .append(badgeString) } textBadges.text = stringBuilder.toString() } private fun bindRestaurant(stwMenu: Menu) { val restaurantId = stwMenu.restaurant val restaurantNameId = Restaurant.fromKey(restaurantId).restaurantName textRestaurant.setText(restaurantNameId) } private fun bindDate(stwMenu: Menu) { textDate.text = stwMenu.date } private fun bindPrice(stwMenu: Menu) { val price = stwMenu.priceStudents!! val priceAsString = String.format(Locale.GERMAN, "%.2f €", price) textPrice.text = priceAsString if (stwMenu.isWeighted) { textPrice.append("/100g") } } private fun bindAllergens(stwMenu: Menu) { val allergens = ArrayList<Allergen>() for (allergenKey in stwMenu.allergens) { allergens.add(Allergen.fromString(allergenKey)) } if (allergens.isEmpty()) { hideAllergenList() } else { showAllergensList(allergens) } } private fun showAllergensList(allergens: List<Allergen>) { var notFirst = false val allergensListAsStringBuffer = StringBuilder() for (allergen in allergens) { if (notFirst) { allergensListAsStringBuffer.append("\n") } else { notFirst = true } val stringId = allergen.stringId val string = resources.getString(stringId) allergensListAsStringBuffer.append(string) } textAllergens.text = allergensListAsStringBuffer.toString() textAllergens.visibility = View.VISIBLE textAllergensHeader.visibility = View.VISIBLE } private fun hideAllergenList() { textAllergens.visibility = View.GONE textAllergensHeader.visibility = View.GONE } /** * Asynchronously load the image of the supplied menu * * @param stwMenu The menu to load a image for */ @Background internal open fun loadImage(stwMenu: Menu, forced: Boolean) { setProgressVisibility(View.VISIBLE) LOGGER.debug("loadImage()") val start = System.currentTimeMillis() LOGGER.debug("loadImage() - start={}", start) val uri: String = if (!TextUtils.isEmpty(stwMenu.image)) { stwMenu.image } else { URI_NO_IMAGE_FILE } LOGGER.debug("loadImage() - URI set [{}]", start) try { val context = context ?: return val bitmap = Ion.with(context) .load(uri) .setLogging("MenuDetailFragment", Log.VERBOSE) .progressBar(progressBar) .asBitmap() .get() applyLoadedImage(bitmap) } catch (e: InterruptedException) { applyErrorImage() LOGGER.error("InterruptedException: {}", e) } catch (e: ExecutionException) { applyErrorImage() LOGGER.error("InterruptedException: {}", e) } LOGGER.debug("loadImage() done") } @UiThread internal open fun setProgressVisibility(visible: Int) { progressBar.visibility = visible indefiniteProgressBar.visibility = visible } @UiThread internal open fun applyErrorImage() { Ion.with(activity!!) .load(URI_NO_IMAGE_FILE) .intoImageView(image) setProgressVisibility(View.GONE) } @UiThread internal open fun applyLoadedImage(bitmap: Bitmap) { image.setImageBitmap(bitmap) setProgressVisibility(View.GONE) } companion object { const val PARCEL_MENU = "PARCEL_MENU" const val URI_NO_IMAGE_FILE = "file:///android_asset/menu_has_no_image.png" private val LOGGER = LoggerFactory.getLogger(MenuDetailFragment::class.java.simpleName) fun newInstance(menu: Menu): MenuDetailFragment_ { if (BuildConfig.DEBUG) LOGGER.debug("newInstance({})", menu) val args = Bundle() args.putParcelable(PARCEL_MENU,menu) val menuDetailFragment = MenuDetailFragment_() menuDetailFragment.arguments = args if (BuildConfig.DEBUG) LOGGER.debug("Created new MenuDetailFragment ({})", menu) if (BuildConfig.DEBUG) LOGGER.debug("newInstance({}) done", menu) return menuDetailFragment } } }
apache-2.0
1e3267c89f35a3e5fd441b0cb2d32fa7
29.263889
95
0.644562
4.516062
false
false
false
false
ThomasVadeSmileLee/cyls
src/main/kotlin/com/scienjus/smartqq/model/Message.kt
1
1147
package com.scienjus.smartqq.model import com.github.salomonbrys.kotson.getObject import com.github.salomonbrys.kotson.string import com.google.gson.JsonObject import com.google.gson.JsonPrimitive /** * 消息. * @author ScienJus * * * @author [Liang Ding](http://88250.b3log.org) * * * @date 15/12/19. */ data class Message( var time: Long = 0L, var content: String? = "", var userId: Long? = 0L, var font: Font? = null ) { constructor(json: JsonObject) : this() { val cont = json.get("content").asJsonArray this.font = cont.get(0).asJsonArray.getObject(1) val size = cont.size() val contentBuilder = StringBuilder() for (i in 1 until size) { contentBuilder.append(cont.get(i).run { if (this@run is JsonPrimitive && [email protected]) { [email protected] } else { [email protected]() } }) } this.content = contentBuilder.toString() this.time = json.get("time").asLong this.userId = json.get("from_uin").asLong } }
mit
0b96eb4bbc50931b173bc86f50a7fc45
26.878049
69
0.570429
3.711039
false
false
false
false
BoD/CineToday
app/src/main/kotlin/org/jraf/android/cinetoday/model/showtime/Showtime.kt
1
2386
/* * This source is part of the * _____ ___ ____ * __ / / _ \/ _ | / __/___ _______ _ * / // / , _/ __ |/ _/_/ _ \/ __/ _ `/ * \___/_/|_/_/ |_/_/ (_)___/_/ \_, / * /___/ * repository. * * Copyright (C) 2017-present Benoit 'BoD' Lubek ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jraf.android.cinetoday.model.showtime import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey import androidx.room.TypeConverters import org.jraf.android.cinetoday.database.Converters import org.jraf.android.cinetoday.model.movie.Movie import org.jraf.android.cinetoday.model.theater.Theater import java.util.Date @Entity( foreignKeys = [ ForeignKey( entity = Theater::class, parentColumns = ["id"], childColumns = ["theaterId"], onDelete = ForeignKey.CASCADE ), ForeignKey( entity = Movie::class, parentColumns = ["id"], childColumns = ["movieId"], onDelete = ForeignKey.CASCADE ) ], indices = [ Index("theaterId"), Index("movieId") ] ) data class Showtime( @PrimaryKey(autoGenerate = true) val id: Long, val theaterId: String, val movieId: String, @field:TypeConverters(Converters.DateConverter::class) val time: Date, val is3d: Boolean ) : Comparable<Showtime> { override fun compareTo(other: Showtime): Int { val res = time.compareTo(other.time) if (res != 0) return res if (is3d) { if (other.is3d) return 0 return 1 } else { if (!other.is3d) return 0 return -1 } } }
gpl-3.0
a2d50cf6094c2d1ce33b2688a3956568
29.202532
72
0.601844
4.156794
false
false
false
false
wix/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/views/element/finder/ExistingViewFinder.kt
1
2211
package com.reactnativenavigation.views.element.finder import android.graphics.drawable.Drawable import android.view.View import android.widget.ImageView import androidx.core.view.doOnPreDraw import com.facebook.drawee.generic.RootDrawable import com.facebook.react.uimanager.util.ReactFindViewUtil import com.reactnativenavigation.viewcontrollers.viewcontroller.ViewController import kotlin.coroutines.Continuation import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine import kotlin.math.min class ExistingViewFinder : ViewFinder { override suspend fun find(root: ViewController<*>, nativeId: String) = suspendCoroutine<View?> { cont -> when (val view = ReactFindViewUtil.findView(root.view, nativeId)) { null -> cont.resume(null) is ImageView -> { if (hasMeasuredDrawable(view)) { resume(view, cont) } else { resumeOnImageLoad(view, cont) } } else -> cont.resume(view) } } private fun resume(view: ImageView, cont: Continuation<View?>) { if (view.drawable is RootDrawable) { view.post { cont.resume(view) } } else { cont.resume(view) } } private fun resumeOnImageLoad(view: ImageView, cont: Continuation<View?>) { view.doOnPreDraw { if (hasMeasuredDrawable(view)) { view.post { cont.resume(view) } } else { resumeOnImageLoad(view, cont) } } } private fun hasMeasuredDrawable(view: ImageView) = when (view.drawable) { is RootDrawable -> true else -> checkIfFastImageIsMeasured(view) } private fun checkIfFastImageIsMeasured(view: ImageView) = with(view.drawable) { this != null && intrinsicWidth != -1 && intrinsicHeight != -1 && isImageScaledToFit(view) } private fun Drawable.isImageScaledToFit(view: ImageView): Boolean { val scaleX = view.width / intrinsicWidth.toFloat() val scaleY = view.height / intrinsicHeight.toFloat() return min(scaleX, scaleY) >= 1f } }
mit
af331bcf33751f40f23b340a0df34dbe
33.015385
108
0.630936
4.625523
false
false
false
false
InsertKoinIO/koin
core/koin-core/src/commonTest/kotlin/org/koin/core/LazyInstanceResolution.kt
1
3142
package org.koin.core import kotlin.test.Test import org.koin.Simple import org.koin.core.logger.Level import org.koin.dsl.koinApplication import org.koin.dsl.module import kotlin.test.assertEquals class LazyInstanceResolution { @Test fun `can lazy resolve a single`() { val app = koinApplication { modules( module { single { Simple.ComponentA() } }) } val koin = app.koin val a: Simple.ComponentA = koin.get() val a2: Simple.ComponentA = koin.get() assertEquals(a, a2) } @Test fun `create eager`() { var i = 0 val app = koinApplication { printLogger(Level.DEBUG) modules( module(createdAtStart = true) { single { i++; Simple.ComponentA() } }) createEagerInstances() } val koin = app.koin assertEquals(1,i) koin.get<Simple.ComponentA>() assertEquals(1,i) } @Test fun `create eager twice`() { var i = 0 val app = koinApplication { printLogger(Level.DEBUG) modules( module(createdAtStart = true) { single { i++; Simple.ComponentA() } }) createEagerInstances() } val koin = app.koin assertEquals(1,i) koin.createEagerInstances() assertEquals(1,i) } @Test fun `create eager definitions different modules - by default`() { var i = 0 val app = koinApplication { printLogger(Level.DEBUG) modules( module(createdAtStart = true) { single { i++; Simple.ComponentA() } }, module(createdAtStart = true) { single { i++; Simple.ComponentB(get()) } }) createEagerInstances() } val koin = app.koin assertEquals(2,i) koin.get<Simple.ComponentA>() koin.get<Simple.ComponentB>() assertEquals(2,i) } @Test fun `create eager definitions different modules - one eager`() { var i = 0 val app = koinApplication { printLogger(Level.DEBUG) modules( module { single { i++; Simple.ComponentA() } }, module(createdAtStart = true) { single { i++; Simple.ComponentB(get()) } }) createEagerInstances() } val koin = app.koin assertEquals(2,i) koin.get<Simple.ComponentA>() koin.get<Simple.ComponentB>() assertEquals(2,i) } @Test fun `eager definitions module`() { val module = module(createdAtStart = true) { single { Simple.ComponentA() } factory { Simple.ComponentB(get()) } scope<Simple.ComponentB> { scoped { Simple.ComponentC(get()) } } } assertEquals(1,module.eagerInstances.size) } }
apache-2.0
ed9bbc895fb3d7d72fe1e77607407c99
25.191667
70
0.501273
4.789634
false
true
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/classes/kt725.kt
3
158
operator fun Int?.inc() = this!!.inc() public fun box() : String { var i : Int? = 10 val j = i++ return if(j==10 && 11 == i) "OK" else "fail" }
apache-2.0
a2cdd22938073c197e82a1e7451e616b
18.75
48
0.506329
2.821429
false
false
false
false
Commit451/GitLabAndroid
app/src/main/java/com/commit451/gitlab/activity/LoadSomeInfoActivity.kt
2
8565
package com.commit451.gitlab.activity import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import com.commit451.gitlab.App import com.commit451.gitlab.R import com.commit451.gitlab.extension.with import com.commit451.gitlab.model.api.Project import com.commit451.gitlab.navigation.Navigator import kotlinx.android.synthetic.main.activity_loading.* import timber.log.Timber /** * Intermediate activity when deep linking to another activity and things need to load */ class LoadSomeInfoActivity : BaseActivity() { companion object { private const val EXTRA_LOAD_TYPE = "load_type" private const val EXTRA_PROJECT_NAMESPACE = "project_namespace" private const val EXTRA_PROJECT_NAME = "project_name" private const val EXTRA_COMMIT_SHA = "extra_commit_sha" private const val EXTRA_MERGE_REQUEST = "merge_request" private const val EXTRA_BUILD_ID = "build_id" private const val EXTRA_MILESTONE_ID = "milestone_id" private const val EXTRA_ISSUE_ID = "issue_id" private const val LOAD_TYPE_DIFF = 0 private const val LOAD_TYPE_MERGE_REQUEST = 1 private const val LOAD_TYPE_BUILD = 2 private const val LOAD_TYPE_MILESTONE = 3 private const val LOAD_TYPE_ISSUE = 4 fun newIntent(context: Context, namespace: String, projectName: String, commitSha: String): Intent { val intent = Intent(context, LoadSomeInfoActivity::class.java) intent.putExtra(EXTRA_PROJECT_NAMESPACE, namespace) intent.putExtra(EXTRA_PROJECT_NAME, projectName) intent.putExtra(EXTRA_COMMIT_SHA, commitSha) intent.putExtra(EXTRA_LOAD_TYPE, LOAD_TYPE_DIFF) return intent } fun newIssueIntent(context: Context, namespace: String, projectName: String, issueId: String): Intent { val intent = Intent(context, LoadSomeInfoActivity::class.java) intent.putExtra(EXTRA_PROJECT_NAMESPACE, namespace) intent.putExtra(EXTRA_PROJECT_NAME, projectName) intent.putExtra(EXTRA_ISSUE_ID, issueId) intent.putExtra(EXTRA_LOAD_TYPE, LOAD_TYPE_ISSUE) return intent } fun newMergeRequestIntent(context: Context, namespace: String, projectName: String, mergeRequestId: String): Intent { val intent = Intent(context, LoadSomeInfoActivity::class.java) intent.putExtra(EXTRA_PROJECT_NAMESPACE, namespace) intent.putExtra(EXTRA_PROJECT_NAME, projectName) intent.putExtra(EXTRA_MERGE_REQUEST, mergeRequestId) intent.putExtra(EXTRA_LOAD_TYPE, LOAD_TYPE_MERGE_REQUEST) return intent } fun newBuildIntent(context: Context, namespace: String, projectName: String, buildId: Long): Intent { val intent = Intent(context, LoadSomeInfoActivity::class.java) intent.putExtra(EXTRA_PROJECT_NAMESPACE, namespace) intent.putExtra(EXTRA_PROJECT_NAME, projectName) intent.putExtra(EXTRA_BUILD_ID, buildId) intent.putExtra(EXTRA_LOAD_TYPE, LOAD_TYPE_BUILD) return intent } fun newMilestoneIntent(context: Context, namespace: String, projectName: String, milestoneIid: String): Intent { val intent = Intent(context, LoadSomeInfoActivity::class.java) intent.putExtra(EXTRA_PROJECT_NAMESPACE, namespace) intent.putExtra(EXTRA_PROJECT_NAME, projectName) intent.putExtra(EXTRA_MILESTONE_ID, milestoneIid) intent.putExtra(EXTRA_LOAD_TYPE, LOAD_TYPE_MILESTONE) return intent } } private var loadType: Int = 0 private var project: Project? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_loading) root.setOnClickListener { finish() } progress.visibility = View.VISIBLE loadType = intent.getIntExtra(EXTRA_LOAD_TYPE, -1) Timber.d("Loading some info type: %d", loadType) when (loadType) { LOAD_TYPE_DIFF, LOAD_TYPE_MERGE_REQUEST, LOAD_TYPE_BUILD, LOAD_TYPE_MILESTONE, LOAD_TYPE_ISSUE -> { val namespace = intent.getStringExtra(EXTRA_PROJECT_NAMESPACE)!! val project = intent.getStringExtra(EXTRA_PROJECT_NAME)!! App.get().gitLab.getProject(namespace, project) .with(this) .subscribe({ loadNextPart(it) }, { Timber.e(it) [email protected]() }) } } } override fun finish() { super.finish() overridePendingTransition(R.anim.do_nothing, R.anim.fade_out) } fun loadNextPart(response: Project) { project = response when (loadType) { LOAD_TYPE_ISSUE -> { val issueId = intent.getStringExtra(EXTRA_ISSUE_ID)!! App.get().gitLab.getIssue(response.id, issueId) .with(this) .subscribe({ Navigator.navigateToIssue(this@LoadSomeInfoActivity, project!!, it) finish() }, { Timber.e(it) [email protected]() }) return } LOAD_TYPE_DIFF -> { val sha = intent.getStringExtra(EXTRA_COMMIT_SHA)!! App.get().gitLab.getCommit(response.id, sha) .with(this) .subscribe({ Navigator.navigateToDiffActivity(this@LoadSomeInfoActivity, project!!, it) finish() }, { Timber.e(it) [email protected]() }) return } LOAD_TYPE_MERGE_REQUEST -> { val mergeRequestId = intent.getStringExtra(EXTRA_MERGE_REQUEST)!! App.get().gitLab.getMergeRequestsByIid(response.id, mergeRequestId) .with(this) .subscribe({ if (it.isNotEmpty()) { Navigator.navigateToMergeRequest(this, project!!, it.first()) finish() } else { [email protected]() } }, { Timber.e(it) [email protected]() }) return } LOAD_TYPE_BUILD -> { val buildId = intent.getLongExtra(EXTRA_BUILD_ID, -1) App.get().gitLab.getBuild(response.id, buildId) .with(this) .subscribe({ Navigator.navigateToBuild(this, project!!, it) finish() }, { Timber.e(it) [email protected]() }) return } LOAD_TYPE_MILESTONE -> { val milestoneId = intent.getStringExtra(EXTRA_MILESTONE_ID)!! App.get().gitLab.getMilestonesByIid(response.id, milestoneId) .with(this) .subscribe({ if (it.isNotEmpty()) { Navigator.navigateToMilestone(this@LoadSomeInfoActivity, project!!, it.first()) finish() } else { [email protected]() } }, { Timber.e(it) [email protected]() }) return } } } private fun onError() { Toast.makeText(this@LoadSomeInfoActivity, R.string.failed_to_load, Toast.LENGTH_SHORT) .show() finish() } }
apache-2.0
7e97a7312ba68770974630a26694b4fd
40.985294
125
0.539405
5.059067
false
false
false
false
arieled91/openweather
src/main/kotlin/com/github/openweather/controller/CurrentWeatherController.kt
1
2911
package com.github.openweather.controller import com.github.openweather.business.CurrentWeather import com.github.openweather.business.LocationCoordinate import com.github.openweather.client.LocationClient import com.github.openweather.repository.CurrentWeatherRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.* import java.util.* import javax.servlet.http.HttpServletRequest @RestController @RequestMapping("/weather/") open class CurrentWeatherController { @Autowired lateinit var repository: CurrentWeatherRepository @CrossOrigin("*") @RequestMapping(value = "current/{id}", method= arrayOf(RequestMethod.GET)) open fun currentWeather( @PathVariable("id") id: Int, @RequestParam("lang") lang: Optional<String> ): CurrentWeather { val currentWeather = repository.find(id, lang.orElse(null)) return currentWeather } @CrossOrigin("*") @RequestMapping(value = "current", method= arrayOf(RequestMethod.GET)) open fun currentWeather( @RequestParam("lat") lat: Double, @RequestParam("lon") lon: Double, @RequestParam("lang") lang: Optional<String> ) : CurrentWeather { val currentWeather = repository.findByCoordinates(lat, lon, lang.orElse(null)) return currentWeather } @CrossOrigin("*") @RequestMapping(value = "current/ip/{ip}", method= arrayOf(RequestMethod.GET)) open fun currentWeatherByIpAddress( @PathVariable("ip") ip: String, @RequestParam("lang") lang: Optional<String>, request : HttpServletRequest ): CurrentWeather { val coordinates = LocationClient.getCoordinatesByIpAddress(ip).orElse(LocationCoordinate()) val currentWeather = repository.findByCoordinates(coordinates.lat, coordinates.lon, lang.orElse(null)) currentWeather.city = coordinates.city return currentWeather } @CrossOrigin("*") @RequestMapping(value = "current/ip", method= arrayOf(RequestMethod.GET)) open fun currentWeatherByIpAddress( @RequestParam("lang") lang: Optional<String>, request : HttpServletRequest ): CurrentWeather { val ipAddress = ipAddress(request) if(ipAddress==null || ipAddress.isBlank()) return CurrentWeather() val coordinates = LocationClient.getCoordinatesByIpAddress(ipAddress).orElse(LocationCoordinate()) val currentWeather = repository.findByCoordinates(coordinates.lat, coordinates.lon, lang.orElse(null)) return currentWeather } fun ipAddress(request: HttpServletRequest) : String?{ var remoteAddr = request.getHeader("X-FORWARDED-FOR") if (remoteAddr == null || "" == remoteAddr) { remoteAddr = request.remoteAddr } return remoteAddr } }
apache-2.0
38b172b61123012d1418eaa3d50f4787
36.320513
110
0.693233
4.859766
false
false
false
false
ShadwLink/Shadow-Mapper
src/main/java/nl/shadowlink/tools/shadowlib/ide/IDE.kt
1
9185
package nl.shadowlink.tools.shadowlib.ide import nl.shadowlink.tools.shadowlib.utils.Constants import nl.shadowlink.tools.shadowlib.utils.GameType import nl.shadowlink.tools.shadowlib.utils.saving.Saveable import nl.shadowlink.tools.shadowlib.utils.saving.SaveableFile import java.io.* import java.util.logging.Level import java.util.logging.Logger /** * @author Shadow-Link */ class IDE( var fileName: String, var gameType: GameType, autoLoad: Boolean ) : Saveable by SaveableFile() { private var fileReader: FileReader? = null private var input: BufferedReader? = null private var readItem = -1 //used to identify what type of section we are reading val itemObjs = mutableListOf<ItemObject>() val itemTobj = mutableListOf<ItemTimedObject>() val itemTree = mutableListOf<ItemTree>() val itemPath = mutableListOf<ItemPath>() val itemAnim = mutableListOf<ItemAnimated>() val itemTAnm = mutableListOf<ItemTimedAnimated>() val itemMlo = mutableListOf<ItemMlo>() val item2dfx = mutableListOf<Item2DFX>() val itemsAMat = mutableListOf<ItemAnimatedMaterial>() val itemTxdp = mutableListOf<ItemTxdPack>() val itemCars = mutableListOf<ItemCars>() init { if (autoLoad) loadIDE() } private fun loadIDE(): Boolean { if (openIDE()) { try { var line: String? = null while (input!!.readLine().also { line = it } != null) { if (readItem == -1) { if (line!!.startsWith("#")) { println("Commentaar: $line") } else if (line!!.startsWith("2dfx")) { readItem = Constants.i2DFX } else if (line!!.startsWith("anim")) { readItem = Constants.iANIM } else if (line!!.startsWith("cars")) { readItem = Constants.iCARS } else if (line!!.startsWith("hier")) { readItem = Constants.iHIER } else if (line!!.startsWith("mlo")) { readItem = Constants.iMLO } else if (line!!.startsWith("objs")) { readItem = Constants.iOBJS } else if (line!!.startsWith("path")) { readItem = Constants.iPATH } else if (line!!.startsWith("peds")) { readItem = Constants.iPEDS } else if (line!!.startsWith("tanm")) { readItem = Constants.iTANM } else if (line!!.startsWith("tobj")) { readItem = Constants.iTOBJ } else if (line!!.startsWith("tree")) { readItem = Constants.iTREE } else if (line!!.startsWith("txdp")) { readItem = Constants.iTXDP } else if (line!!.startsWith("weap")) { readItem = Constants.iWEAP } //Message.displayMsgHigh("Started reading item " + readItem); } else { if (line!!.startsWith("end")) { //Message.displayMsgHigh("Item " + readItem + " ended"); readItem = -1 } else if (line!!.startsWith("#")) { println("Comment: $line") } else if (line!!.isEmpty()) { println("Empty line") } else { var item: IdeItem? = null when (readItem) { Constants.i2DFX -> item = Item2DFX(gameType) Constants.iANIM -> item = ItemAnimated(gameType) Constants.iCARS -> { item = ItemCars(gameType) itemCars.add(item) } Constants.iHIER -> item = ItemHier(gameType) Constants.iMLO -> item = ItemMlo(gameType) Constants.iOBJS -> { item = ItemObject(gameType) itemObjs.add(item) } Constants.iPATH -> item = ItemPath(gameType) Constants.iPEDS -> item = ItemPeds(gameType) Constants.iTANM -> item = ItemTimedAnimated(gameType) Constants.iTOBJ -> { item = ItemTimedObject(gameType) itemTobj.add(item) } Constants.iTREE -> item = ItemTree(gameType) Constants.iTXDP -> { item = ItemTxdPack(gameType) itemTxdp.add(item) } Constants.iWEAP -> item = ItemWeapon(gameType) else -> {} } item!!.read(line!!) } } } closeIDE() } catch (ex: IOException) { Logger.getLogger(IDE::class.java.name).log(Level.SEVERE, null, ex) } } else { //Message.displayMsgHigh("Unable to open file: " + fileName); } return true } fun findItem(name: String): IdeItem? { var ret: IdeItem? = null if (itemObjs.size != 0) { var i = 0 var item = itemObjs[i] while (item.modelName != name) { item = if (i < itemObjs.size - 1) { i++ itemObjs[i] } else { break } } if (item.modelName == name) { //Message.displayMsgSuper("<IDE " + fileName + ">Found file " + name + " at " + i); ret = itemObjs[i] } else { //Message.displayMsgSuper("<IDE " + fileName + ">Unable to find file " + name); } } return ret } fun openIDE(): Boolean { try { fileReader = FileReader(fileName) input = BufferedReader(fileReader) } catch (ex: IOException) { return false } return true } fun closeIDE(): Boolean { try { input!!.close() fileReader!!.close() } catch (ex: IOException) { return false } return true } fun save() { try { var fileWriter: FileWriter? = null var output: BufferedWriter? = null fileWriter = FileWriter(fileName) output = BufferedWriter(fileWriter) output.write("objs") output.newLine() itemObjs.forEach { it.save(output) } output.write("end") output.newLine() output.write("tobj") output.newLine() itemTobj.forEach { it.save(output) } output.write("end") output.newLine() output.write("tree") output.newLine() itemTree.forEach { it.save(output) } output.write("end") output.newLine() output.write("path") output.newLine() itemPath.forEach { it.save(output) } output.write("end") output.newLine() output.write("anim") output.newLine() itemAnim.forEach { it.save(output) } output.write("end") output.newLine() output.write("tanm") output.newLine() itemTAnm.forEach { it.save(output) } output.write("end") output.newLine() output.write("mlo") output.newLine() itemMlo.forEach { it.save(output) } output.write("end") output.newLine() output.write("2dfx") output.newLine() item2dfx.forEach { it.save(output) } output.write("end") output.newLine() output.write("amat") output.newLine() itemsAMat.forEach { it.save(output) } output.write("end") output.newLine() output.write("txdp") output.newLine() itemTxdp.forEach { it.save(output) } output.write("end") output.newLine() output.flush() output.close() fileWriter.close() } catch (ex: IOException) { Logger.getLogger(IDE::class.java.name).log(Level.SEVERE, null, ex) } } }
gpl-2.0
c249ffea919c489d689a763e6a1f2489
37.923729
99
0.446271
4.96755
false
false
false
false
Mindera/skeletoid
base/src/main/java/com/mindera/skeletoid/webview/cookies/CookiesUtils.kt
1
1369
package com.mindera.skeletoid.webview.cookies import android.webkit.CookieManager import com.mindera.skeletoid.logs.LOG object CookiesUtils { private const val LOG_TAG = "CookiesUtils" fun getCookiesFromUrl(url: String): String { val cookieManager = CookieManager.getInstance() return cookieManager.getCookie(url).orEmpty() } fun getCookiesFromUrlToMap(url: String): HashMap<String, String> { val cookies = getCookiesFromUrl(url) return getCookiesToMap(cookies) } fun getCookieValue(url: String, cookieName: String): String? { return getCookiesFromUrlToMap(url).filter { it.key.contains(cookieName) }[cookieName] } fun getCookiesToMap(cookies: String): HashMap<String, String> { val cookiesMap = HashMap<String, String>() val cookieList = cookies.split(";").map { it.trim() }.dropLastWhile { it.isEmpty() } .toTypedArray() for (cookiePair in cookieList) { val cookiePairAsList = cookiePair.split("=", limit = 2).dropLastWhile { it.isEmpty() }.toTypedArray() if (cookiePairAsList.size == 2) { cookiesMap[cookiePairAsList[0]] = cookiePairAsList[1] } else { LOG.e(LOG_TAG, "Cookie is malformed, skipping: $cookiePairAsList") } } return cookiesMap } }
mit
eae91436dafde13edc3b8ef3299cff90
29.444444
113
0.645727
4.401929
false
false
false
false
exponentjs/exponent
packages/expo-modules-core/android/src/main/java/expo/modules/core/utilities/KotlinUtilities.kt
2
761
package expo.modules.core.utilities /** * Returns receiver, or block result if the receiver is `null` * * A more semantic equivalent to: `nullable ?: run { ... }`: * ``` * val nonNullable1 = sthNullable.ifNull { ... } * val nonNullable2 = sthNullable ?: run { ... } * ``` */ inline fun <T> T?.ifNull(block: () -> T): T = this ?: block() /** * If the receiver is instance of `T`, returns the receiver, otherwise returns `null` * * Works the same as the `as?` operator, but allows method chaining without parentheses: * ``` * val x = a.b.takeIfInstanceOf<Number>?.someMethod() * val y = (a.b as? Number)?.someMethod() // same, but needs parenthesis * ``` */ inline fun <reified T> Any?.takeIfInstanceOf(): T? = if (this is T) this else null
bsd-3-clause
b1b336eb16ee200b9e93944db13ac620
32.086957
88
0.634691
3.490826
false
false
false
false
MaTriXy/material-dialogs
datetime/src/main/java/com/afollestad/materialdialogs/datetime/internal/WrapContentViewPager.kt
2
1991
/** * Designed and developed by Aidan Follestad (@afollestad) * * 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.afollestad.materialdialogs.datetime.internal import android.content.Context import android.util.AttributeSet import android.view.View import android.view.View.MeasureSpec.EXACTLY import android.view.View.MeasureSpec.UNSPECIFIED import androidx.viewpager.widget.ViewPager import com.afollestad.materialdialogs.utils.MDUtil.ifNotZero internal class WrapContentViewPager( context: Context, attrs: AttributeSet? = null ) : ViewPager(context, attrs) { override fun onMeasure( widthMeasureSpec: Int, heightMeasureSpec: Int ) { var newHeightSpec = heightMeasureSpec var maxChildHeight = 0 forEachChild { child -> child.measure( widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, UNSPECIFIED) ) val h = child.measuredHeight if (h > maxChildHeight) { maxChildHeight = h } } val maxAllowedHeightFromParent = MeasureSpec.getSize(heightMeasureSpec) if (maxChildHeight > maxAllowedHeightFromParent) { maxChildHeight = maxAllowedHeightFromParent } maxChildHeight.ifNotZero { newHeightSpec = MeasureSpec.makeMeasureSpec(it, EXACTLY) } super.onMeasure(widthMeasureSpec, newHeightSpec) } private fun forEachChild(each: (View) -> Unit) { for (i in 0 until childCount) { val child = getChildAt(i) each(child) } } }
apache-2.0
1a017455440b8b2856dc15653779d6a0
28.716418
75
0.725766
4.577011
false
false
false
false
PolymerLabs/arcs
java/arcs/core/entity/testutil/StorableReferencableEntity.kt
1
1388
package arcs.core.entity.testutil import arcs.core.common.Id import arcs.core.common.Referencable import arcs.core.common.ReferenceId import arcs.core.data.Capability.Ttl import arcs.core.data.RawEntity import arcs.core.data.Schema import arcs.core.data.SchemaFields import arcs.core.data.SchemaName import arcs.core.entity.Entity import arcs.core.entity.EntitySpec import arcs.core.entity.Storable import arcs.core.util.Time /** * A fake entity class, that implements both - [Storable] and [Referencable] interfaces and used for * Handles classes tests. */ class StorableReferencableEntity( override val id: ReferenceId, override val entityId: String? = null, override val creationTimestamp: Long = RawEntity.UNINITIALIZED_TIMESTAMP, override val expirationTimestamp: Long = RawEntity.UNINITIALIZED_TIMESTAMP ) : Entity, Storable, Referencable { override fun ensureEntityFields( idGenerator: Id.Generator, handleName: String, time: Time, ttl: Ttl ) {} final override fun reset() {} override fun serialize(storeSchema: Schema?) = RawEntity() companion object : EntitySpec<StorableReferencableEntity> { override val SCHEMA = Schema( setOf(SchemaName("StorableReferencableEntity")), SchemaFields(emptyMap(), emptyMap()), "abc123" ) override fun deserialize(data: RawEntity) = StorableReferencableEntity("fake") } }
bsd-3-clause
7972fcd69824fdb30aa037ce7007b1df
29.173913
100
0.760807
4.218845
false
false
false
false
SourceUtils/hl2-toolkit
src/main/kotlin/com/timepath/hl2/io/util/Vector3f.kt
1
366
package com.timepath.hl2.io.util import com.timepath.io.struct.StructField public class Vector3f(x: Float = 0f, y: Float = 0f, z: Float = 0f) { StructField(index = 0) private val x: Float = x StructField(index = 1) private val y: Float = y StructField(index = 2) private val z: Float = z override fun toString() = "vec3($x, $y, $z)" }
artistic-2.0
53e29802a1fbaaad8ea4e5368b91afe2
25.142857
68
0.639344
3.07563
false
false
false
false
LittleLightCz/SheepsGoHome
core/src/com/sheepsgohome/gameobjects/Wall.kt
1
793
package com.sheepsgohome.gameobjects import com.badlogic.gdx.Gdx import com.badlogic.gdx.physics.box2d.Body import com.badlogic.gdx.physics.box2d.BodyDef import com.badlogic.gdx.physics.box2d.PolygonShape import com.badlogic.gdx.physics.box2d.World abstract class Wall(world: World) { protected val body: Body init { val bodyDef = BodyDef().apply { position.set(0f, 0f) type = BodyDef.BodyType.StaticBody } val boxShape = PolygonShape().apply { setAsBox(0.1f, Math.max(Gdx.graphics.width, Gdx.graphics.height).toFloat()) } body = world.createBody(bodyDef) body.createFixture(boxShape, 0.0f) body.userData = this boxShape.dispose() } abstract fun setDefaultPosition() }
gpl-3.0
d1e63f02cb95a64edff46b3022ba1db8
23.8125
87
0.667087
3.654378
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/reader/discover/ReaderInterestAdapter.kt
1
1962
package org.wordpress.android.ui.reader.discover import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.DiffUtil.Callback import androidx.recyclerview.widget.RecyclerView.Adapter import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState.ReaderInterestUiState import org.wordpress.android.ui.reader.discover.viewholders.ReaderInterestViewHolder import org.wordpress.android.ui.utils.UiHelpers class ReaderInterestAdapter( private val uiHelpers: UiHelpers ) : Adapter<ReaderInterestViewHolder>() { private val items = mutableListOf<ReaderInterestUiState>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ReaderInterestViewHolder { return ReaderInterestViewHolder(uiHelpers, parent) } override fun getItemCount(): Int = items.size override fun onBindViewHolder(holder: ReaderInterestViewHolder, position: Int) { holder.onBind(items[position]) } fun update(newItems: List<ReaderInterestUiState>) { val diffResult = DiffUtil.calculateDiff(InterestDiffUtil(items, newItems)) items.clear() items.addAll(newItems) diffResult.dispatchUpdatesTo(this) } class InterestDiffUtil( private val oldList: List<ReaderInterestUiState>, private val newList: List<ReaderInterestUiState> ) : Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val newItem = newList[newItemPosition] val oldItem = oldList[oldItemPosition] return (oldItem == newItem) } override fun getOldListSize(): Int = oldList.size override fun getNewListSize(): Int = newList.size override fun areContentsTheSame( oldItemPosition: Int, newItemPosition: Int ): Boolean = oldList[oldItemPosition] == newList[newItemPosition] } }
gpl-2.0
a7cedd9ffa8d0951232cb240e2c8234c
36.730769
114
0.733945
5.218085
false
false
false
false
y20k/transistor
app/src/main/java/org/y20k/transistor/core/Collection.kt
1
1631
/* * Collection.kt * Implements the Collection class * A Collection object holds a list of radio stations * * This file is part of * TRANSISTOR - Radio App for Android * * Copyright (c) 2015-22 - Y20K.org * Licensed under the MIT-License * http://opensource.org/licenses/MIT */ package org.y20k.transistor.core import android.os.Parcelable import androidx.annotation.Keep import com.google.gson.annotations.Expose import kotlinx.parcelize.Parcelize import org.y20k.transistor.Keys import java.util.* /* * Collection class */ @Keep @Parcelize data class Collection(@Expose val version: Int = Keys.CURRENT_COLLECTION_CLASS_VERSION_NUMBER, @Expose var stations: MutableList<Station> = mutableListOf<Station>(), @Expose var modificationDate: Date = Date()) : Parcelable { /* overrides toString method */ override fun toString(): String { val stringBuilder: StringBuilder = StringBuilder() stringBuilder.append("Format version: $version\n") stringBuilder.append("Number of stations in collection: ${stations.size}\n\n") stations.forEach { stringBuilder.append("${it.toString()}\n") } return stringBuilder.toString() } /* Creates a deep copy of a Collection */ fun deepCopy(): Collection { val stationsCopy: MutableList<Station> = mutableListOf<Station>() stations.forEach { stationsCopy.add(it.deepCopy()) } return Collection(version = version, stations = stationsCopy, modificationDate = modificationDate) } }
mit
5fd75b8bffb9d132cd2368ee2b9c1cc5
29.203704
94
0.66401
4.493113
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/sitecreation/sitename/SiteCreationSiteNameViewModel.kt
1
2341
package org.wordpress.android.ui.sitecreation.sitename import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.ui.sitecreation.misc.SiteCreationTracker import org.wordpress.android.viewmodel.SingleLiveEvent import javax.inject.Inject import javax.inject.Named import kotlin.coroutines.CoroutineContext @HiltViewModel class SiteCreationSiteNameViewModel @Inject constructor( private val analyticsTracker: SiteCreationTracker, @Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher ) : ViewModel(), CoroutineScope { private val job = Job() override val coroutineContext: CoroutineContext get() = bgDispatcher + job private var isInitialized = false private val _onSkipButtonPressed = SingleLiveEvent<Unit>() val onSkipButtonPressed: LiveData<Unit> = _onSkipButtonPressed private val _onBackButtonPressed = SingleLiveEvent<Unit>() val onBackButtonPressed: LiveData<Unit> = _onBackButtonPressed private val _onSiteNameEntered = SingleLiveEvent<String>() val onSiteNameEntered: LiveData<String> = _onSiteNameEntered private val _uiState: MutableLiveData<SiteNameUiState> = MutableLiveData() val uiState: LiveData<SiteNameUiState> = _uiState fun start() { if (isInitialized) return analyticsTracker.trackSiteNameViewed() isInitialized = true } fun onSkipPressed() { analyticsTracker.trackSiteNameSkipped() _onSkipButtonPressed.call() } fun onBackPressed() { analyticsTracker.trackSiteNameCanceled() _onBackButtonPressed.call() } fun onSiteNameEntered() { uiState.value?.siteName.let { if (it.isNullOrBlank()) return analyticsTracker.trackSiteNameEntered(it) _onSiteNameEntered.value = it } } fun onSiteNameChanged(siteName: String) { _uiState.value = SiteNameUiState(siteName) } data class SiteNameUiState(val siteName: String) { val isContinueButtonEnabled get() = siteName.isNotBlank() } }
gpl-2.0
1fce9d76eb94108670ccbbed17dbc194
31.971831
78
0.744981
4.856846
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/dependencies/JavaClassesInScriptDependenciesShortNameCache.kt
1
2206
// 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.core.script.dependencies import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import com.intellij.psi.impl.java.stubs.index.JavaShortClassNameIndex import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiShortNamesCache import com.intellij.psi.stubs.StubIndex import com.intellij.util.Processor import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager // Allow searching java classes in jars in script dependencies, this is needed for stuff like completion and autoimport class JavaClassesInScriptDependenciesShortNameCache(private val project: Project) : PsiShortNamesCache() { override fun getAllClassNames() = emptyArray<String>() override fun getClassesByName(name: String, scope: GlobalSearchScope): Array<out PsiClass> { val classpathScope = ScriptConfigurationManager.getInstance(project).getAllScriptsDependenciesClassFilesScope() val classes = StubIndex.getElements( JavaShortClassNameIndex.getInstance().key, name, project, classpathScope.intersectWith(scope), PsiClass::class.java ) return classes.toTypedArray() } override fun getMethodsByName(name: String, scope: GlobalSearchScope): Array<PsiMethod> = PsiMethod.EMPTY_ARRAY override fun getAllMethodNames() = emptyArray<String>() override fun getFieldsByName(name: String, scope: GlobalSearchScope): Array<PsiField> = PsiField.EMPTY_ARRAY override fun getMethodsByNameIfNotMoreThan(name: String, scope: GlobalSearchScope, maxCount: Int): Array<PsiMethod> = PsiMethod.EMPTY_ARRAY override fun processMethodsWithName( name: String, scope: GlobalSearchScope, processor: Processor<in PsiMethod> ) = true override fun getAllFieldNames() = emptyArray<String>() override fun getFieldsByNameIfNotMoreThan(name: String, scope: GlobalSearchScope, maxCount: Int): Array<PsiField> = PsiField.EMPTY_ARRAY }
apache-2.0
698f735f03051c25fa8159646909d0a6
48.044444
158
0.783772
4.785249
false
false
false
false
MER-GROUP/intellij-community
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/LineBreakpointManager.kt
3
8867
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.icons.AllIcons import com.intellij.openapi.util.Ref import com.intellij.util.SmartList import com.intellij.util.containers.putValue import com.intellij.util.containers.remove import com.intellij.xdebugger.XSourcePosition import com.intellij.xdebugger.breakpoints.XLineBreakpoint import gnu.trove.THashMap import gnu.trove.THashSet import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.resolvedPromise import java.util.concurrent.atomic.AtomicBoolean abstract class LineBreakpointManager(private val debugProcess: DebugProcessImpl<*>) { private val ideToVmBreakpoints = THashMap<XLineBreakpoint<*>, MutableList<Breakpoint>>() protected val vmToIdeBreakpoints = THashMap<Breakpoint, MutableList<XLineBreakpoint<*>>>() private val runToLocationBreakpoints = THashSet<Breakpoint>() private val lock = Object() private val breakpointManager: BreakpointManager get() = debugProcess.vm!!.breakpointManager open fun isAnyFirstLineBreakpoint(breakpoint: Breakpoint) = false private val breakpointResolvedListenerAdded = AtomicBoolean() fun setBreakpoint(breakpoint: XLineBreakpoint<*>) { var target = synchronized (lock) { ideToVmBreakpoints[breakpoint] } if (target == null) { setBreakpoint(breakpoint, debugProcess.getLocationsForBreakpoint(breakpoint)) } else { val breakpointManager = breakpointManager for (vmBreakpoint in target) { if (!vmBreakpoint.enabled) { vmBreakpoint.enabled = true breakpointManager.flush(vmBreakpoint).rejected { debugProcess.session.updateBreakpointPresentation(breakpoint, AllIcons.Debugger.Db_invalid_breakpoint, it.message) } } } } } fun removeBreakpoint(breakpoint: XLineBreakpoint<*>, temporary: Boolean): Promise<*> { val disable = temporary && breakpointManager.getMuteMode() !== BreakpointManager.MUTE_MODE.NONE beforeBreakpointRemoved(breakpoint, disable) return doRemoveBreakpoint(breakpoint, disable) } protected open fun beforeBreakpointRemoved(breakpoint: XLineBreakpoint<*>, disable: Boolean) { } fun doRemoveBreakpoint(breakpoint: XLineBreakpoint<*>, disable: Boolean = false): Promise<*> { var vmBreakpoints: Collection<Breakpoint> = emptySet() synchronized (lock) { if (disable) { val list = ideToVmBreakpoints[breakpoint] ?: return resolvedPromise() val iterator = list.iterator() vmBreakpoints = list while (iterator.hasNext()) { val vmBreakpoint = iterator.next() if ((vmToIdeBreakpoints[vmBreakpoint]?.size ?: -1) > 1) { // we must not disable vm breakpoint - it is used for another ide breakpoints iterator.remove() } } } else { vmBreakpoints = ideToVmBreakpoints.remove(breakpoint) ?: return resolvedPromise() if (!vmBreakpoints.isEmpty()) { for (vmBreakpoint in vmBreakpoints) { vmToIdeBreakpoints.remove(vmBreakpoint, breakpoint) if (vmToIdeBreakpoints.containsKey(vmBreakpoint)) { // we must not remove vm breakpoint - it is used for another ide breakpoints return resolvedPromise() } } } } } if (vmBreakpoints.isEmpty()) { return resolvedPromise() } val breakpointManager = breakpointManager val promises = SmartList<Promise<*>>() if (disable) { for (vmBreakpoint in vmBreakpoints) { vmBreakpoint.enabled = false promises.add(breakpointManager.flush(vmBreakpoint)) } } else { for (vmBreakpoint in vmBreakpoints) { promises.add(breakpointManager.remove(vmBreakpoint)) } } return Promise.all(promises) } fun setBreakpoint(breakpoint: XLineBreakpoint<*>, locations: List<Location>, promiseRef: Ref<Promise<out Breakpoint>>? = null) { if (locations.isEmpty()) { return } val vmBreakpoints = SmartList<Breakpoint>() for (location in locations) { vmBreakpoints.add(doSetBreakpoint(breakpoint, location, false, promiseRef)) } synchronized (lock) { ideToVmBreakpoints.put(breakpoint, vmBreakpoints) for (vmBreakpoint in vmBreakpoints) { vmToIdeBreakpoints.putValue(vmBreakpoint, breakpoint) } } } protected fun doSetBreakpoint(breakpoint: XLineBreakpoint<*>?, location: Location, isTemporary: Boolean, promiseRef: Ref<Promise<out Breakpoint>>? = null): Breakpoint { if (breakpointResolvedListenerAdded.compareAndSet(false, true)) { breakpointManager.addBreakpointListener(object : BreakpointListener { override fun resolved(breakpoint: Breakpoint) { synchronized (lock) { vmToIdeBreakpoints[breakpoint] }?.let { for (ideBreakpoint in it) { debugProcess.session.updateBreakpointPresentation(ideBreakpoint, AllIcons.Debugger.Db_verified_breakpoint, null) } } } override fun errorOccurred(breakpoint: Breakpoint, errorMessage: String?) { if (isAnyFirstLineBreakpoint(breakpoint)) { return } if (synchronized (lock) { runToLocationBreakpoints.remove(breakpoint) }) { debugProcess.session.reportError("Cannot run to cursor: $errorMessage") return } synchronized (lock) { vmToIdeBreakpoints[breakpoint] } ?.let { for (ideBreakpoint in it) { debugProcess.session.updateBreakpointPresentation(ideBreakpoint, AllIcons.Debugger.Db_invalid_breakpoint, errorMessage) } } } override fun nonProvisionalBreakpointRemoved(breakpoint: Breakpoint) { synchronized (lock) { vmToIdeBreakpoints.remove(breakpoint)?.let { for (ideBreakpoint in it) { ideToVmBreakpoints.remove(ideBreakpoint, breakpoint) } it } } ?.let { for (ideBreakpoint in it) { setBreakpoint(ideBreakpoint, debugProcess.getLocationsForBreakpoint(ideBreakpoint)) } } } }) } val breakpointManager = breakpointManager val target = createTarget(breakpoint, breakpointManager, location, isTemporary) val condition = breakpoint?.conditionExpression return breakpointManager.setBreakpoint(target, location.line, location.column, condition?.expression, promiseRef = promiseRef) } protected abstract fun createTarget(breakpoint: XLineBreakpoint<*>?, breakpointManager: BreakpointManager, location: Location, isTemporary: Boolean): BreakpointTarget fun runToLocation(position: XSourcePosition) { val addedBreakpoints = doRunToLocation(position) if (addedBreakpoints.isEmpty()) { return } synchronized (lock) { runToLocationBreakpoints.addAll(addedBreakpoints) } debugProcess.resume() } protected abstract fun doRunToLocation(position: XSourcePosition): List<Breakpoint> fun isRunToCursorBreakpoints(breakpoints: List<Breakpoint>): Boolean { synchronized (runToLocationBreakpoints) { return runToLocationBreakpoints.containsAll(breakpoints) } } fun updateAllBreakpoints() { var array = synchronized (lock) { ideToVmBreakpoints.keys.toTypedArray() } for (breakpoint in array) { removeBreakpoint(breakpoint, false) setBreakpoint(breakpoint) } } fun removeAllBreakpoints(): org.jetbrains.concurrency.Promise<*> { synchronized (lock) { ideToVmBreakpoints.clear() vmToIdeBreakpoints.clear() runToLocationBreakpoints.clear() } return breakpointManager.removeAll() } fun clearRunToLocationBreakpoints() { var breakpoints = synchronized (lock) { if (runToLocationBreakpoints.isEmpty) { return@clearRunToLocationBreakpoints } var breakpoints = runToLocationBreakpoints.toArray<Breakpoint>(arrayOfNulls<Breakpoint>(runToLocationBreakpoints.size)) runToLocationBreakpoints.clear() breakpoints } val breakpointManager = breakpointManager for (breakpoint in breakpoints) { breakpointManager.remove(breakpoint) } } }
apache-2.0
6cedd98da45f7958129ac4cac07d840f
35.493827
175
0.692681
5.262315
false
false
false
false
android/play-billing-samples
ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/data/network/retrofit/PendingRequestCounter.kt
1
2964
/* * Copyright 2021 Google LLC. 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.subscriptions.data.network.retrofit import android.util.Log import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import java.util.concurrent.atomic.AtomicInteger /** * Keep track of all pending network requests and set [StateFlow] "loading" * to true when there remaining pending requests and false when all requests have been responded to. * * TODO(cassigbe@): Improve Pending requests count according to b/199924571. */ class PendingRequestCounter { /** * Track the number of pending server requests. */ private val pendingRequestCount = AtomicInteger() private val _loading = MutableStateFlow(false) /** * True when there are pending network requests. * This is used to show a progress bar in the UI. */ val loading: StateFlow<Boolean> = _loading.asStateFlow() /** * Executes the given [block] function while increase and decrease the counter. */ suspend inline fun <T> use(block: () -> T): T { increment() try { return block() } finally { decrement() } } /** * Increment request count and update loading value. * Must plan on calling [decrement] when the request completes. */ suspend fun increment() { val newCount = pendingRequestCount.incrementAndGet() Log.i(TAG, "Pending Server Requests: $newCount") if (newCount <= 0) { Log.e(TAG, "Unexpectedly low request count after new request: $newCount") _loading.emit(false) } else { _loading.emit(true) } } /** * Decrement request count and update loading value. * Must call [increment] each time a network call is made. * and call [decrement] when the server responds to the request. */ suspend fun decrement() { val newCount = pendingRequestCount.decrementAndGet() Log.i(TAG, "Pending Server Requests: $newCount") if (newCount < 0) { Log.w(TAG, "Unexpectedly negative request count: $newCount") _loading.emit(false) } else if (newCount == 0) { _loading.emit(false) } } companion object { private const val TAG = "RequestCounter" } }
apache-2.0
dc177acc273e427bfa2df0a982ab96ae
31.582418
100
0.65857
4.397626
false
false
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/keyboard/sticker/KeyboardStickerListAdapter.kt
2
3379
package org.thoughtcrime.securesms.keyboard.sticker import android.content.Context import android.view.View import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.database.model.StickerRecord import org.thoughtcrime.securesms.glide.cache.ApngOptions import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader.DecryptableUri import org.thoughtcrime.securesms.mms.GlideRequests import org.thoughtcrime.securesms.util.MappingAdapter import org.thoughtcrime.securesms.util.MappingModel import org.thoughtcrime.securesms.util.MappingViewHolder class KeyboardStickerListAdapter( private val glideRequests: GlideRequests, private val eventListener: EventListener?, private val allowApngAnimation: Boolean, ) : MappingAdapter() { init { registerFactory(Sticker::class.java, LayoutFactory(::StickerViewHolder, R.layout.sticker_keyboard_page_list_item)) registerFactory(StickerHeader::class.java, LayoutFactory(::StickerHeaderViewHolder, R.layout.sticker_grid_header)) } data class Sticker(override val packId: String, val stickerRecord: StickerRecord) : MappingModel<Sticker>, HasPackId { val uri: DecryptableUri get() = DecryptableUri(stickerRecord.uri) override fun areItemsTheSame(newItem: Sticker): Boolean { return packId == newItem.packId && stickerRecord.rowId == newItem.stickerRecord.rowId } override fun areContentsTheSame(newItem: Sticker): Boolean { return areItemsTheSame(newItem) } } private inner class StickerViewHolder(itemView: View) : MappingViewHolder<Sticker>(itemView) { private val image: ImageView = findViewById(R.id.sticker_keyboard_page_image) override fun bind(model: Sticker) { glideRequests.load(model.uri) .set(ApngOptions.ANIMATE, allowApngAnimation) .transition(DrawableTransitionOptions.withCrossFade()) .into(image) if (eventListener != null) { itemView.setOnClickListener { eventListener.onStickerClicked(model) } itemView.setOnLongClickListener { eventListener.onStickerLongClicked(model) true } } else { itemView.setOnClickListener(null) itemView.setOnLongClickListener(null) } } } data class StickerHeader(override val packId: String, private val title: String?, private val titleResource: Int?) : MappingModel<StickerHeader>, HasPackId { fun getTitle(context: Context): String { return title ?: context.resources.getString(titleResource ?: R.string.StickerManagementAdapter_untitled) } override fun areItemsTheSame(newItem: StickerHeader): Boolean { return title == newItem.title } override fun areContentsTheSame(newItem: StickerHeader): Boolean { return areItemsTheSame(newItem) } } private class StickerHeaderViewHolder(itemView: View) : MappingViewHolder<StickerHeader>(itemView) { private val title: TextView = findViewById(R.id.sticker_grid_header_title) override fun bind(model: StickerHeader) { title.text = model.getTitle(context) } } interface HasPackId { val packId: String } interface EventListener { fun onStickerClicked(sticker: Sticker) fun onStickerLongClicked(sticker: Sticker) } }
gpl-3.0
9c2b339ea7d1a48c3e9b12ae9a9cf14d
34.568421
159
0.755549
4.578591
false
false
false
false
GunoH/intellij-community
plugins/devkit/intellij.devkit.workspaceModel/src/metaModel/impl/modules.kt
3
1512
// 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.devkit.workspaceModel.metaModel.impl import com.intellij.workspaceModel.codegen.deft.meta.* val objModuleType: ObjType<ObjModule> = ObjTypeImpl() open class ObjModuleImpl(override val name: String) : ObjModule { private val mutableDependencies: MutableList<ObjModule> = ArrayList() private val mutableTypes: MutableList<ObjClass<*>> = ArrayList() private val mutableExtensions: MutableList<ExtProperty<*, *>> = ArrayList() override val objType: ObjType<*> get() = objModuleType override val dependencies: List<ObjModule> get() = mutableDependencies override val types: List<ObjClass<*>> get() = mutableTypes fun addType(objType: ObjClass<*>) { mutableTypes.add(objType) } fun addExtension(ext: ExtProperty<*, *>) { mutableExtensions.add(ext) } override val extensions: List<ExtProperty<*, *>> get() = mutableExtensions override fun toString(): String = name } class CompiledObjModuleImpl(name: String) : ObjModuleImpl(name), CompiledObjModule { override fun objClass(typeId: Int): ObjClass<*> = types[typeId] override fun <T : Obj, V> extField( receiver: ObjClass<*>, name: String, default: T.() -> V ): ExtProperty<T, V> { @Suppress("UNCHECKED_CAST") return extensions.first { it.name == name } as ExtProperty<T, V> } override val objType: ObjType<*> get() = objModuleType }
apache-2.0
c9b01a99942e0c6662631972f2138583
29.26
120
0.710317
4.064516
false
false
false
false
cicdevelopmentnz/Android-BLE
library/src/main/java/nz/co/cic/ble/scanner/Radio.kt
1
3310
package nz.co.cic.ble.scanner import android.bluetooth.* import android.bluetooth.le.BluetoothLeScanner import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanResult import android.content.Context import android.os.Build import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.FlowableEmitter import org.json.JSONObject /** * Created by dipshit on 4/03/17. */ class Radio(private val c: Context) : BluetoothGattCallback() { private val manager: BluetoothManager private val adapter: BluetoothAdapter private var scanner: BluetoothLeScanner? = null private var legacyCallback: BluetoothAdapter.LeScanCallback? = null private var scanCallback: ScanCallback? = null var isConnected: Boolean = false init { this.adapter = BluetoothAdapter.getDefaultAdapter() this.manager = c.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager } fun start(): Flowable<JSONObject> { return Flowable.create({ subscriber -> this.scanDevices()?.subscribe(RadioDeviceProcessor(c, subscriber)) }, BackpressureStrategy.BUFFER) } fun stop() { compatStop() } fun enable() { if (!this.adapter.isEnabled) { this.adapter.enable() } } fun scanDevices(): Flowable<BluetoothDevice>? { return Flowable.create<BluetoothDevice>({ subscriber -> compatStart(subscriber) }, BackpressureStrategy.BUFFER) } private fun compatStart(observable: FlowableEmitter<BluetoothDevice>) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (this.scanner == null) { this.scanner = this.adapter.bluetoothLeScanner } this.scanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult?) { super.onScanResult(callbackType, result) observable.onNext(result?.device) } override fun onBatchScanResults(results: MutableList<ScanResult>?) { super.onBatchScanResults(results) val it = results?.iterator() while (it!!.hasNext()) { var sr = it.next() observable.onNext(sr.device) } } } this.scanner?.startScan(this.scanCallback) } else { this.legacyCallback = object : BluetoothAdapter.LeScanCallback { override fun onLeScan(device: BluetoothDevice?, rssi: Int, scanRecord: ByteArray?) { observable.onNext(device) } } this.adapter.startLeScan(this.legacyCallback) } } private fun compatStop() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { this.scanner?.stopScan(this.scanCallback) } else { this.adapter.stopLeScan(this.legacyCallback) } } //Bluetooth Gatt Callbacks override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { super.onConnectionStateChange(gatt, status, newState) } }
gpl-3.0
19ffd359c12f73200d019f917cbf8acb
28.81982
100
0.617221
4.992459
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/sharing/v2/ShareViewModel.kt
1
3192
package org.thoughtcrime.securesms.sharing.v2 import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.kotlin.subscribeBy import io.reactivex.rxjava3.subjects.PublishSubject import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.contacts.paged.ContactSearchKey import org.thoughtcrime.securesms.sharing.InterstitialContentType import org.thoughtcrime.securesms.util.rx.RxStore class ShareViewModel( unresolvedShareData: UnresolvedShareData, shareRepository: ShareRepository ) : ViewModel() { companion object { private val TAG = Log.tag(ShareViewModel::class.java) } private val store = RxStore(ShareState()) private val disposables = CompositeDisposable() private val eventSubject = PublishSubject.create<ShareEvent>() val state: Flowable<ShareState> = store.stateFlowable val events: Observable<ShareEvent> = eventSubject init { disposables += shareRepository.resolve(unresolvedShareData).subscribeBy( onSuccess = { data -> when (data) { ResolvedShareData.Failure -> { moveToFailedState() } else -> { store.update { it.copy(loadState = ShareState.ShareDataLoadState.Loaded(data)) } } } }, onError = this::moveToFailedState ) } fun onContactSelectionConfirmed(contactSearchKeys: List<ContactSearchKey>) { val loadState = store.state.loadState if (loadState !is ShareState.ShareDataLoadState.Loaded) { return } val recipientKeys = contactSearchKeys.filterIsInstance(ContactSearchKey.RecipientSearchKey::class.java) val hasStory = recipientKeys.any { it.isStory } val openConversation = !hasStory && recipientKeys.size == 1 val resolvedShareData = loadState.resolvedShareData if (openConversation) { eventSubject.onNext(ShareEvent.OpenConversation(resolvedShareData, recipientKeys.first())) return } val event = when (resolvedShareData.toMultiShareArgs().interstitialContentType) { InterstitialContentType.MEDIA -> ShareEvent.OpenMediaInterstitial(resolvedShareData, recipientKeys) InterstitialContentType.TEXT -> ShareEvent.OpenTextInterstitial(resolvedShareData, recipientKeys) InterstitialContentType.NONE -> ShareEvent.SendWithoutInterstitial(resolvedShareData, recipientKeys) } eventSubject.onNext(event) } override fun onCleared() { disposables.clear() } private fun moveToFailedState(throwable: Throwable? = null) { Log.w(TAG, "Could not load share data.", throwable) store.update { it.copy(loadState = ShareState.ShareDataLoadState.Failed) } } class Factory( private val unresolvedShareData: UnresolvedShareData, private val shareRepository: ShareRepository ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return modelClass.cast(ShareViewModel(unresolvedShareData, shareRepository)) as T } } }
gpl-3.0
6049e21fc0f9c26f870a7485c7d6732c
34.466667
107
0.75188
4.619392
false
false
false
false
ftomassetti/kolasu
core/src/main/kotlin/com/strumenta/kolasu/model/Position.kt
1
8060
package com.strumenta.kolasu.model import java.io.File import java.net.URL import java.nio.file.Path val START_LINE = 1 val START_COLUMN = 0 val START_POINT = Point(START_LINE, START_COLUMN) /** * A location in a source code file. * The line should be in 1..n, the column in 0..n. * * Consider a file with one line, containing text "HELLO": * - the point before the first character will be Point(1, 0) * - the point at the end of the first line, after the letter "O" will be Point(1, 5) */ data class Point(val line: Int, val column: Int) : Comparable<Point> { override fun compareTo(other: Point): Int { if (line == other.line) { return this.column - other.column } return this.line - other.line } init { checkLine(line) checkColumn(column) } companion object { fun checkLine(line: Int) { require(line >= START_LINE) { "Line should be equal or greater than 1, was $line" } } fun checkColumn(column: Int) { require(column >= START_COLUMN) { "Column should be equal or greater than 0, was $column" } } } override fun toString() = "Line $line, Column $column" fun positionWithLength(length: Int): Position { require(length >= 0) return Position(this, this.plus(length)) } /** * Translate the Point to an offset in the original code stream. */ fun offset(code: String): Int { val lines = code.split("\r\n", "\n", "\r") require(lines.size >= line) { "The point does not exist in the given text. It indicates line $line but there are only ${lines.size} lines" } require(lines[line - 1].length >= column) { "The column does not exist in the given text. Line $line has ${lines[line - 1].length} columns, " + "the point indicates column $column" } val newLines = this.line - 1 return lines.subList(0, this.line - 1).foldRight(0) { it, acc -> it.length + acc } + newLines + column } /** * Computes whether this point comes strictly before another point. * @param other the other point */ fun isBefore(other: Point) = this < other /** * Computes whether this point is the same as, or comes before, another point. * @param other the other point */ fun isSameOrBefore(other: Point) = this <= other /** * Computes whether this point is the same as, or comes after, another point. * @param other the other point */ fun isSameOrAfter(other: Point) = this >= other operator fun plus(length: Int): Point { return Point(this.line, this.column + length) } operator fun plus(text: String): Point { if (text.isEmpty()) { return this } var line = this.line var column = this.column var i = 0 while (i < text.length) { if (text[i] == '\n' || text[i] == '\r') { line++ column = 0 if (text[i] == '\r' && i < text.length - 1 && text[i + 1] == '\n') { i++ // Count the \r\n sequence as 1 line } } else { column++ } i++ } return Point(line, column) } val asPosition: Position get() = Position(this, this) } fun linePosition(lineNumber: Int, lineCode: String, source: Source? = null): Position { require(lineNumber >= 1) { "Line numbers are expected to be equal or greater than 1" } return Position(Point(lineNumber, START_COLUMN), Point(lineNumber, lineCode.length), source) } abstract class Source class SourceSet(val name: String, val root: Path) class SourceSetElement(val sourceSet: SourceSet, val relativePath: Path) : Source() class FileSource(val file: File) : Source() class StringSource(val code: String? = null) : Source() class URLSource(val url: URL) : Source() /** * This source is intended to be used for nodes that are "calculated". * For example, nodes representing types that are derived by examining the code * but cannot be associated to any specific point in the code. * * @param description this is a description of the source. It is used to describe the process that calculated the node. * Examples of values could be "type inference". */ data class SyntheticSource(val description: String) : Source() /** * An area in a source file, from start to end. * The start point is the point right before the starting character. * The end point is the point right after the last character. * An empty position will have coinciding points. * * Consider a file with one line, containing text "HELLO". * The Position of such text will be Position(Point(1, 0), Point(1, 5)). */ data class Position(val start: Point, val end: Point, var source: Source? = null) : Comparable<Position> { override fun toString(): String { return "Position(start=$start, end=$end${if (source == null) "" else ", source=$source"})" } override fun compareTo(other: Position): Int { val cmp = this.start.compareTo(other.start) return if (cmp == 0) { this.end.compareTo(other.end) } else { cmp } } constructor(start: Point, end: Point, source: Source? = null, validate: Boolean = true) : this(start, end, source) { if (validate) { require(start.isBefore(end) || start == end) { "End should follows start or be the same as start (start: $start, end: $end)" } } } /** * Given the whole code extract the portion of text corresponding to this position */ fun text(wholeText: String): String { return wholeText.substring(start.offset(wholeText), end.offset(wholeText)) } /** * The length in characters of the text under this position in the provided source. * @param code the source text. */ fun length(code: String) = end.offset(code) - start.offset(code) fun isEmpty(): Boolean = start == end /** * Tests whether the given point is contained in the interval represented by this object. * @param point the point. */ fun contains(point: Point): Boolean { return ((point == start || start.isBefore(point)) && (point == end || point.isBefore(end))) } /** * Tests whether the given position is contained in the interval represented by this object. * @param position the position */ fun contains(position: Position?): Boolean { return (position != null) && this.start.isSameOrBefore(position.start) && this.end.isSameOrAfter(position.end) } /** * Tests whether the given node is contained in the interval represented by this object. * @param node the node */ fun contains(node: Node): Boolean { return this.contains(node.position) } /** * Tests whether the given position overlaps the interval represented by this object. * @param position the position */ fun overlaps(position: Position?): Boolean { return (position != null) && ( (this.start.isSameOrAfter(position.start) && this.start.isSameOrBefore(position.end)) || (this.end.isSameOrAfter(position.start) && this.end.isSameOrBefore(position.end)) || (position.start.isSameOrAfter(this.start) && position.start.isSameOrBefore(this.end)) || (position.end.isSameOrAfter(this.start) && position.end.isSameOrBefore(this.end)) ) } } /** * Utility function to create a Position */ fun pos(startLine: Int, startCol: Int, endLine: Int, endCol: Int) = Position( Point(startLine, startCol), Point(endLine, endCol) ) fun Node.isBefore(other: Node): Boolean = position!!.start.isBefore(other.position!!.start) val Node.startLine: Int? get() = this.position?.start?.line val Node.endLine: Int? get() = this.position?.end?.line
apache-2.0
99de1e9b3bd632c7ff248a868ff2cbcf
33.297872
120
0.61464
4.017946
false
false
false
false
google/accompanist
appcompat-theme/src/sharedTest/kotlin/com/google/accompanist/appcompattheme/BaseAppCompatThemeTest.kt
1
7514
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.accompanist.appcompattheme import android.view.ContextThemeWrapper import androidx.annotation.StyleRes import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.LocalContentColor import androidx.compose.material.MaterialTheme import androidx.compose.material.Typography import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.toFontFamily import androidx.test.filters.SdkSuppress import com.google.accompanist.appcompattheme.test.R import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test /** * Class which contains the majority of the tests. This class is extended * in both the `androidTest` and `test` source sets for setup of the relevant * test runner. */ abstract class BaseAppCompatThemeTest<T : AppCompatActivity>( activityClass: Class<T> ) { @get:Rule val composeTestRule = createAndroidComposeRule(activityClass) @Test fun colors() = composeTestRule.setContent { AppCompatTheme { val color = MaterialTheme.colors assertEquals(colorResource(R.color.aquamarine), color.primary) // By default, onSecondary is calculated to the highest contrast of black/white // against primary assertEquals(Color.Black, color.onPrimary) // primaryVariant == colorPrimaryDark assertEquals(colorResource(R.color.royal_blue), color.primaryVariant) assertEquals(colorResource(R.color.dark_golden_rod), color.secondary) // By default, onSecondary is calculated to the highest contrast of black/white // against secondary assertEquals(Color.Black, color.onSecondary) // Assert that secondaryVariant == secondary assertEquals(colorResource(R.color.dark_golden_rod), color.secondaryVariant) assertEquals(colorResource(R.color.dark_salmon), color.error) // onError is calculated to the highest contrast of black/white against error assertEquals(Color.Black, color.onError) assertEquals(colorResource(R.color.light_coral), color.background) // By default, onBackground is calculated to the highest contrast of black/white // against background assertEquals(Color.Black, color.onBackground) // AppCompatTheme updates the LocalContentColor to match the calculated onBackground assertEquals(Color.Black, LocalContentColor.current) } } @Test fun colors_textColorPrimary() = composeTestRule.setContent { WithThemeOverlay(R.style.ThemeOverlay_TextColorPrimary) { AppCompatTheme { val color = MaterialTheme.colors assertEquals(colorResource(R.color.aquamarine), color.primary) assertEquals(Color.Black, color.onPrimary) assertEquals(colorResource(R.color.royal_blue), color.primaryVariant) assertEquals(colorResource(R.color.dark_golden_rod), color.secondary) assertEquals(Color.Black, color.onSecondary) assertEquals(colorResource(R.color.dark_golden_rod), color.secondaryVariant) assertEquals(colorResource(R.color.dark_salmon), color.error) assertEquals(Color.Black, color.onError) assertEquals(colorResource(R.color.light_coral), color.background) // Our textColorPrimary (midnight_blue) contains provides enough contrast vs // the background color, so it should be used. assertEquals(colorResource(R.color.midnight_blue), color.onBackground) // AppCompatTheme updates the LocalContentColor to match the calculated onBackground assertEquals(colorResource(R.color.midnight_blue), LocalContentColor.current) if (!isSystemInDarkTheme()) { // Our textColorPrimary (midnight_blue) provides enough contrast vs // the light surface color, so it should be used. assertEquals(colorResource(R.color.midnight_blue), color.onSurface) } else { // In dark theme, textColorPrimary (midnight_blue) does not provide // enough contrast vs the light surface color, // so we use a computed value of white assertEquals(Color.White, color.onSurface) } } } } @Test @SdkSuppress(minSdkVersion = 23) // XML font families with >1 fonts are only supported on API 23+ open fun type_rubik_family_api23() = composeTestRule.setContent { val rubik = FontFamily( Font(R.font.rubik_300, FontWeight.W300), Font(R.font.rubik_400, FontWeight.W400), Font(R.font.rubik_500, FontWeight.W500), Font(R.font.rubik_700, FontWeight.W700), ) WithThemeOverlay(R.style.ThemeOverlay_RubikFontFamily) { AppCompatTheme { MaterialTheme.typography.assertFontFamily(expected = rubik) } } } @Test fun type_rubik_fixed400() = composeTestRule.setContent { val rubik400 = Font(R.font.rubik_400, FontWeight.W400).toFontFamily() WithThemeOverlay(R.style.ThemeOverlay_Rubik400) { AppCompatTheme { MaterialTheme.typography.assertFontFamily(expected = rubik400) } } } } internal fun Typography.assertFontFamily(expected: FontFamily) { assertEquals(expected, h1.fontFamily) assertEquals(expected, h2.fontFamily) assertEquals(expected, h3.fontFamily) assertEquals(expected, h4.fontFamily) assertEquals(expected, h5.fontFamily) assertEquals(expected, h5.fontFamily) assertEquals(expected, h6.fontFamily) assertEquals(expected, body1.fontFamily) assertEquals(expected, body2.fontFamily) assertEquals(expected, button.fontFamily) assertEquals(expected, caption.fontFamily) assertEquals(expected, overline.fontFamily) } /** * Function which applies an Android theme overlay to the current context. */ @Composable fun WithThemeOverlay( @StyleRes themeOverlayId: Int, content: @Composable () -> Unit, ) { val themedContext = ContextThemeWrapper(LocalContext.current, themeOverlayId) CompositionLocalProvider(LocalContext provides themedContext, content = content) }
apache-2.0
d74b1aa1875771feb4becb438cd6fe0a
42.183908
101
0.695768
4.798212
false
true
false
false
linkedin/LiTr
litr/src/main/java/com/linkedin/android/litr/frameextract/VideoFrameExtractor.kt
1
5865
/* * Copyright 2021 LinkedIn Corporation * All Rights Reserved. * * Licensed under the BSD 2-Clause License (the "License"). See License in the project root for * license information. */ package com.linkedin.android.litr.frameextract import android.content.Context import android.graphics.Bitmap import android.os.Handler import android.os.Looper import android.util.Log import com.linkedin.android.litr.ExperimentalFrameExtractorApi import com.linkedin.android.litr.frameextract.behaviors.FrameExtractBehavior import com.linkedin.android.litr.frameextract.behaviors.MediaMetadataExtractBehavior import com.linkedin.android.litr.frameextract.queue.ComparableFutureTask import com.linkedin.android.litr.frameextract.queue.PriorityExecutorUtil /** * Provides the entry point for single frame extraction. * * This class uses a single, dedicated thread to schedule jobs. The priority of each job can be specified within [FrameExtractParameters]. * * @param context The application context. * @param listenerLooper The looper on which [extract] listener events will be processed. * @param extractBehavior The behavior to use for extracting frames from media. */ @ExperimentalFrameExtractorApi class VideoFrameExtractor @JvmOverloads constructor( context: Context, private val listenerLooper: Looper = Looper.getMainLooper(), private var extractBehavior: FrameExtractBehavior = MediaMetadataExtractBehavior(context) ) { private val activeJobMap = mutableMapOf<String, ActiveExtractJob>() private val listenerHandler by lazy { Handler(listenerLooper) } private val executorService = PriorityExecutorUtil.newSingleThreadPoolPriorityExecutor() /** * Starts a new frame extract job with the specified parameters. The [listener] will be updated with the job status. * * @param requestId The ID of this request. Only one request per ID can be active. This ID is used to then refer to the request when calling [stop]. * @param params Specifies extraction options and other parameters. * @param listener The listener to notify about the job status, such as success/error. */ fun extract(requestId: String, params: FrameExtractParameters, listener: FrameExtractListener?) { if (activeJobMap.containsKey(requestId)) { Log.w(TAG, "Request with ID $requestId already exists") return } val task = FrameExtractJob(requestId, params, extractBehavior, rootListener) val futureTask = ComparableFutureTask(task, null, params.priority) executorService.execute(futureTask) activeJobMap[requestId] = ActiveExtractJob(futureTask, listener) } /** * Cancels the specified extract job. If the job was in progress, [FrameExtractListener.onCancelled] will be called for the job. * Does not terminate immediately: [FrameExtractListener.onExtracted] may still be called after this method is called. */ fun stop(requestId: String) { activeJobMap[requestId]?.let { if (!it.future.isCancelled && !it.future.isDone) { it.future.cancel(true) } if (!it.future.isStarted) { // If the job hasn't started, it won't probably even start, but it will remain in the activeJobMap, // we must remove it from there. activeJobMap.remove(requestId) } } } /** * Cancels all started extract jobs. [FrameExtractListener.onCancelled] will be called for jobs that have been started. */ fun stopAll() { val iterator = activeJobMap.iterator() while (iterator.hasNext()) { val job = iterator.next().value if (!job.future.isCancelled && !job.future.isDone) { job.future.cancel(true) } if (!job.future.isStarted) { // If the job hasn't started, it won't probably even start, but it will remain in the activeJobMap, // we must remove it from there. iterator.remove() } } } /** * Stops all extract jobs immediately and frees resources. */ fun release() { executorService.shutdownNow() extractBehavior.release() activeJobMap.clear() } private fun onCompleteJob(jobId: String) { activeJobMap.remove(jobId) } private val rootListener = object : FrameExtractListener { override fun onStarted(id: String, timestampUs: Long) { runOnListenerHandler(activeJobMap[id]?.listener) { it.onStarted(id, timestampUs) } } override fun onExtracted(id: String, timestampUs: Long, bitmap: Bitmap) { runOnListenerHandler(activeJobMap[id]?.listener) { onCompleteJob(id) it.onExtracted(id, timestampUs, bitmap) } } override fun onCancelled(id: String, timestampUs: Long) { runOnListenerHandler(activeJobMap[id]?.listener) { onCompleteJob(id) it.onCancelled(id, timestampUs) } } override fun onError(id: String, timestampUs: Long, cause: Throwable?) { runOnListenerHandler(activeJobMap[id]?.listener) { onCompleteJob(id) it.onError(id, timestampUs, cause) } } private fun runOnListenerHandler(listener: FrameExtractListener?, func: (FrameExtractListener) -> Unit) { if (listener != null) { listenerHandler.post { func(listener) } } } } private data class ActiveExtractJob(val future: ComparableFutureTask<*>, val listener: FrameExtractListener?) companion object { private const val TAG = "VideoThumbnailExtractor" } }
bsd-2-clause
a925c7b1b23e75db22c18e37af83af89
37.585526
152
0.663939
4.684505
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/backup/full/FullBackupManager.kt
1
14352
package eu.kanade.tachiyomi.data.backup.full import android.content.Context import android.net.Uri import com.hippo.unifile.UniFile import eu.kanade.tachiyomi.data.backup.AbstractBackupManager import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CATEGORY import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CATEGORY_MASK import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CHAPTER import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CHAPTER_MASK import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_HISTORY import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_HISTORY_MASK import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_TRACK import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_TRACK_MASK import eu.kanade.tachiyomi.data.backup.full.models.Backup import eu.kanade.tachiyomi.data.backup.full.models.BackupCategory import eu.kanade.tachiyomi.data.backup.full.models.BackupChapter import eu.kanade.tachiyomi.data.backup.full.models.BackupFull import eu.kanade.tachiyomi.data.backup.full.models.BackupHistory import eu.kanade.tachiyomi.data.backup.full.models.BackupManga import eu.kanade.tachiyomi.data.backup.full.models.BackupSerializer import eu.kanade.tachiyomi.data.backup.full.models.BackupSource import eu.kanade.tachiyomi.data.backup.full.models.BackupTracking import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.History import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.models.MangaCategory import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.util.system.logcat import kotlinx.serialization.protobuf.ProtoBuf import logcat.LogPriority import okio.buffer import okio.gzip import okio.sink import java.io.FileOutputStream import kotlin.math.max class FullBackupManager(context: Context) : AbstractBackupManager(context) { val parser = ProtoBuf /** * Create backup Json file from database * * @param uri path of Uri * @param isJob backup called from job */ override fun createBackup(uri: Uri, flags: Int, isJob: Boolean): String { // Create root object var backup: Backup? = null databaseHelper.inTransaction { val databaseManga = getFavoriteManga() backup = Backup( backupManga(databaseManga, flags), backupCategories(), emptyList(), backupExtensionInfo(databaseManga) ) } var file: UniFile? = null try { file = ( if (isJob) { // Get dir of file and create var dir = UniFile.fromUri(context, uri) dir = dir.createDirectory("automatic") // Delete older backups val numberOfBackups = numberOfBackups() val backupRegex = Regex("""tachiyomi_\d+-\d+-\d+_\d+-\d+.proto.gz""") dir.listFiles { _, filename -> backupRegex.matches(filename) } .orEmpty() .sortedByDescending { it.name } .drop(numberOfBackups - 1) .forEach { it.delete() } // Create new file to place backup dir.createFile(BackupFull.getDefaultFilename()) } else { UniFile.fromUri(context, uri) } ) ?: throw Exception("Couldn't create backup file") val byteArray = parser.encodeToByteArray(BackupSerializer, backup!!) file.openOutputStream().also { // Force overwrite old file size, (it as? FileOutputStream)?.channel?.truncate(0) }.sink().gzip().buffer().use { it.write(byteArray) } val fileUri = file.uri // Make sure it's a valid backup file FullBackupRestoreValidator().validate(context, fileUri) return fileUri.toString() } catch (e: Exception) { logcat(LogPriority.ERROR, e) file?.delete() throw e } } private fun backupManga(mangas: List<Manga>, flags: Int): List<BackupManga> { return mangas.map { backupMangaObject(it, flags) } } private fun backupExtensionInfo(mangas: List<Manga>): List<BackupSource> { return mangas .asSequence() .map { it.source } .distinct() .map { sourceManager.getOrStub(it) } .map { BackupSource.copyFrom(it) } .toList() } /** * Backup the categories of library * * @return list of [BackupCategory] to be backed up */ private fun backupCategories(): List<BackupCategory> { return databaseHelper.getCategories() .executeAsBlocking() .map { BackupCategory.copyFrom(it) } } /** * Convert a manga to Json * * @param manga manga that gets converted * @param options options for the backup * @return [BackupManga] containing manga in a serializable form */ private fun backupMangaObject(manga: Manga, options: Int): BackupManga { // Entry for this manga val mangaObject = BackupManga.copyFrom(manga) // Check if user wants chapter information in backup if (options and BACKUP_CHAPTER_MASK == BACKUP_CHAPTER) { // Backup all the chapters val chapters = databaseHelper.getChapters(manga).executeAsBlocking() if (chapters.isNotEmpty()) { mangaObject.chapters = chapters.map { BackupChapter.copyFrom(it) } } } // Check if user wants category information in backup if (options and BACKUP_CATEGORY_MASK == BACKUP_CATEGORY) { // Backup categories for this manga val categoriesForManga = databaseHelper.getCategoriesForManga(manga).executeAsBlocking() if (categoriesForManga.isNotEmpty()) { mangaObject.categories = categoriesForManga.mapNotNull { it.order } } } // Check if user wants track information in backup if (options and BACKUP_TRACK_MASK == BACKUP_TRACK) { val tracks = databaseHelper.getTracks(manga).executeAsBlocking() if (tracks.isNotEmpty()) { mangaObject.tracking = tracks.map { BackupTracking.copyFrom(it) } } } // Check if user wants history information in backup if (options and BACKUP_HISTORY_MASK == BACKUP_HISTORY) { val historyForManga = databaseHelper.getHistoryByMangaId(manga.id!!).executeAsBlocking() if (historyForManga.isNotEmpty()) { val history = historyForManga.mapNotNull { history -> val url = databaseHelper.getChapter(history.chapter_id).executeAsBlocking()?.url url?.let { BackupHistory(url, history.last_read) } } if (history.isNotEmpty()) { mangaObject.history = history } } } return mangaObject } fun restoreMangaNoFetch(manga: Manga, dbManga: Manga) { manga.id = dbManga.id manga.copyFrom(dbManga) insertManga(manga) } /** * Fetches manga information * * @param manga manga that needs updating * @return Updated manga info. */ fun restoreManga(manga: Manga): Manga { return manga.also { it.initialized = it.description != null it.id = insertManga(it) } } /** * Restore the categories from Json * * @param backupCategories list containing categories */ internal fun restoreCategories(backupCategories: List<BackupCategory>) { // Get categories from file and from db val dbCategories = databaseHelper.getCategories().executeAsBlocking() // Iterate over them backupCategories.map { it.getCategoryImpl() }.forEach { category -> // Used to know if the category is already in the db var found = false for (dbCategory in dbCategories) { // If the category is already in the db, assign the id to the file's category // and do nothing if (category.name == dbCategory.name) { category.id = dbCategory.id found = true break } } // If the category isn't in the db, remove the id and insert a new category // Store the inserted id in the category if (!found) { // Let the db assign the id category.id = null val result = databaseHelper.insertCategory(category).executeAsBlocking() category.id = result.insertedId()?.toInt() } } } /** * Restores the categories a manga is in. * * @param manga the manga whose categories have to be restored. * @param categories the categories to restore. */ internal fun restoreCategoriesForManga(manga: Manga, categories: List<Int>, backupCategories: List<BackupCategory>) { val dbCategories = databaseHelper.getCategories().executeAsBlocking() val mangaCategoriesToUpdate = ArrayList<MangaCategory>(categories.size) categories.forEach { backupCategoryOrder -> backupCategories.firstOrNull { it.order == backupCategoryOrder }?.let { backupCategory -> dbCategories.firstOrNull { dbCategory -> dbCategory.name == backupCategory.name }?.let { dbCategory -> mangaCategoriesToUpdate += MangaCategory.create(manga, dbCategory) } } } // Update database if (mangaCategoriesToUpdate.isNotEmpty()) { databaseHelper.deleteOldMangasCategories(listOf(manga)).executeAsBlocking() databaseHelper.insertMangasCategories(mangaCategoriesToUpdate).executeAsBlocking() } } /** * Restore history from Json * * @param history list containing history to be restored */ internal fun restoreHistoryForManga(history: List<BackupHistory>) { // List containing history to be updated val historyToBeUpdated = ArrayList<History>(history.size) for ((url, lastRead) in history) { val dbHistory = databaseHelper.getHistoryByChapterUrl(url).executeAsBlocking() // Check if history already in database and update if (dbHistory != null) { dbHistory.apply { last_read = max(lastRead, dbHistory.last_read) } historyToBeUpdated.add(dbHistory) } else { // If not in database create databaseHelper.getChapter(url).executeAsBlocking()?.let { val historyToAdd = History.create(it).apply { last_read = lastRead } historyToBeUpdated.add(historyToAdd) } } } databaseHelper.updateHistoryLastRead(historyToBeUpdated).executeAsBlocking() } /** * Restores the sync of a manga. * * @param manga the manga whose sync have to be restored. * @param tracks the track list to restore. */ internal fun restoreTrackForManga(manga: Manga, tracks: List<Track>) { // Fix foreign keys with the current manga id tracks.map { it.manga_id = manga.id!! } // Get tracks from database val dbTracks = databaseHelper.getTracks(manga).executeAsBlocking() val trackToUpdate = mutableListOf<Track>() tracks.forEach { track -> var isInDatabase = false for (dbTrack in dbTracks) { if (track.sync_id == dbTrack.sync_id) { // The sync is already in the db, only update its fields if (track.media_id != dbTrack.media_id) { dbTrack.media_id = track.media_id } if (track.library_id != dbTrack.library_id) { dbTrack.library_id = track.library_id } dbTrack.last_chapter_read = max(dbTrack.last_chapter_read, track.last_chapter_read) isInDatabase = true trackToUpdate.add(dbTrack) break } } if (!isInDatabase) { // Insert new sync. Let the db assign the id track.id = null trackToUpdate.add(track) } } // Update database if (trackToUpdate.isNotEmpty()) { databaseHelper.insertTracks(trackToUpdate).executeAsBlocking() } } internal fun restoreChaptersForManga(manga: Manga, chapters: List<Chapter>) { val dbChapters = databaseHelper.getChapters(manga).executeAsBlocking() chapters.forEach { chapter -> val dbChapter = dbChapters.find { it.url == chapter.url } if (dbChapter != null) { chapter.id = dbChapter.id chapter.copyFrom(dbChapter) if (dbChapter.read && !chapter.read) { chapter.read = dbChapter.read chapter.last_page_read = dbChapter.last_page_read } else if (chapter.last_page_read == 0 && dbChapter.last_page_read != 0) { chapter.last_page_read = dbChapter.last_page_read } if (!chapter.bookmark && dbChapter.bookmark) { chapter.bookmark = dbChapter.bookmark } } chapter.manga_id = manga.id } val newChapters = chapters.groupBy { it.id != null } newChapters[true]?.let { updateKnownChapters(it) } newChapters[false]?.let { insertChapters(it) } } }
apache-2.0
1e356e0a9ed6a1d270a5997555522cb9
38.320548
121
0.598035
5.02697
false
false
false
false
mdanielwork/intellij-community
python/src/com/jetbrains/python/run/runAnything/pyRunAnythingUtil.kt
3
1898
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.run.runAnything import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.configurations.PathEnvironmentVariableUtil import com.intellij.ide.actions.runAnything.RunAnythingUtil import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.EnvironmentUtil import com.jetbrains.python.sdk.PythonSdkType /** * @author vlan */ internal val DataContext.project: Project get() = RunAnythingUtil.fetchProject(this) internal val DataContext.virtualFile: VirtualFile? get() = CommonDataKeys.VIRTUAL_FILE.getData(this) internal fun VirtualFile.findPythonSdk(project: Project): Sdk? { val module = ModuleUtil.findModuleForFile(this, project) return PythonSdkType.findPythonSdk(module) } internal fun GeneralCommandLine.findExecutableInPath(): String? { val executable = exePath if ("/" in executable || "\\" in executable) return executable val paths = listOfNotNull(effectiveEnvironment["PATH"], System.getenv("PATH"), EnvironmentUtil.getValue("PATH")) return paths .asSequence() .mapNotNull { path -> if (SystemInfo.isWindows) { PathEnvironmentVariableUtil.getWindowsExecutableFileExtensions() .mapNotNull { ext -> PathEnvironmentVariableUtil.findInPath("$executable$ext", path, null)?.path } .firstOrNull() } else { PathEnvironmentVariableUtil.findInPath(executable, path, null)?.path } } .firstOrNull() }
apache-2.0
3d0604bfb66374f92dcc331281329cda
38.541667
140
0.77608
4.54067
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/extractFunction/duplicates/branchingMatch2.kt
9
1119
// WITH_STDLIB // PARAM_TYPES: kotlin.Int // PARAM_TYPES: kotlin.Int // PARAM_DESCRIPTOR: value-parameter a: kotlin.Int defined in test // PARAM_DESCRIPTOR: var b: kotlin.Int defined in test // SIBLING: fun test(a: Int): Int { var b: Int = 1 <selection>if (a > 0) { b = b + a } else { b = b - a }</selection> return b } fun foo1() { val x = 1 var y: Int = x println( if (x > 0) { y + x } else { y - x } ) } fun foo2(x: Int) { var p: Int = 1 if (x > 0) { p = p + x } else { p = p - x } println(p) } fun foo3(x: Int): Int { var p: Int = 1 if (x > 0) { return p + x } else { return p - x } } fun foo4() { val t: (Int) -> (Int) = { var n = it if (it > 0) { n + it } else { n - it } } println(t(1)) } fun foo5(x: Int): Int { var p: Int = 1 if (x > 0) { val t = p + x } else { val u = p - x } }
apache-2.0
0a91fcff0a4a35fc1160dc9ded2a0196
14.121622
66
0.37891
3.024324
false
false
false
false
sreich/ore-infinium
core/src/com/ore/infinium/components/PlayerComponent.kt
1
4015
/** MIT License Copyright (c) 2016 Shaun Reich <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.ore.infinium.components import com.artemis.Component import com.ore.infinium.HotbarInventory import com.ore.infinium.Inventory import com.ore.infinium.LoadedViewport import com.ore.infinium.OreTimer import com.ore.infinium.systems.MovementSystem import com.ore.infinium.util.DoNotCopy import com.ore.infinium.util.DoNotPrint import com.ore.infinium.util.ExtendedComponent import com.ore.infinium.util.INVALID_ENTITY_ID class PlayerComponent : Component(), ExtendedComponent<PlayerComponent> { var playerName: String = "" /** * Unique and utilized only by players, is not global or related to generic entity id's * Is used to identify the players, for knowing which one the network is talking about, * and is also very useful for kicking/banning. */ var connectionPlayerId = -1 var killed: Boolean = false /** * if the player notified us and has a control panel opened, we will * periodically send it info updates for it. (like fuel consumption). * * they will notify us when they close it, too, so we can stop * * this is a network id, of course */ @DoNotCopy @DoNotPrint @Transient var openedControlPanelEntity = INVALID_ENTITY_ID @DoNotCopy @DoNotPrint @Transient var placeableItemTimer = OreTimer() @DoNotCopy @DoNotPrint @Transient var secondaryActionTimer = OreTimer() /** * the tick that an attack last took place at. * see ToolComponent.attackTickInterval */ @DoNotCopy @DoNotPrint @Transient var primaryAttackTimer = OreTimer() // public Vector2 mousePositionWorldCoords; // public boolean mouseLeftButtonHeld; // public boolean mouseRightButtonHeld; @DoNotCopy @DoNotPrint @Transient var ping: Int = 0 @DoNotCopy @DoNotPrint @Transient var loadedViewport = LoadedViewport() @DoNotCopy @DoNotPrint @Transient var hotbarInventory: HotbarInventory? = null @DoNotCopy @DoNotPrint @Transient var inventory: Inventory? = null //public int equippedItemAnimator; /** * @return entity id that is equipped as primary */ val equippedPrimaryItem: Int get() = hotbarInventory!!.itemEntity(hotbarInventory!!.selectedSlot) companion object { val jumpVelocity = MovementSystem.GRAVITY_ACCEL * 18 const val NORMAL_MOVEMENT_SPEED = 0.38f var maxMovementSpeed = NORMAL_MOVEMENT_SPEED const val NORMAL_MOVEMENT_RAMP_UP_FACTOR = 2.0f var movementRampUpFactor = NORMAL_MOVEMENT_RAMP_UP_FACTOR //ms val placeableItemDelay = 300L /** * for interacting with things like doors and control panels */ val secondaryActionDelay = 300L } override fun copyFrom(other: PlayerComponent) = throw TODO("function not yet implemented") override fun canCombineWith(other: PlayerComponent) = throw TODO("function not yet implemented") }
mit
f8f8e5af7d5c17204f65f62007549de5
37.238095
100
0.736737
4.461111
false
false
false
false
justnero-ru/university
semestr.06/ТРСиПВ/bellman/src/main/kotlin/bellman/test/test.kt
1
3147
package bellman.test import mpi.MPI import bellman.graph.algorithm.bellmanFord import bellman.graph.algorithm.parallel.Master import bellman.graph.algorithm.parallel.Slave import bellman.graph.random import kotlin.system.measureNanoTime fun iterationNumber(iterationCoefficient: Int, vertexNumber: Int) = maxOf(3, (iterationCoefficient * 1e3 / vertexNumber).toInt()) fun makeTest(args: Array<String>, tests: TestSet): ResultSet { val processNumber = MPI.COMM_WORLD.Size() return tests.tests .map { (iterationCoefficient, graphs) -> val (vertexNumber, edgeProbability) = graphs return@map vertexNumber.map { vertexNumber -> val iterationNumber = iterationNumber(iterationCoefficient, vertexNumber) edgeProbability.map { edgeProbability -> TestResult( processNumber, Input(iterationNumber, vertexNumber, edgeProbability), measureBellman(args, iterationNumber, GenerateValues(vertexNumber, edgeProbability)) ) } }.reduce { acc, testResult -> acc + testResult } } .reduce { acc, testResult -> acc + testResult } .let(::ResultSet) } fun measureBellman(args: Array<String>, iterationNumber: Int, generateValues: GenerateValues): ParallelAndSequentialTime { val parallelResult = parallelBellmanFord(args, generateValues, iterationNumber) if (MPI.COMM_WORLD.Rank() == 0) { val sequentialResult = sequentialBellmanFord(generateValues, iterationNumber) return parallelResult.average() / 1e6 to sequentialResult.average() / 1e6 } return -1.0 to -1.0 } fun sequentialBellmanFord(generateValues: GenerateValues, iterationNumber: Int): MutableList<Long> { val result = mutableListOf<Long>() repeat(iterationNumber) { val plainAdjacencyList = generateValues.generateGraph() val sourceVertex = random(generateValues.vertexNumber - 1) val vertexNumber = generateValues.vertexNumber val nanoTime = measureNanoTime { bellmanFord(plainAdjacencyList, sourceVertex, vertexNumber) } result.add(nanoTime) } return result } fun parallelBellmanFord(args: Array<String>, generateValues: GenerateValues, iterationNumber: Int): MutableList<Long> { // MPI.Init(args) val comm = MPI.COMM_WORLD val rank = comm.Rank() val process = if (rank == 0) Master(generateValues) else Slave() val result = mutableListOf<Long>() repeat(iterationNumber) { val nanoTime = measureNanoTime { process.work() } if (rank == 0) { result.add(nanoTime) process.plainAdjacencyList = generateValues.generateGraph() } process.reset() } // MPI.Finalize() return result }
mit
92bbe21812e56e17e4b978a990d7829e
29.553398
116
0.607881
4.641593
false
true
false
false
chrislo27/Tickompiler
src/main/kotlin/rhmodding/tickompiler/gameputter/GamePutter.kt
2
2353
package rhmodding.tickompiler.gameputter import java.nio.ByteBuffer import kotlin.math.roundToInt object GamePutter { fun putGame(base: ByteBuffer, gameContents: ByteBuffer, s: Int): List<Int> { val tableIndex = gameContents.getInt(0) val start = gameContents.getInt(4) val assets = gameContents.getInt(8) if (tableIndex >= 0x100) { base.putInt(0x3358 + 36*(tableIndex-0x100) + 4, 0xC000000 + start + s) base.putInt(0x3358 + 36*(tableIndex-0x100) + 8, 0xC000000 + assets + s) } else { base.putInt(52 * tableIndex + 4, 0xC000000 + start + s) base.putInt(52 * tableIndex + 8, 0xC000000 + assets + s) } val result = mutableListOf<Int>() gameContents.position(12) while (gameContents.hasRemaining()) { var opint = gameContents.int if (opint == -2) { break } val adjArgs = mutableListOf<Int>() if (opint == -1) { val amount = gameContents.int for (i in 1..amount) { val ann = gameContents.int val anncode = ann and 0xFF val annArg = ann ushr 8 if (anncode == 0 || anncode == 1 || anncode == 2) { adjArgs.add(annArg) } } opint = gameContents.int } result.add(opint) val argCount = (opint ushr 10) and 0b1111 val args: MutableList<Int> = (0 until argCount).map { val arg = gameContents.int if (it in adjArgs) { arg + 0xC000000 + s } else { arg } }.toMutableList() result.addAll(args) } while (gameContents.hasRemaining()) { result.add(gameContents.int) } return result } fun putTempo(base: ByteBuffer, tempoFile: String, s: Int): List<Int> { val tempo = tempoFile.split(Regex("\\r?\\n")).filter { it.isNotBlank() }.map { it.split(" ") } val ids = tempo[0].map { it.toInt(16) } val result = mutableListOf<Int>() tempo.drop(1).forEachIndexed { index, list -> val bpm = list[0].toFloat() val beats = list[1].toFloat() val time = 60*beats/bpm val timeInt = (time * 32000).roundToInt() result.add(java.lang.Float.floatToIntBits(beats)) result.add(timeInt) if (index == tempo.size - 2) { result.add(0x8000) } else { result.add(0) } } for (i in 0 until 0x1DD) { val one = base.getInt(16*i + 0x1588) val two = base.getInt(16*i + 0x1588 + 4) if (one in ids || two in ids) { base.putInt(16*i + 0x1588 + 12, 0xC000000 + s) } } return result } }
mit
b095e8cad91010c9f2027736fde513e9
27.02381
96
0.630259
2.828125
false
false
false
false
Alkaizyr/Trees
src/btree/BTree.kt
1
5970
package btree import java.util.LinkedList class BTree<K: Comparable<K>> (val t: Int): Iterable<BNode<K>> { var root: BNode<K>? = null fun insert(key: K) { if (root == null) root = BNode() if (root!!.keys.size == 2 * t - 1) { val newNode: BNode<K> = BNode(false) newNode.children.add(root!!) newNode.splitChildren(t, 0) root = newNode insertNonfull(key, newNode) } else insertNonfull(key, root!!) } private fun insertNonfull(key: K, node: BNode<K>) { var i = 0 while (i < node.keys.size && key > node.keys[i]) i++ if (node.isLeaf) node.keys.add(i, key) else { if (node.children[i].keys.size == 2 * t - 1) { node.splitChildren(t, i) if (key > node.keys[i]) i++ } insertNonfull(key, node.children[i]) } } fun delete(key: K) { if (find(key) == null) return if (root == null) return deletePrivate(key, root!!) if (root!!.keys.size == 0) root = null } private fun deletePrivate(key: K, node: BNode<K>) { var i = 0 while (i < node.keys.size && key > node.keys[i]) i++ if (node.keys.size > i && node.keys[i] == key) { if ((node.isLeaf)) { node.keys.removeAt(i) } else if (node.children[i].keys.size > t - 1) { val prevNode = prevKey(key, node) node.keys[i] = prevNode.keys.last() deletePrivate(prevNode.keys.last(), node.children[i]) } else if (node.children[i + 1].keys.size > t - 1) { val nextNode = nextKey(key, node) node.keys[i] = nextNode.keys.first() deletePrivate(nextNode.keys.first(), node.children[i + 1]) } else { node.mergeChildren(i) if (node.keys.isEmpty()) { root = node.children[i] } deletePrivate(key, node.children[i]) } } else { if (node.children[i].keys.size < t) { when { node.children[i] != node.children.last() && node.children[i + 1].keys.size > t - 1 -> { node.children[i].keys.add(node.keys[i]) node.keys[i] = node.children[i + 1].keys.first() node.children[i + 1].keys.removeAt(0) if (!node.children[i].isLeaf) { node.children[i].children.add(node.children[i + 1].children.first()) node.children[i + 1].children.removeAt(0) } } node.children[i] != node.children.first() && node.children[i - 1].keys.size > t - 1 -> { node.children[i].keys.add(0, node.keys[i - 1]) node.keys[i - 1] = node.children[i - 1].keys.last() node.children[i - 1].keys.removeAt(node.children[i - 1].keys.size - 1) if (!node.children[i].isLeaf) { node.children[i].children.add(0, node.children[i - 1].children.last()) node.children[i - 1].children.removeAt(node.children[i - 1].children.size - 1) } } node.children[i] != node.children.last() -> { node.mergeChildren(i) if (node.keys.isEmpty()) { root = node.children[i] } } node.children[i] != node.children.first() -> { node.mergeChildren(i - 1) if (node.keys.isEmpty()) { root = node.children[i - 1] } i-- } } } deletePrivate(key, node.children[i]) } } private fun prevKey(key: K, node: BNode<K>): BNode<K> { var currentNode = node.children[node.keys.indexOf(key)] while (!currentNode.isLeaf) currentNode = currentNode.children.last() return currentNode } private fun nextKey(key: K, node: BNode<K>): BNode<K> { var currentNode = node.children[node.keys.indexOf(key) + 1] while (!currentNode.isLeaf) currentNode = currentNode.children.first() return currentNode } fun find(key: K): K? { var node: BNode<K>? = root ?: return null var i = 0 while (i < node!!.keys.size - 1 && key > node.keys[i]) i++ while (node!!.keys[i] != key) { if (node.isLeaf) return null when { key < node.keys[i] -> node = node.children[i] key > node.keys[i] -> node = node.children[i + 1] } i = 0 while (i < node.keys.size - 1 && key > node.keys[i]) i++ } return key } override fun iterator(): Iterator<BNode<K>> { return (object : Iterator<BNode<K>> { var NodeList = LinkedList<BNode<K>>() init { if (root != null && root!!.keys.isNotEmpty()) { NodeList.add(root!!) } } override fun hasNext() = NodeList.isNotEmpty() override fun next(): BNode<K> { val next = NodeList.remove() if (!next.isLeaf) { NodeList.addAll(next.children) } return next } }) } }
mit
e997a72924f86da19034c60037f5f87a
29.620513
106
0.430988
4.180672
false
false
false
false
google/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/VmOptionsGenerator.kt
4
2657
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") package org.jetbrains.intellij.build.impl import org.jetbrains.intellij.build.ProductProperties import java.io.IOException import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.util.function.BiConsumer @Suppress("IdentifierGrammar") object VmOptionsGenerator { @Suppress("SpellCheckingInspection") private val COMMON_VM_OPTIONS: List<String> = listOf( "-XX:+UseG1GC", "-XX:SoftRefLRUPolicyMSPerMB=50", "-XX:CICompilerCount=2", "-XX:+HeapDumpOnOutOfMemoryError", "-XX:-OmitStackTraceInFastThrow", "-XX:+IgnoreUnrecognizedVMOptions", // allowing the JVM to start even with outdated options stuck in user configs "-XX:CompileCommand=exclude,com/intellij/openapi/vfs/impl/FilePartNodeRoot,trieDescend", // temporary workaround for crashes in С2 (JBR-4509) "-ea", "-Dsun.io.useCanonCaches=false", "-Dsun.java2d.metal=true", "-Djbr.catch.SIGABRT=true", "-Djdk.http.auth.tunneling.disabledSchemes=\"\"", "-Djdk.attach.allowAttachSelf=true", "-Djdk.module.illegalAccess.silent=true", "-Dkotlinx.coroutines.debug=off") private val MEMORY_OPTIONS: Map<String, String> = linkedMapOf( "-Xms" to "128m", "-Xmx" to "750m", "-XX:ReservedCodeCacheSize=" to "512m") @JvmStatic fun computeVmOptions(isEAP: Boolean, productProperties: ProductProperties): List<String> = computeVmOptions(isEAP, productProperties.customJvmMemoryOptions) @JvmStatic fun computeVmOptions(isEAP: Boolean, customJvmMemoryOptions: Map<String, String>?): List<String> { val result = ArrayList<String>() if (customJvmMemoryOptions != null) { val memory = LinkedHashMap<String, String>() memory.putAll(MEMORY_OPTIONS) memory.putAll(customJvmMemoryOptions) memory.forEach(BiConsumer { k, v -> result.add(k + v) }) } result.addAll(COMMON_VM_OPTIONS) if (isEAP) { var place = result.indexOf("-ea") if (place < 0) place = result.indexOfFirst { it.startsWith("-D") } if (place < 0) place = result.size // must be consistent with `ConfigImportHelper#updateVMOptions` result.add(place, "-XX:MaxJavaStackTraceDepth=10000") } return result } @JvmStatic @Throws(IOException::class) fun writeVmOptions(file: Path, vmOptions: List<String>, separator: String) { Files.writeString(file, vmOptions.joinToString(separator = separator, postfix = separator), StandardCharsets.US_ASCII) } }
apache-2.0
4d727052cc7d260cfd03b59c277d207d
36.408451
145
0.721386
3.934815
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/tests/testData/resolve/referenceInJava/dependency/dependencies.kt
1
1543
package k public class Class() { public val prop: Int = 0 fun function() = 1 fun <T : Number, G> function2( b: Byte, c: Char, s: Short, i: Int, l: Long, bool: Boolean, f: Float, d: Double, ba: ByteArray, ca: CharArray, ia: IntArray, la: LongArray, boola: BooleanArray, fa: FloatArray, da: DoubleArray, sa: Array<String>, baa: Array<ByteArray>, saa: Array<Array<String>>, t: T, g: G, str: String, nestedClass: Class.F, innerClass: Class.G, nestedNested: Class.F.F ) { } class F { fun function() = 1 class F { fun function() = 1 } } inner class G { fun function() = 5 } } public enum class EnumClass { ENTRY } public fun topLevelFun() { } public class ClassWithClassObject { companion object { fun f() = 1 } } public object KotlinObject { fun f() = 1 } public interface StaticFieldInClassObjectInInterface { companion object { public const val XX: String = "xx" } } object PlatformStaticFun { @JvmStatic fun test() { } } interface InterfaceNoImpl { fun foo() } public class InterfaceWithDelegatedNoImpl(f: InterfaceNoImpl): InterfaceNoImpl by f interface InterfaceWithImpl { fun foo() = 1 } public class InterfaceWithDelegatedWithImpl(f: InterfaceWithImpl) : InterfaceWithImpl by f @kotlin.jvm.JvmOverloads public fun withJvmOverloads(i: Int, b: Boolean = false, s: String="hello") {} annotation class KAnno(val c: Int = 4, val d: String)
apache-2.0
35f49b6b5ca2d10c3f8c6a2f82fbf28d
20.136986
143
0.625405
3.682578
false
false
false
false
mikepenz/Android-Iconics
iconics-core/src/main/java/com/mikepenz/iconics/animation/IconicsAnimatedDrawable.kt
1
4605
/* * Copyright 2020 Mike Penz * * 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.mikepenz.iconics.animation import android.content.res.Resources import android.graphics.Canvas import android.view.View import androidx.core.view.ViewCompat import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.typeface.IIcon import com.mikepenz.iconics.typeface.ITypeface import java.lang.ref.WeakReference import java.util.ArrayList /** * @author pa.gulko zTrap (28.11.2018) */ open class IconicsAnimatedDrawable : IconicsDrawable { private val processors = ArrayList<IconicsAnimationProcessor>() constructor(res: Resources, theme: Resources.Theme? = null) : super(res, theme) constructor(res: Resources, theme: Resources.Theme? = null, icon: Char) : super(res, theme, icon) constructor(res: Resources, theme: Resources.Theme? = null, icon: String) : super(res, theme, icon) constructor(res: Resources, theme: Resources.Theme? = null, icon: IIcon) : super(res, theme, icon) protected constructor(res: Resources, theme: Resources.Theme? = null, typeface: ITypeface, icon: IIcon) : super(res, theme, typeface, icon) // FI-LO override fun draw(canvas: Canvas) { processors.forEach { it.processPreDraw( canvas, iconBrush, contourBrush, backgroundBrush, backgroundContourBrush ) } super.draw(canvas) processors.reversed().forEach { it.processPostDraw(canvas) } } /** Attach an [processor][IconicsAnimationProcessor] to this drawable */ fun processor(processor: IconicsAnimationProcessor): IconicsAnimatedDrawable { processor.setDrawable(this) processors.add(processor) return this } /** Attach an [processors][IconicsAnimationProcessor] to this drawable */ fun processors(vararg processors: IconicsAnimationProcessor): IconicsAnimatedDrawable { if (processors.isEmpty()) return this processors.forEach { processor(it) } return this } /** * @return The runner which used for animations. Animations can be easily removed by calling * [Runner.unset] */ fun animateIn(view: View): IconicsAnimatedDrawable.Runner { return IconicsAnimatedDrawable.Runner().also { it.setFor(view, this) } } class Runner internal constructor() { private var isAttached = false private var view: WeakReference<View>? = null private var drawable: IconicsAnimatedDrawable? = null private val listener = object : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(v: View) { isAttached = true ViewCompat.postOnAnimation(v, object : Runnable { override fun run() { if (isAttached && view?.get() != null) { drawable?.let { v.invalidateDrawable(it) ViewCompat.postOnAnimation(v, this) } } } }) } override fun onViewDetachedFromWindow(v: View) { isAttached = false } } /** Setup all animations to provided drawable and view */ fun setFor(view: View, drawable: IconicsAnimatedDrawable) { unset() this.view = WeakReference(view) this.drawable = drawable if (ViewCompat.isAttachedToWindow(view)) { listener.onViewAttachedToWindow(view) } view.addOnAttachStateChangeListener(listener) } /** Clear all animations from previously provided drawable and view */ fun unset() { drawable = null view?.let { it.get()?.removeOnAttachStateChangeListener(listener) it.clear() } view = null isAttached = false } } }
apache-2.0
099d9fdbea740f493f25891c64dbb6af
33.886364
143
0.622801
4.909382
false
false
false
false
BartoszJarocki/Design-patterns-in-Kotlin
src/behavioral/Interpreter.kt
1
2126
package behavioral interface IntegerExpression { fun evaluate(context: IntegerContext): Int fun replace(character: Char, integerExpression: IntegerExpression): IntegerExpression fun copied(): IntegerExpression } class IntegerContext(var data: MutableMap<Char, Int> = mutableMapOf()) { fun lookup(name: Char): Int = data[name]!! fun assign(expression: IntegerVariableExpression, value: Int) { data[expression.name] = value } } class IntegerVariableExpression(val name: Char) : IntegerExpression { override fun evaluate(context: IntegerContext): Int = context.lookup(name = name) override fun replace(character: Char, integerExpression: IntegerExpression): IntegerExpression { if (character == this.name) return integerExpression.copied() else return IntegerVariableExpression(name = this.name) } override fun copied(): IntegerExpression = IntegerVariableExpression(name = this.name) } class AddExpression(var operand1: IntegerExpression, var operand2: IntegerExpression) : IntegerExpression { override fun evaluate(context: IntegerContext): Int = this.operand1.evaluate(context) + this.operand2.evaluate(context) override fun replace(character: Char, integerExpression: IntegerExpression): IntegerExpression = AddExpression(operand1 = operand1.replace(character = character, integerExpression = integerExpression), operand2 = operand2.replace(character = character, integerExpression = integerExpression)) override fun copied(): IntegerExpression = AddExpression(operand1 = this.operand1, operand2 = this.operand2) } fun main(args: Array<String>) { val context = IntegerContext() val a = IntegerVariableExpression(name = 'A') val b = IntegerVariableExpression(name = 'B') val c = IntegerVariableExpression(name = 'C') val expression = AddExpression(operand1 = a, operand2 = AddExpression(operand1 = b, operand2 = c)) // a + (b + c) context.assign(expression = a, value = 2) context.assign(expression = b, value = 1) context.assign(expression = c, value = 3) println(expression.evaluate(context)) }
apache-2.0
9d644890a9de051184d629fff8a0a94a
41.54
205
0.739887
4.504237
false
false
false
false
allotria/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/util/MarkdownTextUtil.kt
8
1305
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.util import com.intellij.openapi.util.TextRange /** * Text utilities used mainly by Markdown formatter * to perform accurate formatting and reflow of text. */ internal object MarkdownTextUtil { fun getTrimmedRange(text: String, shift: Int = 0): TextRange { val dropStart = text.takeWhile { it.isWhitespace() }.count() val dropLast = text.reversed().takeWhile { it.isWhitespace() }.count() if (dropStart + dropLast >= text.length) return TextRange.EMPTY_RANGE return TextRange.from(shift + dropStart, text.length - dropLast - dropStart) } fun getSplitBySpacesRanges(text: String, shift: Int = 0): Sequence<TextRange> = sequence { var start = -1 var length = -1 for ((index, char) in text.withIndex()) { if (char.isWhitespace()) { if (length > 0) { yield(TextRange.from(shift + start, length)) } start = -1 length = -1 } else { if (start == -1) { start = index length = 0 } length++ } } if (length > 0) { yield(TextRange.from(shift + start, length)) } } }
apache-2.0
0ebc43b9a490824850110e31ac0c9385
28.681818
140
0.62682
3.907186
false
false
false
false
jiro-aqua/vertical-text-viewer
vtextview/src/main/java/jp/gr/aqua/vtextviewer/LaunchActivity.kt
1
1655
package jp.gr.aqua.vtextviewer import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import jp.gr.aqua.vtextviewer.databinding.ActivityLauncherBinding class LaunchActivity : AppCompatActivity() { companion object{ const val JOTA_PACKAGE = "jp.sblo.pandora.jota.plus" const val BETA_PACKAGE = "jp.gr.aqua.jotaplus.beta" const val MAIN_CLASS = "jp.sblo.pandora.jotaplus.Main" const val STORE_URL = "market://details?id=" } lateinit var binding : ActivityLauncherBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLauncherBinding.inflate(layoutInflater) setContentView(binding.root) binding.openJota.setOnClickListener { openJota(JOTA_PACKAGE) } binding.openBeta.setOnClickListener { openJota(BETA_PACKAGE) } binding.settings.setOnClickListener { val intent = Intent(this, PreferenceActivity::class.java) startActivity(intent) finish() } } private fun openJota(pkgname : String){ val intent = Intent().apply{ setClassName(pkgname, MAIN_CLASS) } try{ startActivity(intent) }catch(e:Exception){ val uri = STORE_URL + pkgname val storeIntent = Intent(Intent.ACTION_VIEW, Uri.parse(uri)) try { startActivity(storeIntent) }catch(e:Exception){ e.printStackTrace() } } } }
apache-2.0
a9f00b50b8a83d552d52b30611253d51
28.553571
72
0.62719
4.38992
false
false
false
false
DmytroTroynikov/aemtools
lang/src/main/kotlin/com/aemtools/lang/htl/psi/HtlElementFactory.kt
1
3482
package com.aemtools.lang.htl.psi import com.aemtools.common.constant.const.DOLLAR import com.aemtools.common.util.psiFileFactory import com.aemtools.common.util.findChildrenByType import com.aemtools.lang.htl.file.HtlFileType import com.intellij.lang.ASTNode import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileFactory /** * @author Dmytro Troynikov */ object HtlElementFactory { /** * Create [HtlPropertyAccess] element with given text. * * @param text the text * @param project the project * * @return new htl property access element */ fun createPropertyAccess(text: String, project: Project): HtlPropertyAccess? = project.psiFileFactory() .file("$DOLLAR{$text}") .findChildrenByType(HtlPropertyAccess::class.java) .firstOrNull() /** * Create [ASTNode] of [HtlTypes.DOT_ACCESS] type. * * @param text the text * @param project the project * @return new ast node */ fun createDotAccessIdentifier(text: String, project: Project): ASTNode? = project.psiFileFactory() .file("$DOLLAR{var.$text}") .findChildrenByType(HtlAccessIdentifier::class.java) .firstOrNull() ?.node ?.findChildByType(HtlTypes.DOT_ACCESS) /** * Create [ASTNode] of [HtlTypes.ARRAY_LIKE_ACCESS] type. * Singlequoted version. * * @param text the text * @param project the project * @return new ast node */ fun createArrayLikeAccessSingleQuoted(text: String, project: Project): ASTNode? = project.psiFileFactory() .file("$DOLLAR{var['$text']}") .findChildrenByType(HtlAccessIdentifier::class.java) .firstOrNull() ?.node ?.findChildByType(HtlTypes.ARRAY_LIKE_ACCESS) /** * Create [ASTNode] of {HtlTypes.ARRAY_LIKE_ACCESS] type. * Doublequoted version. * * @param text the text * @param project the project * @return new ast node */ fun createArrayLikeAccessDoublequoted(text: String, project: Project): ASTNode? = project.psiFileFactory() .file("$DOLLAR{var[\"$text\"]}") .findChildrenByType(HtlAccessIdentifier::class.java) .firstOrNull() ?.node ?.findChildByType(HtlTypes.ARRAY_LIKE_ACCESS) /** * Create [HtlStringLiteral] with given value. * * @param value the value of new string literal * @param project the project * @param doublequoted *true* for doublequoted literal (*false* by default) * * @return instance of htl string literal */ fun createStringLiteral(value: String, project: Project, doublequoted: Boolean = false): HtlStringLiteral? = project.psiFileFactory() .file(if (doublequoted) { "$DOLLAR{\"$value\"}" } else { "$DOLLAR{'$value'}" }) .findChildrenByType(HtlStringLiteral::class.java) .firstOrNull() /** * Create option [HtlVariableName] with given name. * * @param value the name of option * @param project the project * * @return new option object */ fun createOption(value: String, project: Project): HtlVariableName? = project.psiFileFactory() .file("$DOLLAR{@ $value}") .findChildrenByType(HtlVariableName::class.java) .firstOrNull() private fun PsiFileFactory.file(text: String): PsiFile = createFileFromText("dummy.html", HtlFileType, text) }
gpl-3.0
3d53b72b17772fb7837ab27c458d6b93
29.54386
110
0.654796
4.314746
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/test/JobExtensionsTest.kt
1
2810
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import kotlin.coroutines.* import kotlin.test.* class JobExtensionsTest : TestBase() { private val job = Job() private val scope = CoroutineScope(job + CoroutineExceptionHandler { _, _ -> }) @Test fun testIsActive() = runTest { expect(1) scope.launch(Dispatchers.Unconfined) { ensureActive() coroutineContext.ensureActive() coroutineContext[Job]!!.ensureActive() expect(2) delay(Long.MAX_VALUE) } expect(3) job.ensureActive() scope.ensureActive() scope.coroutineContext.ensureActive() job.cancelAndJoin() finish(4) } @Test fun testIsCompleted() = runTest { expect(1) scope.launch(Dispatchers.Unconfined) { ensureActive() coroutineContext.ensureActive() coroutineContext[Job]!!.ensureActive() expect(2) } expect(3) job.complete() job.join() assertFailsWith<JobCancellationException> { job.ensureActive() } assertFailsWith<JobCancellationException> { scope.ensureActive() } assertFailsWith<JobCancellationException> { scope.coroutineContext.ensureActive() } finish(4) } @Test fun testIsCancelled() = runTest { expect(1) scope.launch(Dispatchers.Unconfined) { ensureActive() coroutineContext.ensureActive() coroutineContext[Job]!!.ensureActive() expect(2) throw TestException() } expect(3) checkException { job.ensureActive() } checkException { scope.ensureActive() } checkException { scope.coroutineContext.ensureActive() } finish(4) } @Test fun testEnsureActiveWithEmptyContext() = runTest { withEmptyContext { ensureActive() // should not do anything } } private inline fun checkException(block: () -> Unit) { val result = runCatching(block) val exception = result.exceptionOrNull() ?: fail() assertTrue(exception is JobCancellationException) assertTrue(exception.cause is TestException) } @Test fun testJobExtension() = runTest { assertSame(coroutineContext[Job]!!, coroutineContext.job) assertSame(NonCancellable, NonCancellable.job) assertSame(job, job.job) assertFailsWith<IllegalStateException> { EmptyCoroutineContext.job } assertFailsWith<IllegalStateException> { Dispatchers.Default.job } assertFailsWith<IllegalStateException> { (Dispatchers.Default + CoroutineName("")).job } } }
apache-2.0
372fffcff7d1461bc16ff9b6481fee82
28.578947
102
0.621352
5.203704
false
true
false
false
Kotlin/kotlinx.coroutines
reactive/kotlinx-coroutines-rx3/src/RxChannel.kt
1
3176
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.rx3 import io.reactivex.rxjava3.core.* import io.reactivex.rxjava3.disposables.* import kotlinx.atomicfu.* import kotlinx.coroutines.channels.* import kotlinx.coroutines.internal.* import kotlinx.coroutines.flow.* /** * Subscribes to this [MaybeSource] and returns a channel to receive elements emitted by it. * The resulting channel shall be [cancelled][ReceiveChannel.cancel] to unsubscribe from this source. * * This API is internal in the favour of [Flow]. * [MaybeSource] doesn't have a corresponding [Flow] adapter, so it should be transformed to [Observable] first. */ @PublishedApi internal fun <T> MaybeSource<T>.openSubscription(): ReceiveChannel<T> { val channel = SubscriptionChannel<T>() subscribe(channel) return channel } /** * Subscribes to this [ObservableSource] and returns a channel to receive elements emitted by it. * The resulting channel shall be [cancelled][ReceiveChannel.cancel] to unsubscribe from this source. * * This API is internal in the favour of [Flow]. * [ObservableSource] doesn't have a corresponding [Flow] adapter, so it should be transformed to [Observable] first. */ @PublishedApi internal fun <T> ObservableSource<T>.openSubscription(): ReceiveChannel<T> { val channel = SubscriptionChannel<T>() subscribe(channel) return channel } /** * Subscribes to this [MaybeSource] and performs the specified action for each received element. * * If [action] throws an exception at some point or if the [MaybeSource] raises an error, the exception is rethrown from * [collect]. */ public suspend inline fun <T> MaybeSource<T>.collect(action: (T) -> Unit): Unit = openSubscription().consumeEach(action) /** * Subscribes to this [ObservableSource] and performs the specified action for each received element. * * If [action] throws an exception at some point, the subscription is cancelled, and the exception is rethrown from * [collect]. Also, if the [ObservableSource] signals an error, that error is rethrown from [collect]. */ public suspend inline fun <T> ObservableSource<T>.collect(action: (T) -> Unit): Unit = openSubscription().consumeEach(action) @Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER") private class SubscriptionChannel<T> : LinkedListChannel<T>(null), Observer<T>, MaybeObserver<T> { private val _subscription = atomic<Disposable?>(null) @Suppress("CANNOT_OVERRIDE_INVISIBLE_MEMBER") override fun onClosedIdempotent(closed: LockFreeLinkedListNode) { _subscription.getAndSet(null)?.dispose() // dispose exactly once } // Observer overrider override fun onSubscribe(sub: Disposable) { _subscription.value = sub } override fun onSuccess(t: T) { trySend(t) close(cause = null) } override fun onNext(t: T) { trySend(t) // Safe to ignore return value here, expectedly racing with cancellation } override fun onComplete() { close(cause = null) } override fun onError(e: Throwable) { close(cause = e) } }
apache-2.0
7a61adaf22a4a3623838be1ee7680160
33.521739
120
0.720403
4.223404
false
false
false
false
leafclick/intellij-community
platform/configuration-store-impl/src/schemeManager/SchemeManagerImpl.kt
1
23228
// 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.configurationStore.schemeManager import com.intellij.concurrency.ConcurrentCollectionFactory import com.intellij.configurationStore.* import com.intellij.ide.ui.UITheme import com.intellij.ide.ui.laf.TempUIThemeBasedLookAndFeelInfo import com.intellij.openapi.application.ex.DecodeDefaultsUtil import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.AbstractExtensionPointBean import com.intellij.openapi.options.SchemeProcessor import com.intellij.openapi.options.SchemeState import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.util.text.StringUtilRt import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.SafeWriteRequestor import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.newvfs.NewVirtualFile import com.intellij.util.* import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.catch import com.intellij.util.containers.mapSmart import com.intellij.util.io.* import com.intellij.util.text.UniqueNameGenerator import gnu.trove.THashSet import org.jdom.Document import org.jdom.Element import java.io.File import java.io.IOException import java.nio.file.FileSystemException import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Function import java.util.function.Predicate class SchemeManagerImpl<T : Any, MUTABLE_SCHEME : T>(val fileSpec: String, processor: SchemeProcessor<T, MUTABLE_SCHEME>, private val provider: StreamProvider?, internal val ioDirectory: Path, val roamingType: RoamingType = RoamingType.DEFAULT, val presentableName: String? = null, private val schemeNameToFileName: SchemeNameToFileName = CURRENT_NAME_CONVERTER, private val fileChangeSubscriber: FileChangeSubscriber? = null, private val virtualFileResolver: VirtualFileResolver? = null) : SchemeManagerBase<T, MUTABLE_SCHEME>(processor), SafeWriteRequestor, StorageManagerFileWriteRequestor { private val isUseVfs: Boolean get() = fileChangeSubscriber != null || virtualFileResolver != null internal val isOldSchemeNaming = schemeNameToFileName == OLD_NAME_CONVERTER private val isLoadingSchemes = AtomicBoolean() internal val schemeListManager = SchemeListManager(this) internal val schemes: MutableList<T> get() = schemeListManager.schemes internal var cachedVirtualDirectory: VirtualFile? = null internal val schemeExtension: String private val updateExtension: Boolean internal val filesToDelete = ContainerUtil.newConcurrentSet<String>() // scheme could be changed - so, hashcode will be changed - we must use identity hashing strategy internal val schemeToInfo = ConcurrentCollectionFactory.createMap<T, ExternalInfo>(ContainerUtil.identityStrategy()) init { if (processor is SchemeExtensionProvider) { schemeExtension = processor.schemeExtension updateExtension = true } else { schemeExtension = FileStorageCoreUtil.DEFAULT_EXT updateExtension = false } if (isUseVfs) { LOG.runAndLogException { refreshVirtualDirectory() } } } override val rootDirectory: File get() = ioDirectory.toFile() override val allSchemeNames: Collection<String> get() = schemes.mapSmart { processor.getSchemeKey(it) } override val allSchemes: List<T> get() = Collections.unmodifiableList(schemes) override val isEmpty: Boolean get() = schemes.isEmpty() private fun refreshVirtualDirectory() { // store refreshes root directory, so, we don't need to use refreshAndFindFile val directory = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) ?: return cachedVirtualDirectory = directory directory.children if (directory is NewVirtualFile) { directory.markDirty() } directory.refresh(true, false) } override fun loadBundledScheme(resourceName: String, requestor: Any) { try { val url = when (requestor) { is AbstractExtensionPointBean -> requestor.loaderForClass.getResource(resourceName) is TempUIThemeBasedLookAndFeelInfo -> File(resourceName).toURI().toURL() is UITheme -> DecodeDefaultsUtil.getDefaults(requestor.providerClassLoader, resourceName) else -> DecodeDefaultsUtil.getDefaults(requestor, resourceName) } if (url == null) { LOG.error("Cannot read scheme from $resourceName") return } val bytes = URLUtil.openStream(url).readBytes() lazyPreloadScheme(bytes, isOldSchemeNaming) { name, parser -> val attributeProvider = Function<String, String?> { parser.getAttributeValue(null, it) } val fileName = PathUtilRt.getFileName(url.path) val extension = getFileExtension(fileName, true) val externalInfo = ExternalInfo(fileName.substring(0, fileName.length - extension.length), extension) val schemeKey = name ?: (processor as LazySchemeProcessor).getSchemeKey(attributeProvider, externalInfo.fileNameWithoutExtension) ?: throw nameIsMissed(bytes) externalInfo.schemeKey = schemeKey val scheme = (processor as LazySchemeProcessor).createScheme(SchemeDataHolderImpl(processor, bytes, externalInfo), schemeKey, attributeProvider, true) val oldInfo = schemeToInfo.put(scheme, externalInfo) LOG.assertTrue(oldInfo == null) val oldScheme = schemeListManager.readOnlyExternalizableSchemes.put(schemeKey, scheme) if (oldScheme != null) { LOG.warn("Duplicated scheme ${schemeKey} - old: $oldScheme, new $scheme") } schemes.add(scheme) if (requestor is UITheme) { requestor.editorSchemeName = schemeKey } if (requestor is TempUIThemeBasedLookAndFeelInfo) { requestor.theme.editorSchemeName = schemeKey } } } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { LOG.error("Cannot read scheme from $resourceName", e) } } internal fun createSchemeLoader(isDuringLoad: Boolean = false): SchemeLoader<T, MUTABLE_SCHEME> { val filesToDelete = THashSet(filesToDelete) // caller must call SchemeLoader.apply to bring back scheduled for delete files this.filesToDelete.removeAll(filesToDelete) // SchemeLoader can use retain list to bring back previously scheduled for delete file, // but what if someone will call save() during load and file will be deleted, although should be loaded by a new load session // (because modified on disk) return SchemeLoader(this, schemes, filesToDelete, isDuringLoad) } internal fun getFileExtension(fileName: CharSequence, isAllowAny: Boolean): String { return when { StringUtilRt.endsWithIgnoreCase(fileName, schemeExtension) -> schemeExtension StringUtilRt.endsWithIgnoreCase(fileName, FileStorageCoreUtil.DEFAULT_EXT) -> FileStorageCoreUtil.DEFAULT_EXT isAllowAny -> PathUtil.getFileExtension(fileName.toString())!! else -> throw IllegalStateException("Scheme file extension $fileName is unknown, must be filtered out") } } override fun loadSchemes(): Collection<T> { if (!isLoadingSchemes.compareAndSet(false, true)) { throw IllegalStateException("loadSchemes is already called") } try { // isDuringLoad is true even if loadSchemes called not first time, but on reload, // because scheme processor should use cumulative event `reloaded` to update runtime state/caches val schemeLoader = createSchemeLoader(isDuringLoad = true) val isLoadOnlyFromProvider = provider != null && provider.processChildren(fileSpec, roamingType, { canRead(it) }) { name, input, readOnly -> catchAndLog({ "${provider.javaClass.name}: $name" }) { val scheme = schemeLoader.loadScheme(name, input, null) if (readOnly && scheme != null) { schemeListManager.readOnlyExternalizableSchemes.put(processor.getSchemeKey(scheme), scheme) } } true } if (!isLoadOnlyFromProvider) { if (virtualFileResolver == null) { ioDirectory.directoryStreamIfExists({ canRead(it.fileName.toString()) }) { directoryStream -> for (file in directoryStream) { catchAndLog({ file.toString() }) { val bytes = try { Files.readAllBytes(file) } catch (e: FileSystemException) { when { file.isDirectory() -> return@catchAndLog else -> throw e } } schemeLoader.loadScheme(file.fileName.toString(), null, bytes) } } } } else { for (file in virtualDirectory?.children ?: VirtualFile.EMPTY_ARRAY) { catchAndLog({ file.path }) { if (canRead(file.nameSequence)) { schemeLoader.loadScheme(file.name, null, file.contentsToByteArray()) } } } } } val newSchemes = schemeLoader.apply() for (newScheme in newSchemes) { if (processPendingCurrentSchemeName(newScheme)) { break } } fileChangeSubscriber?.invoke(this) return newSchemes } finally { isLoadingSchemes.set(false) } } override fun reload() { processor.beforeReloaded(this) // we must not remove non-persistent (e.g. predefined) schemes, because we cannot load it (obviously) // do not schedule scheme file removing because we just need to update our runtime state, not state on disk removeExternalizableSchemesFromRuntimeState() processor.reloaded(this, loadSchemes()) } // method is used to reflect already performed changes on disk, so, `isScheduleToDelete = false` is passed to `retainExternalInfo` internal fun removeExternalizableSchemesFromRuntimeState() { // todo check is bundled/read-only schemes correctly handled val iterator = schemes.iterator() for (scheme in iterator) { if ((scheme as? SerializableScheme)?.schemeState ?: processor.getState(scheme) == SchemeState.NON_PERSISTENT) { continue } activeScheme?.let { if (scheme === it) { currentPendingSchemeName = processor.getSchemeKey(it) activeScheme = null } } iterator.remove() @Suppress("UNCHECKED_CAST") processor.onSchemeDeleted(scheme as MUTABLE_SCHEME) } retainExternalInfo(isScheduleToDelete = false) } internal fun getFileName(scheme: T) = schemeToInfo.get(scheme)?.fileNameWithoutExtension fun canRead(name: CharSequence) = (updateExtension && name.endsWith(FileStorageCoreUtil.DEFAULT_EXT, true) || name.endsWith(schemeExtension, ignoreCase = true)) && (processor !is LazySchemeProcessor || processor.isSchemeFile(name)) override fun save(errors: MutableList<Throwable>) { if (isLoadingSchemes.get()) { LOG.warn("Skip save - schemes are loading") } var hasSchemes = false val nameGenerator = UniqueNameGenerator() val changedSchemes = SmartList<MUTABLE_SCHEME>() for (scheme in schemes) { val state = (scheme as? SerializableScheme)?.schemeState ?: processor.getState(scheme) if (state == SchemeState.NON_PERSISTENT) { continue } hasSchemes = true if (state != SchemeState.UNCHANGED) { @Suppress("UNCHECKED_CAST") changedSchemes.add(scheme as MUTABLE_SCHEME) } val fileName = getFileName(scheme) if (fileName != null && !isRenamed(scheme)) { nameGenerator.addExistingName(fileName) } } val filesToDelete = THashSet(filesToDelete) for (scheme in changedSchemes) { try { saveScheme(scheme, nameGenerator, filesToDelete) } catch (e: Throwable) { errors.add(RuntimeException("Cannot save scheme $fileSpec/$scheme", e)) } } if (!filesToDelete.isEmpty) { val iterator = schemeToInfo.values.iterator() for (info in iterator) { if (filesToDelete.contains(info.fileName)) { iterator.remove() } } this.filesToDelete.removeAll(filesToDelete) deleteFiles(errors, filesToDelete) // remove empty directory only if some file was deleted - avoid check on each save if (!hasSchemes && (provider == null || !provider.isApplicable(fileSpec, roamingType))) { removeDirectoryIfEmpty(errors) } } } private fun removeDirectoryIfEmpty(errors: MutableList<Throwable>) { ioDirectory.directoryStreamIfExists { for (file in it) { if (!file.isHidden()) { LOG.info("Directory ${ioDirectory.fileName} is not deleted: at least one file ${file.fileName} exists") return@removeDirectoryIfEmpty } } } LOG.info("Remove scheme directory ${ioDirectory.fileName}") if (isUseVfs) { val dir = virtualDirectory cachedVirtualDirectory = null if (dir != null) { runWriteAction { try { dir.delete(this) } catch (e: IOException) { errors.add(e) } } } } else { errors.catch { ioDirectory.delete() } } } private fun saveScheme(scheme: MUTABLE_SCHEME, nameGenerator: UniqueNameGenerator, filesToDelete: MutableSet<String>) { var externalInfo: ExternalInfo? = schemeToInfo.get(scheme) val currentFileNameWithoutExtension = externalInfo?.fileNameWithoutExtension val element = processor.writeScheme(scheme)?.let { it as? Element ?: (it as Document).detachRootElement() } if (element.isEmpty()) { externalInfo?.scheduleDelete(filesToDelete, "empty") return } var fileNameWithoutExtension = currentFileNameWithoutExtension if (fileNameWithoutExtension == null || isRenamed(scheme)) { fileNameWithoutExtension = nameGenerator.generateUniqueName(schemeNameToFileName(processor.getSchemeKey(scheme))) } val fileName = fileNameWithoutExtension!! + schemeExtension // file will be overwritten, so, we don't need to delete it filesToDelete.remove(fileName) val newDigest = element!!.digest() when { externalInfo != null && currentFileNameWithoutExtension === fileNameWithoutExtension && externalInfo.isDigestEquals(newDigest) -> return isEqualToBundledScheme(externalInfo, newDigest, scheme, filesToDelete) -> return // we must check it only here to avoid delete old scheme just because it is empty (old idea save -> new idea delete on open) processor is LazySchemeProcessor && processor.isSchemeDefault(scheme, newDigest) -> { externalInfo?.scheduleDelete(filesToDelete, "equals to default") return } } // stream provider always use LF separator val byteOut = element.toBufferExposingByteArray() var providerPath: String? if (provider != null && provider.enabled) { providerPath = "$fileSpec/$fileName" if (!provider.isApplicable(providerPath, roamingType)) { providerPath = null } } else { providerPath = null } // if another new scheme uses old name of this scheme, we must not delete it (as part of rename operation) @Suppress("SuspiciousEqualsCombination") val renamed = externalInfo != null && fileNameWithoutExtension !== currentFileNameWithoutExtension && currentFileNameWithoutExtension != null && nameGenerator.isUnique(currentFileNameWithoutExtension) if (providerPath == null) { if (isUseVfs) { var file: VirtualFile? = null var dir = virtualDirectory if (dir == null || !dir.isValid) { dir = createDir(ioDirectory, this) cachedVirtualDirectory = dir } if (renamed) { val oldFile = dir.findChild(externalInfo!!.fileName) if (oldFile != null) { // VFS doesn't allow to rename to existing file, so, check it if (dir.findChild(fileName) == null) { runWriteAction { oldFile.rename(this, fileName) } file = oldFile } else { externalInfo.scheduleDelete(filesToDelete, "renamed") } } } if (file == null) { file = dir.getOrCreateChild(fileName, this) } runWriteAction { file.getOutputStream(this).use { byteOut.writeTo(it) } } } else { if (renamed) { externalInfo!!.scheduleDelete(filesToDelete, "renamed") } ioDirectory.resolve(fileName).write(byteOut.internalBuffer, 0, byteOut.size()) } } else { if (renamed) { externalInfo!!.scheduleDelete(filesToDelete, "renamed") } provider!!.write(providerPath, byteOut.internalBuffer, byteOut.size(), roamingType) } if (externalInfo == null) { externalInfo = ExternalInfo(fileNameWithoutExtension, schemeExtension) schemeToInfo.put(scheme, externalInfo) } else { externalInfo.setFileNameWithoutExtension(fileNameWithoutExtension, schemeExtension) } externalInfo.digest = newDigest externalInfo.schemeKey = processor.getSchemeKey(scheme) } private fun isEqualToBundledScheme(externalInfo: ExternalInfo?, newDigest: ByteArray, scheme: MUTABLE_SCHEME, filesToDelete: MutableSet<String>): Boolean { fun serializeIfPossible(scheme: T): Element? { LOG.runAndLogException { @Suppress("UNCHECKED_CAST") val bundledAsMutable = scheme as? MUTABLE_SCHEME ?: return null return processor.writeScheme(bundledAsMutable) as Element } return null } val bundledScheme = schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(scheme)) if (bundledScheme == null) { if ((processor as? LazySchemeProcessor)?.isSchemeEqualToBundled(scheme) == true) { externalInfo?.scheduleDelete(filesToDelete, "equals to bundled") return true } return false } val bundledExternalInfo = schemeToInfo.get(bundledScheme) ?: return false if (bundledExternalInfo.digest == null) { serializeIfPossible(bundledScheme)?.let { bundledExternalInfo.digest = it.digest() } ?: return false } if (bundledExternalInfo.isDigestEquals(newDigest)) { externalInfo?.scheduleDelete(filesToDelete, "equals to bundled") return true } return false } private fun isRenamed(scheme: T): Boolean { val info = schemeToInfo.get(scheme) return info != null && processor.getSchemeKey(scheme) != info.schemeKey } private fun deleteFiles(errors: MutableList<Throwable>, filesToDelete: MutableSet<String>) { if (provider != null) { val iterator = filesToDelete.iterator() for (name in iterator) { errors.catch { val spec = "$fileSpec/$name" if (provider.delete(spec, roamingType)) { LOG.debug { "$spec deleted from provider $provider" } iterator.remove() } } } } if (filesToDelete.isEmpty()) { return } LOG.debug { "Delete scheme files: ${filesToDelete.joinToString()}" } if (isUseVfs) { virtualDirectory?.let { virtualDir -> val childrenToDelete = virtualDir.children.filter { filesToDelete.contains(it.name) } if (childrenToDelete.isNotEmpty()) { runWriteAction { for (file in childrenToDelete) { errors.catch { file.delete(this) } } } } return } } for (name in filesToDelete) { errors.catch { ioDirectory.resolve(name).delete() } } } internal val virtualDirectory: VirtualFile? get() { var result = cachedVirtualDirectory if (result == null) { val path = ioDirectory.systemIndependentPath result = when (virtualFileResolver) { null -> LocalFileSystem.getInstance().findFileByPath(path) else -> virtualFileResolver.resolveVirtualFile(path) } cachedVirtualDirectory = result } return result } override fun setSchemes(newSchemes: List<T>, newCurrentScheme: T?, removeCondition: Predicate<T>?) { schemeListManager.setSchemes(newSchemes, newCurrentScheme, removeCondition) } internal fun retainExternalInfo(isScheduleToDelete: Boolean) { if (schemeToInfo.isEmpty()) { return } val iterator = schemeToInfo.entries.iterator() l@ for ((scheme, info) in iterator) { if (schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(scheme)) === scheme) { continue } for (s in schemes) { if (s === scheme) { filesToDelete.remove(info.fileName) continue@l } } iterator.remove() if (isScheduleToDelete) { info.scheduleDelete(filesToDelete, "requested to delete") } } } override fun addScheme(scheme: T, replaceExisting: Boolean) = schemeListManager.addScheme(scheme, replaceExisting) override fun findSchemeByName(schemeName: String) = schemes.firstOrNull { processor.getSchemeKey(it) == schemeName } override fun removeScheme(name: String) = removeFirstScheme(true) { processor.getSchemeKey(it) == name } override fun removeScheme(scheme: T) = removeScheme(scheme, isScheduleToDelete = true) fun removeScheme(scheme: T, isScheduleToDelete: Boolean) = removeFirstScheme(isScheduleToDelete) { it === scheme } != null override fun isMetadataEditable(scheme: T) = !schemeListManager.readOnlyExternalizableSchemes.containsKey(processor.getSchemeKey(scheme)) override fun toString() = fileSpec internal fun removeFirstScheme(isScheduleToDelete: Boolean, condition: (T) -> Boolean): T? { val iterator = schemes.iterator() for (scheme in iterator) { if (!condition(scheme)) { continue } if (activeScheme === scheme) { activeScheme = null } iterator.remove() if (isScheduleToDelete && processor.isExternalizable(scheme)) { schemeToInfo.remove(scheme)?.scheduleDelete(filesToDelete, "requested to delete (removeFirstScheme)") } return scheme } return null } }
apache-2.0
fc9bd0a9b1b9afe5c3e710b74a8c1da1
35.930048
233
0.667987
5.108423
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/methodsFromAny/callableReferencesEqualToCallablesFromAPI.kt
2
537
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.* import kotlin.test.assertEquals class A { fun foo() = "foo" val bar = "bar" } fun checkEqual(x: Any, y: Any) { assertEquals(x, y) assertEquals(y, x) assertEquals(x.hashCode(), y.hashCode()) } fun box(): String { checkEqual(A::foo, A::class.members.single { it.name == "foo" }) checkEqual(A::bar, A::class.members.single { it.name == "bar" }) return "OK" }
apache-2.0
e9fd56dab406572cb64414c4739ea41e
20.48
72
0.636872
3.196429
false
false
false
false
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/ndrei/teslacorelib/energy/EnergySystemFactory.kt
1
1206
package net.ndrei.teslacorelib.energy import net.minecraft.item.ItemStack import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumFacing import net.minecraftforge.common.capabilities.Capability import net.modcrafters.mclib.energy.IGenericEnergyStorage object EnergySystemFactory { private fun<T, R> Array<T>.firstNonNull(predicate: (element: T) -> R?): R? { @Suppress("LoopToCallChain") for (item in this) { val result = predicate(item) ?: continue return result } return null } fun wrapTileEntity(te: TileEntity, side: EnumFacing) : IGenericEnergyStorage? = EnergySystem.ORDERED.firstNonNull { it.system.wrapTileEntity(te, side) } fun wrapItemStack(stack: ItemStack) : IGenericEnergyStorage? = EnergySystem.ORDERED.firstNonNull { it.system.wrapItemStack(stack) } fun isCapabilitySupported(capability: Capability<*>) = EnergySystem.ORDERED.any { it.system.hasCapability(capability) } fun<T> wrapCapability(capability: Capability<T>, energy: IGenericEnergyStorage) : T? = EnergySystem.ORDERED.firstNonNull { it.system.wrapCapability(capability, energy) } }
mit
a7b8858442d99851584cc2e5e64a8d72
39.233333
96
0.715589
4.516854
false
false
false
false
JuliusKunze/kotlin-native
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/Mappings.kt
1
20764
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.native.interop.gen import org.jetbrains.kotlin.native.interop.indexer.* interface DeclarationMapper { fun getKotlinClassForPointed(structDecl: StructDecl): Classifier fun isMappedToStrict(enumDef: EnumDef): Boolean fun getKotlinNameForValue(enumDef: EnumDef): String fun getPackageFor(declaration: TypeDeclaration): String } fun DeclarationMapper.getKotlinClassFor( objCClassOrProtocol: ObjCClassOrProtocol, isMeta: Boolean = false ): Classifier { val pkg = if (objCClassOrProtocol.isForwardDeclaration) { when (objCClassOrProtocol) { is ObjCClass -> "objcnames.classes" is ObjCProtocol -> "objcnames.protocols" } } else { this.getPackageFor(objCClassOrProtocol) } val className = objCClassOrProtocol.kotlinClassName(isMeta) return Classifier.topLevel(pkg, className) } val PrimitiveType.kotlinType: KotlinClassifierType get() = when (this) { is CharType -> KotlinTypes.byte is BoolType -> KotlinTypes.boolean // TODO: C primitive types should probably be generated as type aliases for Kotlin types. is IntegerType -> when (this.size) { 1 -> KotlinTypes.byte 2 -> KotlinTypes.short 4 -> KotlinTypes.int 8 -> KotlinTypes.long else -> TODO(this.toString()) } is FloatingType -> when (this.size) { 4 -> KotlinTypes.float 8 -> KotlinTypes.double else -> TODO(this.toString()) } else -> throw NotImplementedError() } private val PrimitiveType.bridgedType: BridgedType get() { val kotlinType = this.kotlinType return BridgedType.values().single { it.kotlinType == kotlinType } } private val ObjCPointer.isNullable: Boolean get() = this.nullability != ObjCPointer.Nullability.NonNull /** * Describes the Kotlin types used to represent some C type. */ sealed class TypeMirror(val pointedType: KotlinClassifierType, val info: TypeInfo) { /** * Type to be used in bindings for argument or return value. */ abstract val argType: KotlinType /** * Mirror for C type to be represented in Kotlin as by-value type. */ class ByValue( pointedType: KotlinClassifierType, info: TypeInfo, val valueType: KotlinType, val nullable: Boolean = (info is TypeInfo.Pointer) ) : TypeMirror(pointedType, info) { override val argType: KotlinType get() = valueType.makeNullableAsSpecified(nullable) } /** * Mirror for C type to be represented in Kotlin as by-ref type. */ class ByRef(pointedType: KotlinClassifierType, info: TypeInfo) : TypeMirror(pointedType, info) { override val argType: KotlinType get() = KotlinTypes.cValue.typeWith(pointedType) } } /** * Describes various type conversions for [TypeMirror]. */ sealed class TypeInfo { /** * The conversion from [TypeMirror.argType] to [bridgedType]. */ abstract fun argToBridged(expr: KotlinExpression): KotlinExpression /** * The conversion from [bridgedType] to [TypeMirror.argType]. */ abstract fun argFromBridged( expr: KotlinExpression, scope: KotlinScope, nativeBacked: NativeBacked ): KotlinExpression abstract val bridgedType: BridgedType open fun cFromBridged( expr: NativeExpression, scope: NativeScope, nativeBacked: NativeBacked ): NativeExpression = expr open fun cToBridged(expr: NativeExpression): NativeExpression = expr /** * If this info is for [TypeMirror.ByValue], then this method describes how to * construct pointed-type from value type. */ abstract fun constructPointedType(valueType: KotlinType): KotlinClassifierType class Primitive(override val bridgedType: BridgedType, val varClass: Classifier) : TypeInfo() { override fun argToBridged(expr: KotlinExpression) = expr override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope, nativeBacked: NativeBacked) = expr override fun constructPointedType(valueType: KotlinType) = varClass.typeWith(valueType) } class Boolean : TypeInfo() { override fun argToBridged(expr: KotlinExpression) = "$expr.toByte()" override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope, nativeBacked: NativeBacked) = "$expr.toBoolean()" override val bridgedType: BridgedType get() = BridgedType.BYTE override fun cFromBridged(expr: NativeExpression, scope: NativeScope, nativeBacked: NativeBacked) = "($expr) ? 1 : 0" override fun cToBridged(expr: NativeExpression) = "($expr) ? 1 : 0" override fun constructPointedType(valueType: KotlinType) = KotlinTypes.booleanVarOf.typeWith(valueType) } class Enum(val clazz: Classifier, override val bridgedType: BridgedType) : TypeInfo() { override fun argToBridged(expr: KotlinExpression) = "$expr.value" override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope, nativeBacked: NativeBacked) = scope.reference(clazz) + ".byValue($expr)" override fun constructPointedType(valueType: KotlinType) = clazz.nested("Var").type // TODO: improve } class Pointer(val pointee: KotlinType) : TypeInfo() { override fun argToBridged(expr: String) = "$expr.rawValue" override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope, nativeBacked: NativeBacked) = "interpretCPointer<${pointee.render(scope)}>($expr)" override val bridgedType: BridgedType get() = BridgedType.NATIVE_PTR override fun cFromBridged(expr: NativeExpression, scope: NativeScope, nativeBacked: NativeBacked) = "(void*)$expr" // Note: required for JVM override fun constructPointedType(valueType: KotlinType) = KotlinTypes.cPointerVarOf.typeWith(valueType) } class ObjCPointerInfo(val kotlinType: KotlinType, val type: ObjCPointer) : TypeInfo() { override fun argToBridged(expr: String) = "$expr.rawPtr" override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope, nativeBacked: NativeBacked) = "interpretObjCPointerOrNull<${kotlinType.render(scope)}>($expr)" + if (type.isNullable) "" else "!!" override val bridgedType: BridgedType get() = BridgedType.OBJC_POINTER override fun constructPointedType(valueType: KotlinType) = KotlinTypes.objCObjectVar.typeWith(valueType) } class NSString(val type: ObjCPointer) : TypeInfo() { override fun argToBridged(expr: String) = "CreateNSStringFromKString($expr)" override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope, nativeBacked: NativeBacked) = "CreateKStringFromNSString($expr)" + if (type.isNullable) "" else "!!" override val bridgedType: BridgedType get() = BridgedType.OBJC_POINTER override fun constructPointedType(valueType: KotlinType): KotlinClassifierType { return KotlinTypes.objCStringVarOf.typeWith(valueType) } } class ObjCBlockPointerInfo(val kotlinType: KotlinFunctionType, val type: ObjCBlockPointer) : TypeInfo() { override val bridgedType: BridgedType get() = BridgedType.OBJC_POINTER // When passing Kotlin function as block pointer from Kotlin to native, // it first gets wrapped by a holder in [argToBridged], // and then converted to block in [cFromBridged]. override fun argToBridged(expr: KotlinExpression): KotlinExpression = "createKotlinObjectHolder($expr)" override fun cFromBridged( expr: NativeExpression, scope: NativeScope, nativeBacked: NativeBacked ): NativeExpression { val mappingBridgeGenerator = scope.mappingBridgeGenerator val blockParameters = type.parameterTypes.mapIndexed { index, it -> "p$index" to it.getStringRepresentation() }.joinToString { "${it.second} ${it.first}" } val blockReturnType = type.returnType.getStringRepresentation() val kniFunction = "kniFunction" val codeBuilder = NativeCodeBuilder(scope) return buildString { append("({ ") // Statement expression begins. append("id $kniFunction = $expr; ") // Note: it gets captured below. append("($kniFunction == nil) ? nil : ") append("(id)") // Cast the block to `id`. append("^$blockReturnType($blockParameters) {") // Block begins. // As block body, generate the code which simply bridges to Kotlin and calls the Kotlin function: mappingBridgeGenerator.nativeToKotlin( codeBuilder, nativeBacked, type.returnType, type.parameterTypes.mapIndexed { index, it -> TypedNativeValue(it, "p$index") } + TypedNativeValue(ObjCIdType(ObjCPointer.Nullability.Nullable, emptyList()), kniFunction) ) { kotlinValues -> val kotlinFunctionType = kotlinType.render(this.scope) val kotlinFunction = "unwrapKotlinObjectHolder<$kotlinFunctionType>(${kotlinValues.last()})" "$kotlinFunction(${kotlinValues.dropLast(1).joinToString()})" }.let { codeBuilder.out("return $it;") } codeBuilder.lines.joinTo(this, separator = " ") append(" };") // Block ends. append(" })") // Statement expression ends. } } // When passing block pointer as Kotlin function from native to Kotlin, // it is converted to Kotlin function in [cFromBridged]. override fun cToBridged(expr: NativeExpression): NativeExpression = expr override fun argFromBridged( expr: KotlinExpression, scope: KotlinScope, nativeBacked: NativeBacked ): KotlinExpression { val mappingBridgeGenerator = scope.mappingBridgeGenerator val funParameters = type.parameterTypes.mapIndexed { index, _ -> "p$index" to kotlinType.parameterTypes[index] }.joinToString { "${it.first}: ${it.second.render(scope)}" } val funReturnType = kotlinType.returnType.render(scope) val codeBuilder = KotlinCodeBuilder(scope) val kniBlockPtr = "kniBlockPtr" // Build the anonymous function expression: val anonymousFun = buildString { append("fun($funParameters): $funReturnType {\n") // Anonymous function begins. // As function body, generate the code which simply bridges to native and calls the block: mappingBridgeGenerator.kotlinToNative( codeBuilder, nativeBacked, type.returnType, type.parameterTypes.mapIndexed { index, it -> TypedKotlinValue(it, "p$index") } + TypedKotlinValue(PointerType(VoidType), "interpretCPointer<COpaque>($kniBlockPtr)") ) { nativeValues -> val type = type val blockType = blockTypeStringRepresentation(type) val objCBlock = "((__bridge $blockType)${nativeValues.last()})" "$objCBlock(${nativeValues.dropLast(1).joinToString()})" }.let { codeBuilder.out("return $it") } codeBuilder.build().joinTo(this, separator = "\n") append("}") // Anonymous function ends. } val nullOutput = if (type.isNullable) "null" else "throw NullPointerException()" return "$expr.let { $kniBlockPtr -> if (kniBlockPtr == nativeNullPtr) $nullOutput else $anonymousFun }" } override fun constructPointedType(valueType: KotlinType): KotlinClassifierType { return Classifier.topLevel("kotlinx.cinterop", "ObjCBlockVar").typeWith(valueType) } } class ByRef(val pointed: KotlinType) : TypeInfo() { override fun argToBridged(expr: String) = error(pointed) override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope, nativeBacked: NativeBacked) = error(pointed) override val bridgedType: BridgedType get() = error(pointed) override fun cFromBridged(expr: NativeExpression, scope: NativeScope, nativeBacked: NativeBacked) = error(pointed) override fun cToBridged(expr: String) = error(pointed) // TODO: this method must not exist override fun constructPointedType(valueType: KotlinType): KotlinClassifierType = error(pointed) } } fun mirrorPrimitiveType(type: PrimitiveType): TypeMirror.ByValue { val varClassName = when (type) { is CharType -> "ByteVar" is BoolType -> "BooleanVar" is IntegerType -> when (type.size) { 1 -> "ByteVar" 2 -> "ShortVar" 4 -> "IntVar" 8 -> "LongVar" else -> TODO(type.toString()) } is FloatingType -> when (type.size) { 4 -> "FloatVar" 8 -> "DoubleVar" else -> TODO(type.toString()) } else -> TODO(type.toString()) } val varClass = Classifier.topLevel("kotlinx.cinterop", varClassName) val varClassOf = Classifier.topLevel("kotlinx.cinterop", "${varClassName}Of") val info = if (type == BoolType) { TypeInfo.Boolean() } else { TypeInfo.Primitive(type.bridgedType, varClassOf) } return TypeMirror.ByValue(varClass.type, info, type.kotlinType) } private fun byRefTypeMirror(pointedType: KotlinClassifierType) : TypeMirror.ByRef { val info = TypeInfo.ByRef(pointedType) return TypeMirror.ByRef(pointedType, info) } fun mirror(declarationMapper: DeclarationMapper, type: Type): TypeMirror = when (type) { is PrimitiveType -> mirrorPrimitiveType(type) is RecordType -> byRefTypeMirror(declarationMapper.getKotlinClassForPointed(type.decl).type) is EnumType -> { val pkg = declarationMapper.getPackageFor(type.def) val kotlinName = declarationMapper.getKotlinNameForValue(type.def) when { declarationMapper.isMappedToStrict(type.def) -> { val bridgedType = (type.def.baseType.unwrapTypedefs() as PrimitiveType).bridgedType val clazz = Classifier.topLevel(pkg, kotlinName) val info = TypeInfo.Enum(clazz, bridgedType) TypeMirror.ByValue(clazz.nested("Var").type, info, clazz.type) } !type.def.isAnonymous -> { val baseTypeMirror = mirror(declarationMapper, type.def.baseType) TypeMirror.ByValue( Classifier.topLevel(pkg, kotlinName + "Var").type, baseTypeMirror.info, Classifier.topLevel(pkg, kotlinName).type ) } else -> mirror(declarationMapper, type.def.baseType) } } is PointerType -> { val pointeeType = type.pointeeType val unwrappedPointeeType = pointeeType.unwrapTypedefs() if (unwrappedPointeeType is VoidType) { val info = TypeInfo.Pointer(KotlinTypes.cOpaque) TypeMirror.ByValue(KotlinTypes.cOpaquePointerVar, info, KotlinTypes.cOpaquePointer) } else if (unwrappedPointeeType is ArrayType) { mirror(declarationMapper, pointeeType) } else { val pointeeMirror = mirror(declarationMapper, pointeeType) val info = TypeInfo.Pointer(pointeeMirror.pointedType) TypeMirror.ByValue( KotlinTypes.cPointerVar.typeWith(pointeeMirror.pointedType), info, KotlinTypes.cPointer.typeWith(pointeeMirror.pointedType) ) } } is ArrayType -> { // TODO: array type doesn't exactly correspond neither to pointer nor to value. val elemTypeMirror = mirror(declarationMapper, type.elemType) if (type.elemType.unwrapTypedefs() is ArrayType) { elemTypeMirror } else { val info = TypeInfo.Pointer(elemTypeMirror.pointedType) TypeMirror.ByValue( KotlinTypes.cArrayPointerVar.typeWith(elemTypeMirror.pointedType), info, KotlinTypes.cArrayPointer.typeWith(elemTypeMirror.pointedType) ) } } is FunctionType -> byRefTypeMirror(KotlinTypes.cFunction.typeWith(getKotlinFunctionType(declarationMapper, type))) is Typedef -> { val baseType = mirror(declarationMapper, type.def.aliased) val pkg = declarationMapper.getPackageFor(type.def) val name = type.def.name when (baseType) { is TypeMirror.ByValue -> TypeMirror.ByValue( Classifier.topLevel(pkg, "${name}Var").type, baseType.info, Classifier.topLevel(pkg, name).type, nullable = baseType.nullable ) is TypeMirror.ByRef -> TypeMirror.ByRef(Classifier.topLevel(pkg, name).type, baseType.info) } } is ObjCPointer -> objCPointerMirror(declarationMapper, type) else -> TODO(type.toString()) } private fun objCPointerMirror(declarationMapper: DeclarationMapper, type: ObjCPointer): TypeMirror.ByValue { if (type is ObjCObjectPointer && type.def.name == "NSString") { val info = TypeInfo.NSString(type) return objCMirror(KotlinTypes.string, info, type.isNullable) } val clazz = when (type) { is ObjCIdType -> type.protocols.firstOrNull()?.let { declarationMapper.getKotlinClassFor(it) } ?: KotlinTypes.objCObject is ObjCClassPointer -> KotlinTypes.objCClass is ObjCObjectPointer -> declarationMapper.getKotlinClassFor(type.def) is ObjCInstanceType -> TODO(type.toString()) // Must have already been handled. is ObjCBlockPointer -> return objCBlockPointerMirror(declarationMapper, type) } val valueType = clazz.type return objCMirror(valueType, TypeInfo.ObjCPointerInfo(valueType, type), type.isNullable) } private fun objCBlockPointerMirror(declarationMapper: DeclarationMapper, type: ObjCBlockPointer): TypeMirror.ByValue { val returnType = if (type.returnType.unwrapTypedefs() is VoidType) { KotlinTypes.unit } else { mirror(declarationMapper, type.returnType).argType } val kotlinType = KotlinFunctionType( type.parameterTypes.map { mirror(declarationMapper, it).argType }, returnType ) val info = TypeInfo.ObjCBlockPointerInfo(kotlinType, type) return objCMirror(kotlinType, info, type.isNullable) } private fun objCMirror(valueType: KotlinType, info: TypeInfo, nullable: Boolean) = TypeMirror.ByValue( info.constructPointedType(valueType.makeNullableAsSpecified(nullable)), info, valueType.makeNullable(), // All typedefs to Objective-C pointers would be nullable for simplicity nullable ) fun getKotlinFunctionType(declarationMapper: DeclarationMapper, type: FunctionType): KotlinFunctionType { val returnType = if (type.returnType.unwrapTypedefs() is VoidType) { KotlinTypes.unit } else { mirror(declarationMapper, type.returnType).argType } return KotlinFunctionType( type.parameterTypes.map { mirror(declarationMapper, it).argType }, returnType, nullable = false ) }
apache-2.0
fda1a9de77a0b00a247cb6f8f5a28647
38.475285
118
0.637498
4.89717
false
false
false
false
JuliusKunze/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/library/impl/KonanLibraryWriterImpl.kt
1
4990
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan.library.impl import org.jetbrains.kotlin.backend.konan.library.KonanLibraryReader import llvm.LLVMModuleRef import llvm.LLVMWriteBitcodeToFile import org.jetbrains.kotlin.backend.konan.library.KonanLibrary import org.jetbrains.kotlin.backend.konan.library.KonanLibraryWriter import org.jetbrains.kotlin.backend.konan.library.LinkData import org.jetbrains.kotlin.konan.file.* import org.jetbrains.kotlin.konan.properties.* import org.jetbrains.kotlin.konan.target.KonanTarget abstract class FileBasedLibraryWriter ( val file: File, val currentAbiVersion: Int): KonanLibraryWriter { } class LibraryWriterImpl(override val libDir: File, moduleName: String, currentAbiVersion: Int, override val target: KonanTarget?, val nopack: Boolean = false): FileBasedLibraryWriter(libDir, currentAbiVersion), KonanLibrary { public constructor(path: String, moduleName: String, currentAbiVersion: Int, target:KonanTarget?, nopack: Boolean): this(File(path), moduleName, currentAbiVersion, target, nopack) override val libraryName = libDir.path val klibFile get() = File("${libDir.path}.klib") // TODO: Experiment with separate bitcode files. // Per package or per class. val mainBitcodeFile = File(kotlinDir, "program.kt.bc") override val mainBitcodeFileName = mainBitcodeFile.path val manifestProperties = Properties() init { // TODO: figure out the proper policy here. libDir.deleteRecursively() klibFile.delete() libDir.mkdirs() linkdataDir.mkdirs() targetDir.mkdirs() kotlinDir.mkdirs() nativeDir.mkdirs() includedDir.mkdirs() resourcesDir.mkdirs() // TODO: <name>:<hash> will go somewhere around here. manifestProperties.setProperty("unique_name", "$moduleName") manifestProperties.setProperty("abi_version", "$currentAbiVersion") } var llvmModule: LLVMModuleRef? = null override fun addKotlinBitcode(llvmModule: LLVMModuleRef) { this.llvmModule = llvmModule LLVMWriteBitcodeToFile(llvmModule, mainBitcodeFileName) } override fun addLinkData(linkData: LinkData) { MetadataWriterImpl(this).addLinkData(linkData) } override fun addNativeBitcode(library: String) { val basename = File(library).name File(library).copyTo(File(nativeDir, basename)) } override fun addIncludedBinary(library: String) { val basename = File(library).name File(library).copyTo(File(includedDir, basename)) } override fun addLinkDependencies(libraries: List<KonanLibraryReader>) { if (libraries.isEmpty()) { manifestProperties.remove("depends") // make sure there are no leftovers from the .def file. return } else { val newValue = libraries .map { it.uniqueName } . joinToString(" ") manifestProperties.setProperty("depends", newValue) } } override fun addManifestAddend(path: String) { val properties = File(path).loadProperties() manifestProperties.putAll(properties) } override fun addDataFlowGraph(dataFlowGraph: ByteArray) { dataFlowGraphFile.writeBytes(dataFlowGraph) } override fun commit() { manifestProperties.saveToFile(manifestFile) if (!nopack) { libDir.zipDirAs(klibFile) libDir.deleteRecursively() } } } internal fun buildLibrary( natives: List<String>, included: List<String>, linkDependencies: List<KonanLibraryReader>, linkData: LinkData, abiVersion: Int, target: KonanTarget, output: String, moduleName: String, llvmModule: LLVMModuleRef, nopack: Boolean, manifest: String?, dataFlowGraph: ByteArray?): KonanLibraryWriter { val library = LibraryWriterImpl(output, moduleName, abiVersion, target, nopack) library.addKotlinBitcode(llvmModule) library.addLinkData(linkData) natives.forEach { library.addNativeBitcode(it) } included.forEach { library.addIncludedBinary(it) } manifest ?.let { library.addManifestAddend(it) } library.addLinkDependencies(linkDependencies) dataFlowGraph?.let { library.addDataFlowGraph(it) } library.commit() return library }
apache-2.0
3bbd57b2be171c349b564da5077260b9
32.716216
95
0.699599
4.50361
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/klib/KlibMetaFileType.kt
3
883
// 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.klib import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.KotlinIdeaAnalysisBundle import org.jetbrains.kotlin.library.KLIB_METADATA_FILE_EXTENSION object KlibMetaFileType : FileType { override fun getName() = "KNM" override fun getDescription() = KotlinIdeaAnalysisBundle.message("klib.metadata.short") override fun getDefaultExtension() = KLIB_METADATA_FILE_EXTENSION override fun getIcon(): Nothing? = null override fun isBinary() = true override fun isReadOnly() = true override fun getCharset(file: VirtualFile, content: ByteArray): Nothing? = null const val STUB_VERSION = 2 }
apache-2.0
ea602f74d23eb41b52c171a215827c6f
43.15
158
0.772367
4.349754
false
false
false
false
ianhanniballake/muzei
main/src/main/java/com/google/android/apps/muzei/legacy/LegacySourcePackageListener.kt
1
11932
/* * Copyright 2019 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. */ @file:Suppress("DEPRECATION") package com.google.android.apps.muzei.legacy import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.Drawable import android.util.Log import androidx.core.app.NotificationChannelCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import androidx.core.content.edit import androidx.core.net.toUri import androidx.navigation.NavDeepLinkBuilder import com.google.android.apps.muzei.settings.Prefs import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.channels.sendBlocking import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.map import net.nurik.roman.muzei.R @OptIn(ExperimentalCoroutinesApi::class) class LegacySourcePackageListener( private val applicationContext: Context ) { companion object { private const val TAG = "LegacySourcePackage" private const val PREF_LAST_NOTIFIED = "legacy_last_notified" private const val NOTIFICATION_CHANNEL = "legacy" private const val NOTIFICATION_ID = 19 private const val NOTIFICATION_SUMMARY_TAG = "summary" private const val NOTIFICATION_GROUP_KEY = "legacy" } private val largeIconSize = applicationContext.resources.getDimensionPixelSize( android.R.dimen.notification_large_icon_height) private var lastNotifiedSources = setOf<LegacySourceInfo>() private val prefs = Prefs.getSharedPreferences(applicationContext) init { prefs.getStringSet(PREF_LAST_NOTIFIED, mutableSetOf())?.also { packageNames -> lastNotifiedSources = packageNames.map { packageName -> LegacySourceInfo(packageName) }.toSet() } } /** * A [Flow] that listens for package changes and recomputes all of the * legacy sources found. */ private val legacySources: Flow<Set<LegacySourceInfo>> = callbackFlow { val sourcePackageChangeReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent?) { if (intent?.data == null) { return } val packageName = intent.data?.schemeSpecificPart // Update the sources from the changed package if (BuildConfig.DEBUG) { Log.d(TAG, "Package $packageName changed") } sendBlocking(queryLegacySources()) } } // Register for package change events val packageChangeFilter = IntentFilter().apply { addDataScheme("package") addAction(Intent.ACTION_PACKAGE_ADDED) addAction(Intent.ACTION_PACKAGE_CHANGED) addAction(Intent.ACTION_PACKAGE_REPLACED) addAction(Intent.ACTION_PACKAGE_REMOVED) } applicationContext.registerReceiver(sourcePackageChangeReceiver, packageChangeFilter) send(queryLegacySources()) awaitClose { applicationContext.unregisterReceiver(sourcePackageChangeReceiver) } } private fun queryLegacySources(): Set<LegacySourceInfo> { val queryIntent = Intent(LegacySourceServiceProtocol.ACTION_MUZEI_ART_SOURCE) val pm = applicationContext.packageManager val resolveInfos = pm.queryIntentServices(queryIntent, PackageManager.GET_META_DATA) val legacySources = mutableSetOf<LegacySourceInfo>() for (ri in resolveInfos) { val info = ri.serviceInfo if (info?.metaData?.containsKey("replacement") == true) { // Skip MuzeiArtSources that have a replacement continue } if (BuildConfig.DEBUG) { val legacySource = ComponentName(ri.serviceInfo.packageName, ri.serviceInfo.name) Log.d(TAG, "Found legacy source $legacySource") } val sourceInfo = LegacySourceInfo(ri.serviceInfo.packageName).apply { title = info.applicationInfo.loadLabel(pm).toString() icon = generateSourceImage(info.applicationInfo.loadIcon(pm)) } legacySources.add(sourceInfo) } return legacySources } /** * A [Flow] that represents the list of unsupported legacy sources. * * Users will be notified when a new unsupported source is found */ internal val unsupportedSources = legacySources.map { legacySources -> if (lastNotifiedSources != legacySources) { updateNotifiedSources(legacySources) } legacySources.toList() } private fun updateNotifiedSources(legacySources: Set<LegacySourceInfo>) { val additions = legacySources - lastNotifiedSources val removals = lastNotifiedSources - legacySources val notificationManager = NotificationManagerCompat.from(applicationContext) // Cancel the notification associated with sources that have since been removed removals.forEach { notificationManager.cancel(it.packageName, NOTIFICATION_ID) } lastNotifiedSources = legacySources prefs.edit { putStringSet(PREF_LAST_NOTIFIED, lastNotifiedSources.map { it.packageName }.toSet()) } if (legacySources.isEmpty()) { // If there's no Legacy Sources, cancel any summary notification still present notificationManager.cancel(NOTIFICATION_SUMMARY_TAG, NOTIFICATION_ID) } else { val channel = NotificationChannelCompat.Builder(NOTIFICATION_CHANNEL, NotificationManagerCompat.IMPORTANCE_DEFAULT) .setName(applicationContext.getString(R.string.legacy_notification_channel_name)) .build() notificationManager.createNotificationChannel(channel) val contentIntent = NavDeepLinkBuilder(applicationContext) .setGraph(R.navigation.main_navigation) .setDestination(R.id.legacy_source_info) .createPendingIntent() val learnMorePendingIntent = PendingIntent.getActivity( applicationContext, 0, Intent(Intent.ACTION_VIEW, LegacySourceManager.LEARN_MORE_LINK).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }, 0) // Send a notification for each new Legacy Source for (info in additions) { val sendFeedbackPendingIntent = PendingIntent.getActivity( applicationContext, 0, Intent(Intent.ACTION_VIEW, "https://play.google.com/store/apps/details?id=${info.packageName}".toUri()), 0) val notification = NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL) .setSmallIcon(R.drawable.ic_stat_muzei) .setColor(ContextCompat.getColor(applicationContext, R.color.notification)) .setContentTitle(applicationContext.getString( R.string.legacy_notification_title, info.title)) .setContentText(applicationContext.getString(R.string.legacy_notification_text)) .setContentIntent(contentIntent) .setStyle(NotificationCompat.BigTextStyle().bigText( applicationContext.getString(R.string.legacy_notification_text))) .setLargeIcon(info.icon) .setGroup(NOTIFICATION_GROUP_KEY) .setLocalOnly(true) .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setDefaults(NotificationCompat.DEFAULT_ALL) .setOnlyAlertOnce(true) .addAction(NotificationCompat.Action.Builder(R.drawable.ic_notif_info, applicationContext.getString(R.string.legacy_action_learn_more), learnMorePendingIntent).build()) .addAction(NotificationCompat.Action.Builder(R.drawable.ic_notif_feedback, applicationContext.getString(R.string.legacy_action_send_feedback), sendFeedbackPendingIntent).build()) .build() notificationManager.notify(info.packageName, NOTIFICATION_ID, notification) } // Send a summary notification val summaryText = applicationContext.resources.getQuantityString( R.plurals.legacy_summary_text, legacySources.size, legacySources.size) val summaryNotification = NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL) .setSmallIcon(R.drawable.ic_stat_muzei) .setColor(ContextCompat.getColor(applicationContext, R.color.notification)) .setContentTitle(applicationContext.getString(R.string.legacy_summary_title)) .setContentText(summaryText) .setContentIntent(contentIntent) .setShowWhen(false) .setStyle(NotificationCompat.InboxStyle() .setSummaryText(summaryText) .also { for (info in legacySources) { it.addLine(info.title) } }) .setGroup(NOTIFICATION_GROUP_KEY) .setGroupSummary(true) .setLocalOnly(true) .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setDefaults(NotificationCompat.DEFAULT_ALL) .setOnlyAlertOnce(true) .addAction(NotificationCompat.Action.Builder(R.drawable.ic_notif_info, applicationContext.getString(R.string.legacy_action_learn_more), learnMorePendingIntent).build()) .build() notificationManager.notify(NOTIFICATION_SUMMARY_TAG, NOTIFICATION_ID, summaryNotification) } } private fun generateSourceImage(image: Drawable?) = image?.run { Bitmap.createBitmap(largeIconSize, largeIconSize, Bitmap.Config.ARGB_8888).apply { val canvas = Canvas(this) image.setBounds(0, 0, largeIconSize, largeIconSize) image.draw(canvas) } } } data class LegacySourceInfo(val packageName: String) { lateinit var title: String var icon: Bitmap? = null }
apache-2.0
9ec43c267d6c93d5b81a28894c0381a7
45.609375
109
0.628059
5.493554
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/compiler/asJava/ultraLightClasses/jvmWildcardAnnotations.kt
10
996
class Inv<E> class Out<out T> class OutPair<out Final, out Y> class In<in Z> class Final open class Open class Container { @JvmSuppressWildcards(true) fun deepOpen(x: Out<Out<Out<Open>>>) {} @JvmSuppressWildcards(false) fun bar(): Out<Open> = null!! fun simpleOut(x: Out<@JvmWildcard Final>) {} fun simpleIn(x: In<@JvmWildcard Any?>) {} fun falseTrueFalse(): @JvmSuppressWildcards(false) OutPair<Final, @JvmSuppressWildcards OutPair<Out<Final>, Out<@JvmSuppressWildcards(false) Final>>> = null!! fun combination(): @JvmSuppressWildcards OutPair<Open, @JvmWildcard OutPair<Open, @JvmWildcard Out<Open>>> = null!! @JvmSuppressWildcards(false) fun foo(x: Boolean, y: Out<Int>): Int = 1 @JvmSuppressWildcards(true) fun bar(x: Boolean, y: In<Long>, z: @JvmSuppressWildcards(false) Long): Int = 1 } interface A<T> { @JvmSuppressWildcards(true) fun foo(): Out<T> } interface B { @JvmSuppressWildcards(true) fun foo(): In<Open> }
apache-2.0
39045ffb5ea1661e6caeaeabf534dac7
25.210526
162
0.680723
3.582734
false
false
false
false
smmribeiro/intellij-community
platform/vcs-impl/src/com/intellij/util/ui/cloneDialog/VcsCloneDialog.kt
8
5209
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.ui.cloneDialog import com.intellij.openapi.application.ModalityState import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.CheckoutProvider import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.actions.VcsStatisticsCollector.Companion.CLONE import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogComponentStateListener import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtension import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtensionComponent import com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame import com.intellij.ui.* import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import com.intellij.util.ui.cloneDialog.RepositoryUrlCloneDialogExtension.RepositoryUrlMainExtensionComponent import java.awt.CardLayout import javax.swing.JComponent import javax.swing.JPanel import javax.swing.event.ListSelectionListener /** * Top-level UI-component for new clone/checkout dialog */ class VcsCloneDialog private constructor(private val project: Project, initialExtensionClass: Class<out VcsCloneDialogExtension>, private var initialVcs: Class<out CheckoutProvider>? = null) : DialogWrapper(project) { private lateinit var extensionList: VcsCloneDialogExtensionList private val cardLayout = CardLayout() private val mainPanel = JPanel(cardLayout) private val extensionComponents: MutableMap<String, VcsCloneDialogExtensionComponent> = HashMap() private val listModel = CollectionListModel<VcsCloneDialogExtension>(VcsCloneDialogExtension.EP_NAME.extensionList) private val listener = object : VcsCloneDialogComponentStateListener { override fun onOkActionNameChanged(name: String) = setOKButtonText(name) override fun onOkActionEnabled(enabled: Boolean) { isOKActionEnabled = enabled } override fun onListItemChanged() = listModel.allContentsChanged() } init { init() title = VcsBundle.message("get.from.version.control") JBUI.size(FlatWelcomeFrame.MAX_DEFAULT_WIDTH, FlatWelcomeFrame.DEFAULT_HEIGHT).let { rootPane.minimumSize = it rootPane.preferredSize = it } VcsCloneDialogExtension.EP_NAME.findExtension(initialExtensionClass)?.let { ScrollingUtil.selectItem(extensionList, it) } } override fun getStyle() = DialogStyle.COMPACT override fun createCenterPanel(): JComponent { extensionList = VcsCloneDialogExtensionList(listModel).apply { addListSelectionListener(ListSelectionListener { e -> val source = e.source as VcsCloneDialogExtensionList switchComponent(source.selectedValue) }) preferredSize = JBDimension(200, 0) // width fixed by design } extensionList.accessibleContext.accessibleName = VcsBundle.message("get.from.vcs.extension.list.accessible.name") val scrollableList = ScrollPaneFactory.createScrollPane(extensionList, true).apply { border = IdeBorderFactory.createBorder(SideBorder.RIGHT) } return JBUI.Panels.simplePanel() .addToCenter(mainPanel) .addToLeft(scrollableList) } override fun doValidateAll(): List<ValidationInfo> { return getSelectedComponent()?.doValidateAll() ?: emptyList() } override fun getPreferredFocusedComponent(): JComponent? = getSelectedComponent()?.getPreferredFocusedComponent() fun doClone(checkoutListener: CheckoutProvider.Listener) { val selectedComponent = getSelectedComponent() if (selectedComponent != null) { CLONE.log(project, selectedComponent.javaClass) selectedComponent.doClone(checkoutListener) } } private fun switchComponent(extension: VcsCloneDialogExtension) { val extensionId = extension.javaClass.name val mainComponent = extensionComponents.getOrPut(extensionId, { val component = extension.createMainComponent(project, ModalityState.stateForComponent(window)) mainPanel.add(component.getView(), extensionId) Disposer.register(disposable, component) component.addComponentStateListener(listener) component }) if (mainComponent is RepositoryUrlMainExtensionComponent) { initialVcs?.let { mainComponent.openForVcs(it) } } mainComponent.onComponentSelected() cardLayout.show(mainPanel, extensionId) } private fun getSelectedComponent(): VcsCloneDialogExtensionComponent? { return extensionComponents[extensionList.selectedValue.javaClass.name] } class Builder(private val project: Project) { fun forExtension(clazz: Class<out VcsCloneDialogExtension> = RepositoryUrlCloneDialogExtension::class.java): VcsCloneDialog { return VcsCloneDialog(project, clazz, null) } fun forVcs(clazz: Class<out CheckoutProvider>): VcsCloneDialog { return VcsCloneDialog(project, RepositoryUrlCloneDialogExtension::class.java, clazz) } } }
apache-2.0
c4a96dd6dd5e41febf11132307eeaf1c
41.016129
140
0.772125
5.101861
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/importConversion.kt
2
6576
// 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.j2k import com.intellij.psi.* import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.j2k.ast.Import import org.jetbrains.kotlin.j2k.ast.ImportList import org.jetbrains.kotlin.j2k.ast.assignPrototype import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.annotations.hasJvmStaticAnnotation import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatformAnalyzerServices fun Converter.convertImportList(importList: PsiImportList): ImportList { val imports = importList.allImportStatements .flatMap { convertImport(it) } .distinctBy { it.name } // duplicated imports may appear return ImportList(imports).assignPrototype(importList) } fun Converter.convertImport(anImport: PsiImportStatementBase, dumpConversion: Boolean = false): List<Import> { val reference = anImport.importReference ?: return emptyList() val fqName = FqName(reference.qualifiedName!!) val onDemand = anImport.isOnDemand val convertedImports = if (dumpConversion) { listOf(Import(renderImportName(fqName, onDemand))) } else { convertImport(fqName, reference, onDemand, anImport is PsiImportStaticStatement) .map(::Import) } return convertedImports.map { it.assignPrototype(anImport) } } private fun Converter.convertImport(fqName: FqName, ref: PsiJavaCodeReferenceElement, isOnDemand: Boolean, isImportStatic: Boolean): List<String> { if (!isOnDemand) { if (annotationConverter.isImportNotRequired(fqName)) return emptyList() val mapped = JavaToKotlinClassMap.mapJavaToKotlin(fqName) mapped?.let { // If imported class has a kotlin analog, drop the import if it is not nested if (!it.isNestedClass) return emptyList() return convertNonStaticImport(it.asSingleFqName(), false, null) } } //TODO: how to detect compiled Kotlin here? val target = ref.resolve() return if (isImportStatic) { if (isOnDemand) { convertStaticImportOnDemand(fqName, target) } else { convertStaticExplicitImport(fqName, target) } } else { convertNonStaticImport(fqName, isOnDemand, target) } } private fun Converter.convertStaticImportOnDemand(fqName: FqName, target: PsiElement?): List<String> { when (target) { is KtLightClassForFacade -> return listOf(target.fqName.parent().render() + ".*") is KtLightClass -> { val kotlinOrigin = target.kotlinOrigin val importFromObject = when (kotlinOrigin) { is KtObjectDeclaration -> kotlinOrigin is KtClass -> kotlinOrigin.getCompanionObjects().singleOrNull() else -> null } if (importFromObject != null) { val objectFqName = importFromObject.fqName if (objectFqName != null) { // cannot import on demand from object, generate imports for all members return importFromObject.declarations .mapNotNull { val descriptor = services.resolverForConverter.resolveToDescriptor(it) ?: return@mapNotNull null if (descriptor.hasJvmStaticAnnotation() || descriptor is PropertyDescriptor && descriptor.isConst) descriptor.name else null } .distinct() .map { objectFqName.child(it).render() } } } } } return listOf(renderImportName(fqName, isOnDemand = true)) } private fun convertStaticExplicitImport(fqName: FqName, target: PsiElement?): List<String> { if (target is KtLightDeclaration<*, *>) { val kotlinOrigin = target.kotlinOrigin val nameToImport = if (target is KtLightMethod && kotlinOrigin is KtProperty) kotlinOrigin.nameAsName else fqName.shortName() if (nameToImport != null) { val originParent = kotlinOrigin?.parent when (originParent) { is KtFile -> { // import of function or property accessor from file facade return listOf(originParent.packageFqName.child(nameToImport).render()) } is KtClassBody -> { val parentClass = originParent.parent as KtClassOrObject if (parentClass is KtObjectDeclaration && parentClass.isCompanion()) { return listOfNotNull(parentClass.getFqName()?.child(nameToImport)?.render()) } } } } } return listOf(renderImportName(fqName, isOnDemand = false)) } private fun convertNonStaticImport(fqName: FqName, isOnDemand: Boolean, target: PsiElement?): List<String> { when (target) { is KtLightClassForFacade -> return listOf(target.fqName.parent().render() + ".*") is KtLightClass -> { if (!isOnDemand) { if (isFacadeClassFromLibrary(target)) return emptyList() if (isImportedByDefault(target)) return emptyList() } } } return listOf(renderImportName(fqName, isOnDemand)) } private fun renderImportName(fqName: FqName, isOnDemand: Boolean) = if (isOnDemand) fqName.render() + ".*" else fqName.render() private val DEFAULT_IMPORTS_SET: Set<FqName> = JvmPlatformAnalyzerServices.getDefaultImports( // TODO: use the correct LanguageVersionSettings instance here LanguageVersionSettingsImpl.DEFAULT, includeLowPriorityImports = true ).filter { it.isAllUnder }.map { it.fqName }.toSet() private fun isImportedByDefault(c: KtLightClass) = c.qualifiedName?.let { FqName(it).parent() } in DEFAULT_IMPORTS_SET
apache-2.0
5333aefb3f17092748230ab50f8e18e3
41.425806
158
0.654653
5.058462
false
false
false
false
apache/isis
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/ACTIONS_DELETE.kt
2
2679
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0 import org.apache.causeway.client.kroviz.snapshots.Response object ACTIONS_DELETE : Response() { override val url = "http://localhost:8080/restful/objects/simple.SimpleObject/40/actions/delete" override val str = """{ "id": "delete", "memberType": "action", "links": [ { "rel": "self", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/40/actions/delete", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\"" }, { "rel": "up", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/40", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "Object: Foo" }, { "rel": "urn:org.restfulobjects:rels/invokeaction=\"delete\"", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/40/actions/delete/invoke", "method": "POST", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\"", "arguments": {} }, { "rel": "describedby", "href": "http://localhost:8080/restful/domain-types/simple.SimpleObject/actions/delete", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/action-description\"" } ], "extensions": { "actionType": "user", "actionSemantics": "nonIdempotentAreYouSure" }, "parameters": {} }""" }
apache-2.0
68f944e07d5f2f54fcb62b6d07a398e0
42.209677
109
0.597984
4.327948
false
false
false
false
siosio/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/AbstractProjectModuleOperationProvider.kt
1
5522
package com.jetbrains.packagesearch.intellij.plugin.extensibility import com.intellij.buildsystem.model.OperationFailure import com.intellij.buildsystem.model.OperationItem import com.intellij.buildsystem.model.OperationType import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository import com.intellij.externalSystem.DependencyModifierService import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteAction abstract class AbstractProjectModuleOperationProvider : ProjectModuleOperationProvider { override fun addDependencyToModule( operationMetadata: DependencyOperationMetadata, module: ProjectModule ): List<OperationFailure<out OperationItem>> { val dependency = UnifiedDependency( operationMetadata.groupId, operationMetadata.artifactId, operationMetadata.newVersion, operationMetadata.newScope ) try { runWriteAction { DependencyModifierService.getInstance(module.nativeModule.project).declaredDependencies(operationMetadata.module.nativeModule) .firstOrNull { it.coordinates.groupId == dependency.coordinates.groupId && it.coordinates.artifactId == dependency.coordinates.artifactId } ?.also { DependencyModifierService.getInstance(module.nativeModule.project).updateDependency( operationMetadata.module.nativeModule, it.unifiedDependency, dependency ) } ?: DependencyModifierService.getInstance(module.nativeModule.project) .addDependency(operationMetadata.module.nativeModule, dependency) } return emptyList() } catch (e: Exception) { return listOf(OperationFailure(OperationType.ADD, dependency, e)) } } override fun removeDependencyFromModule( operationMetadata: DependencyOperationMetadata, module: ProjectModule ): List<OperationFailure<out OperationItem>> { val dependency = UnifiedDependency( operationMetadata.groupId, operationMetadata.artifactId, operationMetadata.currentVersion, operationMetadata.currentScope ) try { runWriteAction { DependencyModifierService.getInstance(module.nativeModule.project).removeDependency(operationMetadata.module.nativeModule, dependency) } return emptyList() } catch (e: Exception) { return listOf(OperationFailure(OperationType.REMOVE, dependency, e)) } } override fun updateDependencyInModule( operationMetadata: DependencyOperationMetadata, module: ProjectModule ): List<OperationFailure<out OperationItem>> { val oldDependency = UnifiedDependency( operationMetadata.groupId, operationMetadata.artifactId, operationMetadata.currentVersion, operationMetadata.currentScope ) val newDependency = UnifiedDependency( operationMetadata.groupId, operationMetadata.artifactId, operationMetadata.newVersion, operationMetadata.newScope ?: operationMetadata.currentScope ) try { runWriteAction { DependencyModifierService.getInstance(module.nativeModule.project) .updateDependency(operationMetadata.module.nativeModule, oldDependency, newDependency) } return emptyList() } catch (e: Exception) { return listOf(OperationFailure(OperationType.REMOVE, oldDependency, e)) } } override fun listDependenciesInModule(module: ProjectModule): Collection<UnifiedDependency> = runReadAction { DependencyModifierService.getInstance(module.nativeModule.project) .declaredDependencies(module.nativeModule) .map { dep -> dep.unifiedDependency } } override fun addRepositoryToModule(repository: UnifiedDependencyRepository, module: ProjectModule): List<OperationFailure<out OperationItem>> { try { runWriteAction { DependencyModifierService.getInstance(module.nativeModule.project).addRepository(module.nativeModule, repository) } return emptyList() } catch (e: Exception) { return listOf(OperationFailure(OperationType.ADD, repository, e)) } } override fun removeRepositoryFromModule( repository: UnifiedDependencyRepository, module: ProjectModule ): List<OperationFailure<out OperationItem>> { try { runWriteAction { DependencyModifierService.getInstance(module.nativeModule.project).deleteRepository(module.nativeModule, repository) } return emptyList() } catch (e: Exception) { return listOf(OperationFailure(OperationType.ADD, repository, e)) } } override fun listRepositoriesInModule(module: ProjectModule): Collection<UnifiedDependencyRepository> = runReadAction { DependencyModifierService.getInstance(module.nativeModule.project).declaredRepositories(module.nativeModule) } }
apache-2.0
773abd84c377183d86d55e192169a988
41.476923
150
0.669323
6.558195
false
false
false
false
siosio/intellij-community
plugins/kotlin/i18n/src/org/jetbrains/kotlin/idea/i18n/referenceProviders.kt
1
6367
// 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.i18n import com.intellij.codeInsight.AnnotationUtil import com.intellij.lang.properties.ResourceBundleReference import com.intellij.lang.properties.references.PropertyReference import com.intellij.psi.ElementManipulators import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.PsiReferenceProvider import com.intellij.psi.search.LocalSearchScope import com.intellij.util.ProcessingContext import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.isPlain import org.jetbrains.kotlin.resolve.calls.callUtil.getParentResolvedCall import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver private val PROPERTY_KEY = FqName(AnnotationUtil.PROPERTY_KEY) private val PROPERTY_KEY_RESOURCE_BUNDLE = Name.identifier(AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER) private fun AnnotationDescriptor.getBundleName(): String? { return allValueArguments[PROPERTY_KEY_RESOURCE_BUNDLE]?.value as? String } private fun DeclarationDescriptor.getBundleNameByAnnotation(): String? { return annotations.findAnnotation(PROPERTY_KEY)?.getBundleName() } private fun KtExpression.getBundleNameByContext(): String? { val expression = KtPsiUtil.safeDeparenthesize(this) val parent = expression.parent (parent as? KtProperty)?.let { return it.resolveToDescriptorIfAny()?.getBundleNameByAnnotation() } val bindingContext = expression.analyze(BodyResolveMode.PARTIAL) val resolvedCall = if (parent is KtQualifiedExpression && expression == parent.receiverExpression) { parent.selectorExpression.getResolvedCall(bindingContext) } else { expression.getParentResolvedCall(bindingContext) } ?: return null val callable = resolvedCall.resultingDescriptor if ((resolvedCall.extensionReceiver as? ExpressionReceiver)?.expression == expression) { return callable.extensionReceiverParameter?.annotations?.findAnnotation(PROPERTY_KEY)?.getBundleName() } return resolvedCall.valueArguments.entries .singleOrNull { it.value.arguments.any { it.getArgumentExpression() == expression } } ?.key ?.getBundleNameByAnnotation() } private fun KtAnnotationEntry.getPropertyKeyResolvedCall(): ResolvedCall<*>? { val resolvedCall = resolveToCall() ?: return null val klass = (resolvedCall.resultingDescriptor as? ClassConstructorDescriptor)?.containingDeclaration ?: return null if (klass.kind != ClassKind.ANNOTATION_CLASS || klass.importableFqName != PROPERTY_KEY) return null return resolvedCall } private fun KtStringTemplateExpression.isBundleName(): Boolean { when (val parent = KtPsiUtil.safeDeparenthesize(this).parent) { is KtValueArgument -> { val resolvedCall = parent.getStrictParentOfType<KtAnnotationEntry>()?.getPropertyKeyResolvedCall() ?: return false val valueParameter = (resolvedCall.getArgumentMapping(parent) as? ArgumentMatch)?.valueParameter ?: return false if (valueParameter.name != PROPERTY_KEY_RESOURCE_BUNDLE) return false return true } is KtProperty -> { val contexts = (parent.useScope as? LocalSearchScope)?.scope ?: arrayOf(parent.containingFile) return contexts.any { it.anyDescendantOfType<KtAnnotationEntry> f@{ entry -> if (!entry.valueArguments.any { it.getArgumentName()?.asName == PROPERTY_KEY_RESOURCE_BUNDLE }) return@f false val resolvedCall = entry.getPropertyKeyResolvedCall() ?: return@f false val parameter = resolvedCall.resultingDescriptor.valueParameters.singleOrNull { it.name == PROPERTY_KEY_RESOURCE_BUNDLE } ?: return@f false val valueArgument = resolvedCall.valueArguments[parameter] as? ExpressionValueArgument ?: return@f false val bundleNameExpression = valueArgument.valueArgument?.getArgumentExpression() ?: return@f false bundleNameExpression is KtSimpleNameExpression && bundleNameExpression.mainReference.resolve() == parent } } } } return false } object KotlinPropertyKeyReferenceProvider : PsiReferenceProvider() { override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<out PsiReference> { if (!(element is KtStringTemplateExpression && element.isPlain())) return PsiReference.EMPTY_ARRAY val bundleName = element.getBundleNameByContext() ?: return PsiReference.EMPTY_ARRAY return arrayOf(PropertyReference(ElementManipulators.getValueText(element), element, bundleName, false)) } } object KotlinResourceBundleNameReferenceProvider : PsiReferenceProvider() { override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<out PsiReference> { if (!(element is KtStringTemplateExpression && element.isPlain() && element.isBundleName())) return PsiReference.EMPTY_ARRAY return arrayOf(ResourceBundleReference(element)) } }
apache-2.0
c4583095d800ed0dbe5fe66b4b35fdf5
51.196721
158
0.76551
5.248969
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/runtime/workers/freeze3.kt
2
975
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package runtime.workers.freeze3 import kotlin.test.* import kotlin.native.concurrent.* object AnObject { var x = 1 } @ThreadLocal object Mutable { var x = 2 } val topLevelInline: ULong = 0xc3a5c85c97cb3127U @Test fun runTest1() { assertEquals(1, AnObject.x) if (Platform.memoryModel == MemoryModel.STRICT) { assertFailsWith<InvalidMutabilityException> { AnObject.x++ } assertEquals(1, AnObject.x) } else { AnObject.x++ assertEquals(2, AnObject.x) } Mutable.x++ assertEquals(3, Mutable.x) println("OK") } @Test fun runTest2() { val ok = AtomicInt(0) withWorker() { executeAfter(0, { assertEquals(0xc3a5c85c97cb3127U, topLevelInline) ok.increment() }.freeze()) } assertEquals(1, ok.value) }
apache-2.0
94fb381e3b7cb80120d18002403a4462
18.5
101
0.64
3.385417
false
true
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/KotlinMultilineStringEnterHandler.kt
1
16688
// 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.editor import com.intellij.application.options.CodeStyle import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate.Result import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter import com.intellij.injected.editor.EditorWindow import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.actionSystem.EditorActionHandler import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.util.Ref import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.idea.core.util.toPsiFile import org.jetbrains.kotlin.idea.refactoring.hostEditor import org.jetbrains.kotlin.idea.refactoring.project import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getCallNameExpression import org.jetbrains.kotlin.psi.psiUtil.isSingleQuoted import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull class KotlinMultilineStringEnterHandler : EnterHandlerDelegateAdapter() { private var wasInMultilineString: Boolean = false private var whiteSpaceAfterCaret: String = "" private var isInBrace = false override fun preprocessEnter( file: PsiFile, editor: Editor, caretOffset: Ref<Int>, caretAdvance: Ref<Int>, dataContext: DataContext, originalHandler: EditorActionHandler? ): Result { val offset = caretOffset.get().toInt() if (editor !is EditorWindow) { return preprocessEnter(file, editor, offset, originalHandler, dataContext) } val hostPosition = getHostPosition(dataContext) ?: return Result.Continue return preprocessEnter(hostPosition, originalHandler, dataContext) } private fun preprocessEnter(hostPosition: HostPosition, originalHandler: EditorActionHandler?, dataContext: DataContext): Result { val (file, editor, offset) = hostPosition return preprocessEnter(file, editor, offset, originalHandler, dataContext) } private fun preprocessEnter( file: PsiFile, editor: Editor, offset: Int, originalHandler: EditorActionHandler?, dataContext: DataContext ): Result { if (file !is KtFile) return Result.Continue val document = editor.document val text = document.text if (offset == 0 || offset >= text.length) return Result.Continue val element = file.findElementAt(offset) if (!inMultilineString(element, offset)) { return Result.Continue } else { wasInMultilineString = true } whiteSpaceAfterCaret = text.substring(offset).takeWhile { ch -> ch == ' ' || ch == '\t' } document.deleteString(offset, offset + whiteSpaceAfterCaret.length) val ch1 = text[offset - 1] val ch2 = text[offset] isInBrace = (ch1 == '(' && ch2 == ')') || (ch1 == '{' && ch2 == '}'|| (ch1 == '>' && ch2 == '<')) if (!isInBrace || !CodeInsightSettings.getInstance().SMART_INDENT_ON_ENTER) { return Result.Continue } originalHandler?.execute(editor, editor.caretModel.currentCaret, dataContext) return Result.DefaultForceIndent } override fun postProcessEnter(file: PsiFile, editor: Editor, dataContext: DataContext): Result { if (editor !is EditorWindow) { return postProcessEnter(file, editor) } val hostPosition = getHostPosition(dataContext) ?: return Result.Continue return postProcessEnter(hostPosition.file, hostPosition.editor) } private fun postProcessEnter(file: PsiFile, editor: Editor): Result { if (file !is KtFile) return Result.Continue if (!wasInMultilineString) return Result.Continue wasInMultilineString = false val project = file.project val document = editor.document PsiDocumentManager.getInstance(project).commitDocument(document) val caretModel = editor.caretModel val offset = caretModel.offset val element = file.findElementAt(offset) ?: return Result.Continue val literal = findString(element, offset) ?: return Result.Continue val hasTrimIndentCallInChain = hasTrimIndentCallInChain(literal) val marginChar = if (hasTrimIndentCallInChain) null else getMarginCharFromTrimMarginCallsInChain(literal) ?: getMarginCharFromLiteral(literal) runWriteAction { val settings = MultilineSettings(file) val caretMarker = document.createRangeMarker(offset, offset) caretMarker.isGreedyToRight = true fun caretOffset(): Int = caretMarker.endOffset val prevLineNumber = document.getLineNumber(offset) - 1 assert(prevLineNumber >= 0) val prevLine = getLineByNumber(prevLineNumber, document) val currentLine = getLineByNumber(prevLineNumber + 1, document) val nextLine = if (document.lineCount > prevLineNumber + 2) getLineByNumber(prevLineNumber + 2, document) else "" val wasSingleLine = literal.text.indexOf("\n") == literal.text.lastIndexOf("\n") // Only one '\n' in the string after insertion val lines = literal.text.split("\n") val literalOffset = literal.textRange.startOffset if (wasSingleLine || (lines.size == 3 && isInBrace)) { val shouldUseTrimIndent = hasTrimIndentCallInChain || (marginChar == null && lines.first().trim() == MULTILINE_QUOTE) val newMarginChar: Char? = if (shouldUseTrimIndent) null else (marginChar ?: DEFAULT_TRIM_MARGIN_CHAR) insertTrimCall(document, literal, if (shouldUseTrimIndent) null else newMarginChar) val prevIndent = settings.indentLength(prevLine) val indentSize = prevIndent + settings.marginIndent forceIndent(caretOffset(), indentSize, newMarginChar, document, settings) val isInLineEnd = literal.text.substring(offset - literalOffset) == MULTILINE_QUOTE if (isInLineEnd) { // Move close quote to next line caretMarker.isGreedyToRight = false insertNewLine(caretOffset(), prevIndent, document, settings) caretMarker.isGreedyToRight = true } if (isInBrace) { // Move closing bracket under same indent forceIndent(caretOffset() + 1, indentSize, newMarginChar, document, settings) } } else { val isPrevLineFirst = document.getLineNumber(literalOffset) == prevLineNumber val indentInPreviousLine = when { isPrevLineFirst -> lines.first().substring(MULTILINE_QUOTE.length) else -> prevLine }.prefixLength { it == ' ' || it == '\t' } val prefixStripped = when { isPrevLineFirst -> lines.first().substring(indentInPreviousLine + MULTILINE_QUOTE.length) else -> prevLine.substring(indentInPreviousLine) } val nonBlankNotFirstLines = lines.subList(1, lines.size).filterNot { it.isBlank() || it.trimStart() == MULTILINE_QUOTE } val marginCharToInsert = if (marginChar != null && !prefixStripped.startsWith(marginChar) && nonBlankNotFirstLines.isNotEmpty() && nonBlankNotFirstLines.none { it.trimStart().startsWith(marginChar) } ) { // We have margin char but decide not to insert it null } else { marginChar } if (marginCharToInsert == null || !currentLine.trimStart().startsWith(marginCharToInsert)) { val indentLength = when { isInBrace -> settings.indentLength(nextLine) !isPrevLineFirst -> settings.indentLength(prevLine) else -> settings.indentLength(prevLine) + settings.marginIndent } forceIndent(caretOffset(), indentLength, marginCharToInsert, document, settings) val wsAfterMargin = when { marginCharToInsert != null && prefixStripped.startsWith(marginCharToInsert) -> { prefixStripped.substring(1).takeWhile { it == ' ' || it == '\t' } } else -> "" } // Insert same indent after margin char that previous line has document.insertString(caretOffset(), wsAfterMargin) if (isInBrace) { val nextLineOffset = document.getLineStartOffset(prevLineNumber + 2) forceIndent(nextLineOffset, 0, null, document, settings) document.insertString(nextLineOffset, (marginCharToInsert?.toString() ?: "") + wsAfterMargin) forceIndent(nextLineOffset, indentLength, null, document, settings) } } } document.insertString(caretOffset(), whiteSpaceAfterCaret) caretModel.moveToOffset(caretOffset()) caretMarker.dispose() } return Result.Stop } companion object { private const val DEFAULT_TRIM_MARGIN_CHAR = '|' private const val TRIM_INDENT_CALL = "trimIndent" private const val TRIM_MARGIN_CALL = "trimMargin" private const val MULTILINE_QUOTE = "\"\"\"" class MultilineSettings(file: PsiFile) { private val kotlinIndentOptions = CodeStyle.getIndentOptions(file) private val useTabs = kotlinIndentOptions.USE_TAB_CHARACTER private val tabSize = kotlinIndentOptions.TAB_SIZE private val regularIndent = kotlinIndentOptions.INDENT_SIZE val marginIndent = regularIndent fun getSmartSpaces(count: Int): String = when { useTabs -> StringUtil.repeat("\t", count / tabSize) + StringUtil.repeat(" ", count % tabSize) else -> StringUtil.repeat(" ", count) } fun indentLength(line: String): Int = when { useTabs -> { val tabsCount = line.prefixLength { it == '\t' } tabsCount * tabSize + line.substring(tabsCount).prefixLength { it == ' ' } } else -> line.prefixLength { it == ' ' } } } fun findString(element: PsiElement?, offset: Int): KtStringTemplateExpression? { if (element !is LeafPsiElement) return null when (element.elementType) { KtTokens.REGULAR_STRING_PART -> { // Ok } KtTokens.CLOSING_QUOTE, KtTokens.SHORT_TEMPLATE_ENTRY_START, KtTokens.LONG_TEMPLATE_ENTRY_START -> { if (element.startOffset != offset) { return null } } else -> return null } return element.parents.firstIsInstanceOrNull() } fun inMultilineString(element: PsiElement?, offset: Int) = !(findString(element, offset)?.isSingleQuoted() ?: true) fun getMarginCharFromLiteral(str: KtStringTemplateExpression, marginChar: Char = DEFAULT_TRIM_MARGIN_CHAR): Char? { val lines = str.text.lines() if (lines.size <= 2) return null val middleNonBlank = lines.subList(1, lines.size - 1).filter { !it.isBlank() } if (middleNonBlank.isNotEmpty() && middleNonBlank.all { it.trimStart().startsWith(marginChar) }) { return marginChar } return null } private fun getLiteralCalls(str: KtStringTemplateExpression): Sequence<KtCallExpression> { var previous: PsiElement = str return str.parents .takeWhile { parent -> if (parent is KtQualifiedExpression && parent.receiverExpression == previous) { previous = parent true } else { false } } .mapNotNull { qualified -> (qualified as KtQualifiedExpression).selectorExpression as? KtCallExpression } } fun getMarginCharFromTrimMarginCallsInChain(str: KtStringTemplateExpression): Char? { val literalCall = getLiteralCalls(str).firstOrNull { call -> call.getCallNameExpression()?.text == TRIM_MARGIN_CALL } ?: return null val firstArgument = literalCall.valueArguments.getOrNull(0) ?: return DEFAULT_TRIM_MARGIN_CHAR val argumentExpression = firstArgument.getArgumentExpression() as? KtStringTemplateExpression ?: return DEFAULT_TRIM_MARGIN_CHAR val entry = argumentExpression.entries.singleOrNull() as? KtLiteralStringTemplateEntry ?: return DEFAULT_TRIM_MARGIN_CHAR return entry.text?.singleOrNull() ?: DEFAULT_TRIM_MARGIN_CHAR } fun hasTrimIndentCallInChain(str: KtStringTemplateExpression): Boolean { return getLiteralCalls(str).any { call -> call.getCallNameExpression()?.text == TRIM_INDENT_CALL } } fun getLineByNumber(number: Int, document: Document): String = document.getText(TextRange(document.getLineStartOffset(number), document.getLineEndOffset(number))) fun insertNewLine(nlOffset: Int, indent: Int, document: Document, settings: MultilineSettings) { document.insertString(nlOffset, "\n") forceIndent(nlOffset + 1, indent, null, document, settings) } fun forceIndent(offset: Int, indent: Int, marginChar: Char?, document: Document, settings: MultilineSettings) { val lineNumber = document.getLineNumber(offset) val lineStart = document.getLineStartOffset(lineNumber) val line = getLineByNumber(lineNumber, document) val wsPrefix = line.takeWhile { c -> c == ' ' || c == '\t' } document.replaceString( lineStart, lineStart + wsPrefix.length, settings.getSmartSpaces(indent) + (marginChar?.toString() ?: "") ) } fun String.prefixLength(f: (Char) -> Boolean) = takeWhile(f).count() fun insertTrimCall(document: Document, literal: KtStringTemplateExpression, marginChar: Char?) { if (hasTrimIndentCallInChain(literal) || getMarginCharFromTrimMarginCallsInChain(literal) != null) return if (literal.parents.any { it is KtAnnotationEntry || (it as? KtProperty)?.hasModifier(KtTokens.CONST_KEYWORD) == true }) return if (marginChar == null) { document.insertString(literal.textRange.endOffset, ".$TRIM_INDENT_CALL()") } else { document.insertString( literal.textRange.endOffset, if (marginChar == DEFAULT_TRIM_MARGIN_CHAR) { ".$TRIM_MARGIN_CALL()" } else { ".$TRIM_MARGIN_CALL(\"$marginChar\")" } ) } } private data class HostPosition(val file: PsiFile, val editor: Editor, val offset: Int) private fun getHostPosition(dataContext: DataContext): HostPosition? { val editor = dataContext.hostEditor as? EditorEx ?: return null val project = dataContext.project val virtualFile = editor.virtualFile ?: return null val psiFile = virtualFile.toPsiFile(project) ?: return null return HostPosition(psiFile, editor, editor.caretModel.offset) } } }
apache-2.0
b3fad7b496619910730c682e6e4bb229
43.504
158
0.618528
5.155391
false
false
false
false
androidx/androidx
wear/compose/compose-foundation/src/androidAndroidTest/kotlin/androidx/wear/compose/foundation/CurvedLayoutTest.kt
3
19381
/* * 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.wear.compose.foundation import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import kotlin.math.PI import kotlin.math.abs import kotlin.math.atan2 import kotlin.math.min import org.junit.Assert.assertEquals import org.junit.Assert.fail import org.junit.Rule import org.junit.Test import kotlin.test.assertTrue // When components are laid out, position is specified by integers, so we can't expect // much precision. internal const val FLOAT_TOLERANCE = 1f class CurvedLayoutTest { @get:Rule val rule = createComposeRule() private fun anchor_and_clockwise_test( anchor: Float, anchorType: AnchorType, angularDirection: CurvedDirection.Angular, layoutDirection: LayoutDirection = LayoutDirection.Ltr, initialAnchorType: AnchorType = anchorType ) { var rowCoords: LayoutCoordinates? = null var coords: LayoutCoordinates? = null var anchorTypeState by mutableStateOf(initialAnchorType) var capturedInfo = CapturedInfo() rule.setContent { CompositionLocalProvider(LocalLayoutDirection provides layoutDirection) { CurvedLayout( modifier = Modifier.size(200.dp) .onGloballyPositioned { rowCoords = it }, anchor = anchor, anchorType = anchorTypeState, angularDirection = angularDirection ) { curvedComposable(modifier = CurvedModifier.spy(capturedInfo)) { Box( modifier = Modifier .size(40.dp) .onGloballyPositioned { coords = it } ) } } if (anchorType != initialAnchorType) { LaunchedEffect(true) { anchorTypeState = anchorType } } } } val isLtr = layoutDirection == LayoutDirection.Ltr val clockwise = when (angularDirection) { CurvedDirection.Angular.Normal -> isLtr CurvedDirection.Angular.Reversed -> !isLtr CurvedDirection.Angular.Clockwise -> true CurvedDirection.Angular.CounterClockwise -> false else -> throw java.lang.IllegalArgumentException( "Illegal AngularDirection: $angularDirection" ) } rule.runOnIdle { val dims = RadialDimensions( absoluteClockwise = angularDirection == CurvedDirection.Angular.Normal || angularDirection == CurvedDirection.Angular.Clockwise, rowCoords!!, coords!! ) checkSpy(dims, capturedInfo) // It's at the outer side of the CurvedRow, assertEquals(dims.rowRadius, dims.outerRadius, FLOAT_TOLERANCE) val actualAngle = if (anchorType == AnchorType.Center) { dims.middleAngle } else { if (anchorType == AnchorType.Start == clockwise) { dims.startAngle } else { dims.endAngle } } checkAngle(anchor, actualAngle) } } @Test fun correctly_uses_anchortype_start_clockwise() = anchor_and_clockwise_test(0f, AnchorType.Start, CurvedDirection.Angular.Normal) @Test fun correctly_uses_anchortype_center_clockwise() = anchor_and_clockwise_test(60f, AnchorType.Center, CurvedDirection.Angular.Normal) @Test fun correctly_uses_anchortype_end_clockwise() = anchor_and_clockwise_test(120f, AnchorType.End, CurvedDirection.Angular.Normal) @Test fun correctly_uses_anchortype_start_anticlockwise() = anchor_and_clockwise_test(180f, AnchorType.Start, CurvedDirection.Angular.Reversed) @Test fun correctly_uses_anchortype_center_anticlockwise() = anchor_and_clockwise_test(240f, AnchorType.Center, CurvedDirection.Angular.Reversed) @Test fun correctly_uses_anchortype_end_anticlockwise() = anchor_and_clockwise_test(300f, AnchorType.End, CurvedDirection.Angular.Reversed) @Test fun switched_anchortype_center_to_end_anticlockwise() = anchor_and_clockwise_test( 0f, AnchorType.End, CurvedDirection.Angular.Reversed, initialAnchorType = AnchorType.Center ) @Test fun switched_anchortype_center_to_start_anticlockwise() = anchor_and_clockwise_test( 60f, AnchorType.Start, CurvedDirection.Angular.Reversed, initialAnchorType = AnchorType.Center ) @Test fun switched_anchortype_end_to_center_anticlockwise() = anchor_and_clockwise_test( 120f, AnchorType.Center, CurvedDirection.Angular.Reversed, initialAnchorType = AnchorType.End ) @Test fun switched_anchortype_end_to_start_clockwise() = anchor_and_clockwise_test( 180f, AnchorType.Start, CurvedDirection.Angular.Normal, initialAnchorType = AnchorType.End ) @Test fun switched_anchortype_end_to_center_rtl_anticlockwise() = anchor_and_clockwise_test( 120f, AnchorType.Center, CurvedDirection.Angular.Reversed, initialAnchorType = AnchorType.End, layoutDirection = LayoutDirection.Rtl ) @Test fun switched_anchortype_end_to_start_rtl_clockwise() = anchor_and_clockwise_test( 180f, AnchorType.Start, CurvedDirection.Angular.Normal, initialAnchorType = AnchorType.End, layoutDirection = LayoutDirection.Rtl ) @Test fun switched_anchortype_end_to_center_rtl_absoluteanticlockwise() = anchor_and_clockwise_test( 120f, AnchorType.Center, CurvedDirection.Angular.CounterClockwise, initialAnchorType = AnchorType.End, layoutDirection = LayoutDirection.Rtl ) @Test fun switched_anchortype_end_to_start_rtl_absoluteclockwise() = anchor_and_clockwise_test( 180f, AnchorType.Start, CurvedDirection.Angular.Clockwise, initialAnchorType = AnchorType.End, layoutDirection = LayoutDirection.Rtl ) @Test fun lays_out_multiple_children_correctly() { var rowCoords: LayoutCoordinates? = null val coords = Array<LayoutCoordinates?>(3) { null } rule.setContent { CurvedLayout( modifier = Modifier.onGloballyPositioned { rowCoords = it } ) { repeat(3) { ix -> curvedComposable { Box( modifier = Modifier .size(30.dp) .onGloballyPositioned { coords[ix] = it } ) } } } } rule.runOnIdle { val dims = coords.map { RadialDimensions( absoluteClockwise = true, rowCoords!!, it!! ) } dims.forEach { // They are all at the outer side of the CurvedRow, // and have the same innerRadius and sweep assertEquals(it.rowRadius, it.outerRadius, FLOAT_TOLERANCE) assertEquals(dims[0].innerRadius, it.innerRadius, FLOAT_TOLERANCE) assertEquals(dims[0].sweep, it.sweep, FLOAT_TOLERANCE) } // There are one after another, the middle child is centered at 12 o clock checkAngle(dims[0].endAngle, dims[1].startAngle) checkAngle(dims[1].endAngle, dims[2].startAngle) checkAngle(270f, dims[1].middleAngle) } } private fun radial_alignment_test( radialAlignment: CurvedAlignment.Radial, checker: (bigBoxDimensions: RadialDimensions, smallBoxDimensions: RadialDimensions) -> Unit ) { var rowCoords: LayoutCoordinates? = null var smallBoxCoords: LayoutCoordinates? = null var bigBoxCoords: LayoutCoordinates? = null var smallSpy = CapturedInfo() var bigSpy = CapturedInfo() // We have a big box and a small box with the specified alignment rule.setContent { CurvedLayout( modifier = Modifier.onGloballyPositioned { rowCoords = it } ) { curvedComposable( modifier = CurvedModifier.spy(smallSpy), radialAlignment = radialAlignment ) { Box( modifier = Modifier .size(30.dp) .onGloballyPositioned { smallBoxCoords = it } ) } curvedComposable( modifier = CurvedModifier.spy(bigSpy), ) { Box( modifier = Modifier .size(45.dp) .onGloballyPositioned { bigBoxCoords = it } ) } } } rule.runOnIdle { val bigBoxDimensions = RadialDimensions( absoluteClockwise = true, rowCoords!!, bigBoxCoords!! ) checkSpy(bigBoxDimensions, bigSpy) val smallBoxDimensions = RadialDimensions( absoluteClockwise = true, rowCoords!!, smallBoxCoords!! ) checkSpy(smallBoxDimensions, smallSpy) // There are one after another checkAngle(smallBoxDimensions.endAngle, bigBoxDimensions.startAngle) checker(bigBoxDimensions, smallBoxDimensions) } } @Test fun radial_alignment_outer_works() = radial_alignment_test(CurvedAlignment.Radial.Outer) { bigBoxDimension, smallBoxDimension -> assertEquals( bigBoxDimension.outerRadius, smallBoxDimension.outerRadius, FLOAT_TOLERANCE ) } @Test fun radial_alignment_center_works() = radial_alignment_test(CurvedAlignment.Radial.Center) { bigBoxDimension, smallBoxDimension -> assertEquals( bigBoxDimension.centerRadius, smallBoxDimension.centerRadius, FLOAT_TOLERANCE ) } @Test fun radial_alignment_inner_works() = radial_alignment_test(CurvedAlignment.Radial.Inner) { bigBoxDimension, smallBoxDimension -> assertEquals( bigBoxDimension.innerRadius, smallBoxDimension.innerRadius, FLOAT_TOLERANCE ) } private fun visibility_change_test_setup(targetVisibility: Boolean) { val visible = mutableStateOf(!targetVisibility) rule.setContent { CurvedLayout { curvedComposable { Box(modifier = Modifier.size(30.dp)) } if (visible.value) { curvedComposable { Box(modifier = Modifier.size(30.dp).testTag(TEST_TAG)) } } curvedComposable { Box(modifier = Modifier.size(30.dp)) } } } rule.runOnIdle { visible.value = targetVisibility } rule.waitForIdle() if (targetVisibility) { rule.onNodeWithTag(TEST_TAG).assertExists() } else { rule.onNodeWithTag(TEST_TAG).assertDoesNotExist() } } @Test fun showing_child_works() = visibility_change_test_setup(true) @Test fun hiding_child_works() = visibility_change_test_setup(false) @Test fun change_elements_on_side_effect_works() { var num by mutableStateOf(0) rule.setContent { SideEffect { num = 2 } CurvedLayout(modifier = Modifier.fillMaxSize()) { repeat(num) { curvedComposable() { Box(modifier = Modifier.size(20.dp).testTag("Node$it")) } } } } rule.waitForIdle() rule.onNodeWithTag("Node0").assertExists() rule.onNodeWithTag("Node1").assertExists() rule.onNodeWithTag("Node2").assertDoesNotExist() } } internal const val TEST_TAG = "test-item" fun checkAngle(expected: Float, actual: Float) { var d = abs(expected - actual) d = min(d, 360 - d) if (d > FLOAT_TOLERANCE) { fail("Angle is out of tolerance. Expected: $expected, actual: $actual") } } private fun checkSpy(dimensions: RadialDimensions, capturedInfo: CapturedInfo) = checkCurvedLayoutInfo(dimensions.asCurvedLayoutInfo(), capturedInfo.lastLayoutInfo!!) private fun checkCurvedLayoutInfo(expected: CurvedLayoutInfo, actual: CurvedLayoutInfo) { checkAngle(expected.sweepRadians.toDegrees(), actual.sweepRadians.toDegrees()) assertEquals(expected.outerRadius, actual.outerRadius, FLOAT_TOLERANCE) assertEquals(expected.thickness, actual.thickness, FLOAT_TOLERANCE) assertEquals(expected.centerOffset.x, actual.centerOffset.x, FLOAT_TOLERANCE) assertEquals(expected.centerOffset.y, actual.centerOffset.y, FLOAT_TOLERANCE) checkAngle(expected.startAngleRadians.toDegrees(), actual.startAngleRadians.toDegrees()) } private fun Float.toRadians() = this * PI.toFloat() / 180f private fun Float.toDegrees() = this * 180f / PI.toFloat() private data class RadialPoint(val distance: Float, val angle: Float) // Utility class to compute the dimensions of the annulus segment corresponding to a given component // given that component's and the parent CurvedRow's LayoutCoordinates, and a boolean to indicate // if the layout is clockwise or counterclockwise private class RadialDimensions( absoluteClockwise: Boolean, rowCoords: LayoutCoordinates, coords: LayoutCoordinates ) { // Row dimmensions val rowCenter: Offset val rowRadius: Float // Component dimensions. val innerRadius: Float val outerRadius: Float val centerRadius get() = (innerRadius + outerRadius) / 2 val sweep: Float val startAngle: Float val middleAngle: Float val endAngle: Float init { // Find the radius and center of the CurvedRow, all radial coordinates are relative to this // center rowRadius = min(rowCoords.size.width, rowCoords.size.height) / 2f rowCenter = rowCoords.localToRoot( Offset(rowRadius, rowRadius) ) // Compute the radial coordinates (relative to the center of the CurvedRow) of the found // corners of the component's box and its center val width = coords.size.width.toFloat() val height = coords.size.height.toFloat() val topLeft = toRadialCoordinates(coords, 0f, 0f) val topRight = toRadialCoordinates(coords, width, 0f) val center = toRadialCoordinates(coords, width / 2f, height / 2f) val bottomLeft = toRadialCoordinates(coords, 0f, height) val bottomRight = toRadialCoordinates(coords, width, height) // Ensure the bottom corners are in the same circle assertEquals(bottomLeft.distance, bottomRight.distance, FLOAT_TOLERANCE) // Same with top corners assertEquals(topLeft.distance, topRight.distance, FLOAT_TOLERANCE) // Compute the four dimensions of the annulus sector // Note that startAngle is always before endAngle (even when going counterclockwise) if (absoluteClockwise) { innerRadius = bottomLeft.distance outerRadius = topLeft.distance startAngle = bottomLeft.angle.toDegrees() endAngle = bottomRight.angle.toDegrees() } else { // When components are laid out counterclockwise, they are rotated 180 degrees innerRadius = topLeft.distance outerRadius = bottomLeft.distance startAngle = topRight.angle.toDegrees() endAngle = topLeft.angle.toDegrees() } middleAngle = center.angle.toDegrees() sweep = if (endAngle > startAngle) { endAngle - startAngle } else { endAngle + 360f - startAngle } // All sweep angles are well between 0 and 90 assertTrue( (FLOAT_TOLERANCE..90f - FLOAT_TOLERANCE).contains(sweep), "sweep = $sweep" ) // The outerRadius is greater than the innerRadius assertTrue( outerRadius > innerRadius + FLOAT_TOLERANCE, "innerRadius = $innerRadius, outerRadius = $outerRadius" ) } // TODO: When we finalize CurvedLayoutInfo's API, eliminate the RadialDimensions class and // inline this function to directly convert between LayoutCoordinates and CurvedLayoutInfo. fun asCurvedLayoutInfo() = CurvedLayoutInfo( sweepRadians = sweep.toRadians(), outerRadius = outerRadius, thickness = outerRadius - innerRadius, centerOffset = rowCenter, measureRadius = (outerRadius + innerRadius) / 2, startAngleRadians = startAngle.toRadians() ) fun toRadialCoordinates(coords: LayoutCoordinates, x: Float, y: Float): RadialPoint { val vector = coords.localToRoot(Offset(x, y)) - rowCenter return RadialPoint(vector.getDistance(), atan2(vector.y, vector.x)) } }
apache-2.0
4d1383c40080fd8c0c048d25fde46ee9
34.957328
100
0.609205
4.806796
false
true
false
false
androidx/androidx
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/impl/DisplayInfoManager.kt
3
4752
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.camera2.pipe.integration.impl import android.content.Context import android.graphics.Point import android.hardware.display.DisplayManager import android.hardware.display.DisplayManager.DisplayListener import android.os.Handler import android.os.Looper import android.util.Size import android.view.Display import androidx.annotation.RequiresApi import javax.inject.Inject import javax.inject.Singleton @Suppress("DEPRECATION") // getRealSize @Singleton @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java class DisplayInfoManager @Inject constructor(context: Context) { private val MAX_PREVIEW_SIZE = Size(1920, 1080) companion object { private var lazyMaxDisplay: Display? = null private var lazyPreviewSize: Size? = null internal fun invalidateLazyFields() { lazyMaxDisplay = null lazyPreviewSize = null } internal val displayListener by lazy { object : DisplayListener { override fun onDisplayAdded(displayId: Int) { invalidateLazyFields() } override fun onDisplayRemoved(displayId: Int) { invalidateLazyFields() } override fun onDisplayChanged(displayId: Int) { invalidateLazyFields() } } } } private val displayManager: DisplayManager by lazy { (context.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager).also { it.registerDisplayListener(displayListener, Handler(Looper.getMainLooper())) } } val defaultDisplay: Display get() = getMaxSizeDisplay() val previewSize: Size get() = calculatePreviewSize() private fun getMaxSizeDisplay(): Display { lazyMaxDisplay?.let { return it } val displays = displayManager.displays var maxDisplayWhenStateNotOff: Display? = null var maxDisplaySizeWhenStateNotOff = -1 var maxDisplay: Display? = null var maxDisplaySize = -1 for (display: Display in displays) { val displaySize = Point() // TODO(b/230400472): Use WindowManager#getCurrentWindowMetrics(). Display#getRealSize() // is deprecated since API level 31. display.getRealSize(displaySize) if (displaySize.x * displaySize.y > maxDisplaySize) { maxDisplaySize = displaySize.x * displaySize.y maxDisplay = display } if (display.state != Display.STATE_OFF) { if (displaySize.x * displaySize.y > maxDisplaySizeWhenStateNotOff) { maxDisplaySizeWhenStateNotOff = displaySize.x * displaySize.y maxDisplayWhenStateNotOff = display } } } lazyMaxDisplay = maxDisplayWhenStateNotOff ?: maxDisplay return checkNotNull(lazyMaxDisplay) { "No displays found from ${displayManager.displays}!" } } /** * Calculates the device's screen resolution, or MAX_PREVIEW_SIZE, whichever is smaller. */ private fun calculatePreviewSize(): Size { lazyPreviewSize?.let { return it } val displaySize = Point() val display: Display = defaultDisplay // TODO(b/230400472): Use WindowManager#getCurrentWindowMetrics(). Display#getRealSize() // is deprecated since API level 31. display.getRealSize(displaySize) var displayViewSize: Size displayViewSize = if (displaySize.x > displaySize.y) { Size(displaySize.x, displaySize.y) } else { Size(displaySize.y, displaySize.x) } if (displayViewSize.width * displayViewSize.height > MAX_PREVIEW_SIZE.width * MAX_PREVIEW_SIZE.height ) { displayViewSize = MAX_PREVIEW_SIZE } // TODO(b/230402463): Migrate extra cropping quirk from CameraX. return displayViewSize.also { lazyPreviewSize = displayViewSize } } }
apache-2.0
0e5f27c07033ada8553c331eabd90f3c
33.686131
100
0.647938
4.858896
false
false
false
false
androidx/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/FilledTonalIconButtonTokens.kt
3
2175
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // VERSION: v0_103 // GENERATED CODE - DO NOT MODIFY BY HAND package androidx.compose.material3.tokens import androidx.compose.ui.unit.dp internal object FilledTonalIconButtonTokens { val ContainerColor = ColorSchemeKeyTokens.SecondaryContainer val ContainerShape = ShapeKeyTokens.CornerFull val ContainerSize = 40.0.dp val DisabledContainerColor = ColorSchemeKeyTokens.OnSurface const val DisabledContainerOpacity = 0.12f val DisabledColor = ColorSchemeKeyTokens.OnSurface const val DisabledOpacity = 0.38f val FocusColor = ColorSchemeKeyTokens.OnSecondaryContainer val HoverColor = ColorSchemeKeyTokens.OnSecondaryContainer val Color = ColorSchemeKeyTokens.OnSecondaryContainer val Size = 24.0.dp val PressedColor = ColorSchemeKeyTokens.OnSecondaryContainer val SelectedContainerColor = ColorSchemeKeyTokens.SecondaryContainer val ToggleSelectedFocusColor = ColorSchemeKeyTokens.OnSecondaryContainer val ToggleSelectedHoverColor = ColorSchemeKeyTokens.OnSecondaryContainer val ToggleSelectedColor = ColorSchemeKeyTokens.OnSecondaryContainer val ToggleSelectedPressedColor = ColorSchemeKeyTokens.OnSecondaryContainer val ToggleUnselectedFocusColor = ColorSchemeKeyTokens.OnSurfaceVariant val ToggleUnselectedHoverColor = ColorSchemeKeyTokens.OnSurfaceVariant val ToggleUnselectedColor = ColorSchemeKeyTokens.OnSurfaceVariant val ToggleUnselectedPressedColor = ColorSchemeKeyTokens.OnSurfaceVariant val UnselectedContainerColor = ColorSchemeKeyTokens.SurfaceVariant }
apache-2.0
8b8cc349db3143ddd7cc5ea0ca64375e
46.282609
78
0.805057
5.464824
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/CommitProgressPanel.kt
1
14519
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.vcs.commit import com.intellij.icons.AllIcons import com.intellij.ide.nls.NlsMessages.formatNarrowAndList import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.TooltipDescriptionProvider import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.application.AppUIExecutor.onUiThread import com.intellij.openapi.application.impl.coroutineDispatchingContext import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressSink import com.intellij.openapi.progress.asContextElement import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase import com.intellij.openapi.progress.util.ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsContexts.ProgressDetails import com.intellij.openapi.util.NlsContexts.ProgressText import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsBundle.messagePointer import com.intellij.openapi.vcs.changes.InclusionListener import com.intellij.openapi.wm.ex.ProgressIndicatorEx import com.intellij.openapi.wm.ex.StatusBarEx import com.intellij.openapi.wm.ex.WindowManagerEx import com.intellij.ui.AnimatedIcon import com.intellij.ui.EditorTextComponent import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBPanel import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.components.panels.VerticalLayout import com.intellij.util.ui.* import com.intellij.util.ui.JBUI.Borders.empty import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import java.awt.Component import java.awt.Dimension import java.awt.Font import java.awt.event.* import javax.swing.BoxLayout import javax.swing.JComponent import javax.swing.border.Border import javax.swing.event.HyperlinkEvent import kotlin.properties.Delegates.observable import kotlin.properties.ReadWriteProperty private fun JBLabel.setError(@NlsContexts.Label errorText: String) { text = errorText icon = AllIcons.General.Error foreground = NamedColorUtil.getErrorForeground() isVisible = true } private fun JBLabel.setWarning(@NlsContexts.Label warningText: String) { text = warningText icon = AllIcons.General.Warning foreground = null isVisible = true } open class CommitProgressPanel : CommitProgressUi, InclusionListener, DocumentListener, Disposable { private val scope = CoroutineScope(SupervisorJob() + onUiThread().coroutineDispatchingContext()) .also { Disposer.register(this) { it.cancel() } } private val taskInfo = CommitChecksTaskInfo() private val progressFlow = MutableStateFlow<CommitChecksProgressIndicator?>(null) private var progress: CommitChecksProgressIndicator? by progressFlow::value private val panel = NonOpaquePanel(VerticalLayout(4)) private val scrollPane = FixedSizeScrollPanel(panel, JBDimension(400, 150)) private val failuresPanel = FailuresPanel() private val label = JBLabel().apply { isVisible = false } override var isEmptyMessage by stateFlag() override var isEmptyChanges by stateFlag() override var isDumbMode by stateFlag() protected fun stateFlag(): ReadWriteProperty<Any?, Boolean> { return observable(false) { _, oldValue, newValue -> if (oldValue == newValue) return@observable update() } } val component: JComponent get() = scrollPane fun setup(commitWorkflowUi: CommitWorkflowUi, commitMessage: EditorTextComponent, border: Border) { panel.add(label) panel.add(failuresPanel) panel.border = border Disposer.register(commitWorkflowUi, this) commitMessage.addDocumentListener(this) commitWorkflowUi.addInclusionListener(this, this) setupProgressVisibilityDelay() setupProgressSpinnerTooltip() MyVisibilitySynchronizer().install() } @Suppress("EXPERIMENTAL_API_USAGE") private fun setupProgressVisibilityDelay() { progressFlow .debounce(DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS.toLong()) .onEach { indicator -> if (indicator?.isRunning == true && failuresPanel.isEmpty()) { indicator.component.isVisible = true revalidatePanel() } } .launchIn(scope + CoroutineName("Commit checks indicator visibility")) } private fun setupProgressSpinnerTooltip() { val tooltip = CommitChecksProgressIndicatorTooltip({ progress }, { failuresPanel.width }) tooltip.installOn(failuresPanel.iconLabel, this) } override fun dispose() = Unit override suspend fun <T> runWithProgress(isOnlyRunCommitChecks: Boolean, action: suspend CoroutineScope.() -> T): T { check(progress == null) { "Commit checks indicator already created" } val indicator = InlineCommitChecksProgressIndicator(isOnlyRunCommitChecks) Disposer.register(this, indicator) progress = indicator val context = currentCoroutineContext() indicator.component.isVisible = false indicator.addStateDelegate(object : AbstractProgressIndicatorExBase() { override fun start() = progressStarted(indicator) override fun stop() = progressStopped(indicator) override fun cancel() = context.cancel() // cancel coroutine }) indicator.start() try { return withContext(IndeterminateProgressSink(indicator).asContextElement(), block = action) } finally { indicator.stop() } } private fun progressStarted(indicator: InlineCommitChecksProgressIndicator) { logger<CommitProgressPanel>().assertTrue(progress == indicator) panel.add(indicator.component) addToStatusBar(indicator.statusBarDelegate) failuresPanel.clearFailures() revalidatePanel() } private fun progressStopped(indicator: InlineCommitChecksProgressIndicator) { logger<CommitProgressPanel>().assertTrue(progress == indicator) progress = null panel.remove(indicator.component) removeFromStatusBar(indicator.statusBarDelegate) Disposer.dispose(indicator) failuresPanel.endProgress() revalidatePanel() } private fun revalidatePanel() { component.parent?.let { it.revalidate() it.repaint() } } private fun addToStatusBar(progress: ProgressIndicatorEx) { val frame = WindowManagerEx.getInstanceEx().findFrameFor(null) ?: return val statusBar = frame.statusBar as? StatusBarEx ?: return statusBar.addProgress(progress, taskInfo) } private fun removeFromStatusBar(progress: ProgressIndicatorEx) { // `finish` tracks list of finished `TaskInfo`-s - so we pass new instance to remove from status bar progress.finish(taskInfo) } override fun addCommitCheckFailure(failure: CommitCheckFailure) { progress?.component?.isVisible = false failuresPanel.addFailure(failure) revalidatePanel() } override fun clearCommitCheckFailures() { failuresPanel.clearFailures() revalidatePanel() } override fun getCommitCheckFailures(): List<CommitCheckFailure> { return failuresPanel.getFailures() } override fun documentChanged(event: DocumentEvent) = clearError() override fun inclusionChanged() = clearError() protected fun update() { val error = buildErrorText() when { error != null -> label.setError(error) isDumbMode -> label.setWarning(message("label.commit.checks.not.available.during.indexing")) else -> label.isVisible = false } revalidatePanel() } protected open fun clearError() { isEmptyMessage = false isEmptyChanges = false } @NlsContexts.Label protected open fun buildErrorText(): String? = when { isEmptyChanges && isEmptyMessage -> message("error.no.changes.no.commit.message") isEmptyChanges -> message("error.no.changes.to.commit") isEmptyMessage -> message("error.no.commit.message") else -> null } private inner class MyVisibilitySynchronizer : ContainerListener { private val childListener = object : ComponentAdapter() { override fun componentShown(e: ComponentEvent) { syncVisibility() } override fun componentHidden(e: ComponentEvent) { syncVisibility() } } fun install() { panel.addContainerListener(this) for (child in panel.components) { child.addComponentListener(childListener) } syncVisibility() } override fun componentAdded(e: ContainerEvent) { e.child.addComponentListener(childListener) syncVisibility() } override fun componentRemoved(e: ContainerEvent) { e.child.removeComponentListener(childListener) syncVisibility() } private fun syncVisibility() { val isVisible = panel.components.any { it.isVisible } if (scrollPane.isVisible != isVisible) { scrollPane.isVisible = isVisible revalidatePanel() } } } } sealed class CommitCheckFailure { object Unknown : CommitCheckFailure() open class WithDescription(val text: @NlsContexts.NotificationContent String) : CommitCheckFailure() class WithDetails(text: @NlsContexts.NotificationContent String, val viewDetailsActionText: @NlsContexts.NotificationContent String, val viewDetails: () -> Unit) : WithDescription(text) } private class FailuresPanel : JBPanel<FailuresPanel>() { private var nextFailureId = 0 private val failures = mutableMapOf<Int, CommitCheckFailure>() val iconLabel = JBLabel() private val description = FailuresDescriptionPanel() init { layout = BoxLayout(this, BoxLayout.X_AXIS) add(iconLabel) add(description.apply { border = empty(4, 4, 0, 0) }) add(createCommitChecksToolbar(this).component) isOpaque = false isVisible = false } fun isEmpty(): Boolean = failures.isEmpty() fun clearFailures() { isVisible = false iconLabel.icon = null failures.clear() update() } fun addFailure(failure: CommitCheckFailure) { isVisible = true iconLabel.icon = AnimatedIcon.Default() failures[nextFailureId++] = failure update() } fun endProgress() { isVisible = failures.isNotEmpty() if (isVisible) iconLabel.icon = AllIcons.General.Warning } fun getFailures() = failures.values.toList() private fun update() { description.failures = failures description.update() } } private class FailuresDescriptionPanel : HtmlPanel() { private val isInitialized = true // workaround as `getBody()` is called from super constructor var failures: Map<Int, CommitCheckFailure> = emptyMap() // For `BoxLayout` to layout "commit checks toolbar" right after failures description override fun getMaximumSize(): Dimension { val size = super.getMaximumSize() if (isMaximumSizeSet) return size return Dimension(size).apply { width = preferredSize.width } } override fun getBodyFont(): Font = StartupUiUtil.getLabelFont() override fun getBody(): String = if (isInitialized) buildDescription().toString() else "" override fun hyperlinkUpdate(e: HyperlinkEvent) = showDetails(e) private fun buildDescription(): HtmlChunk { if (failures.isEmpty()) return HtmlChunk.empty() val failureLinks = formatNarrowAndList(failures.mapNotNull { when (val failure = it.value) { is CommitCheckFailure.WithDetails -> HtmlChunk.link(it.key.toString(), failure.text) is CommitCheckFailure.WithDescription -> HtmlChunk.text(failure.text) else -> null } }) if (failureLinks.isBlank()) return HtmlChunk.text(message("label.commit.checks.failed.unknown.reason")) return HtmlChunk.raw(failureLinks) } private fun showDetails(event: HyperlinkEvent) { if (event.eventType != HyperlinkEvent.EventType.ACTIVATED) return val failure = failures[event.description.toInt()] as? CommitCheckFailure.WithDetails ?: return failure.viewDetails() } } private fun createCommitChecksToolbar(target: JComponent): ActionToolbar = ActionManager.getInstance().createActionToolbar( "ChangesView.CommitChecksToolbar", DefaultActionGroup(RerunCommitChecksAction()), true ).apply { setTargetComponent(target) (this as? ActionToolbarImpl)?.setForceMinimumSize(true) // for `BoxLayout` setReservePlaceAutoPopupIcon(false) layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY component.isOpaque = false component.border = null } private class RerunCommitChecksAction : AnActionWrapper(ActionManager.getInstance().getAction("Vcs.RunCommitChecks")), TooltipDescriptionProvider { init { templatePresentation.apply { setText(Presentation.NULL_STRING) setDescription(messagePointer("tooltip.rerun.commit.checks")) icon = AllIcons.General.InlineRefresh hoveredIcon = AllIcons.General.InlineRefreshHover } } } private class IndeterminateProgressSink(private val indicator: ProgressIndicator) : ProgressSink { override fun update(text: @ProgressText String?, details: @ProgressDetails String?, fraction: Double?) { if (text != null) { indicator.text = text } if (details != null) { indicator.text2 = details } // ignore fraction updates } } internal class FixedSizeScrollPanel(view: Component, private val fixedSize: Dimension) : JBScrollPane(view) { init { border = empty() viewportBorder = empty() isOpaque = false horizontalScrollBar.isOpaque = false verticalScrollBar.isOpaque = false viewport.isOpaque = false } override fun getPreferredSize(): Dimension { val size = super.getPreferredSize() if (size.width > fixedSize.width) { size.width = fixedSize.width if (size.height < horizontalScrollBar.height * 2) { size.height = horizontalScrollBar.height * 2 // better handling of a transparent scrollbar for a single text line } } if (size.height > fixedSize.height) { size.height = fixedSize.height } return size } }
apache-2.0
44815aed748191dd400a80afd9d30976
32.072893
121
0.742269
4.66399
false
false
false
false
phase/lang-kotlin-antlr-compiler
src/main/kotlin/xyz/jadonfowler/compiler/ast/ast.kt
1
20160
package xyz.jadonfowler.compiler.ast import org.antlr.v4.runtime.ParserRuleContext import xyz.jadonfowler.compiler.globalModules import java.util.* interface Node /** * Used in ASTBuilder for areas where we need to return something. */ class EmptyNode : Node /** * Modules are compilation units that contain global variables, functions, and classes. */ class Module(val name: String, val imports: List<Import>, val globalVariables: List<Variable>, val globalFunctions: List<Function>, val globalClasses: List<Clazz>, val globalTraits: List<Trait>, val source: String) : Node { val errors: MutableList<String> = mutableListOf() // TODO: I thought this was needed but I never used it. // fun containsReference(reference: Reference): Boolean { // return globalVariables.map { it.name }.contains(reference.name) // || globalFunctions.map { it.name }.contains(reference.name) // || globalClasses.map { it.name }.contains(reference.name) // } fun getFunctionFromReference(reference: Reference): Function? { val moduleName = name val name = reference.name val thingsWithName: List<Function> = globalFunctions.filter { it.name == name } if (thingsWithName.isNotEmpty()) return thingsWithName.last() // Go through imports val imports = imports.map { it.reference.name }.filter { it != moduleName } globalModules.forEach { if (imports.contains(it.name)) { val function = it.getFunctionFromReference(reference) if (function != null) return function } } return null } fun getClazzFromReference(reference: Reference): Clazz? { val moduleName = name val name = reference.name val thingsWithName: List<Clazz> = globalClasses.filter { it.name == name } if (thingsWithName.isNotEmpty()) return thingsWithName.last() // Go through imports val imports = imports.map { it.reference.name }.filter { it != moduleName } globalModules.forEach { if (imports.contains(it.name)) { val clazz = it.getClazzFromReference(reference) if (clazz != null) return clazz } } return null } fun getNodeFromReference(reference: Reference, localVariables: MutableMap<String, Variable>?): Node? { val name = reference.name val thingsWithName: MutableList<Node> = mutableListOf() thingsWithName.addAll(globalClasses.filter { it.name == name }) thingsWithName.addAll(globalTraits.filter { it.name == name }) thingsWithName.addAll(globalFunctions.filter { it.name == name }) thingsWithName.addAll(globalVariables.filter { it.name == name }) localVariables?.forEach { if (it.key == name) thingsWithName.add(it.value) } if (thingsWithName.isNotEmpty()) { val lastThingWithName = thingsWithName.last() when (lastThingWithName) { is Clazz -> return lastThingWithName is Trait -> return lastThingWithName is Function -> return lastThingWithName is Variable -> return lastThingWithName is Formal -> return lastThingWithName } } // Go through imports val imports = imports.map { it.reference.name } globalModules.filter { imports.contains(it.name) }.forEach { val node = it.getNodeFromReference(reference, null) if (node != null) return node } return null } } /** * Container for name of module to import */ class Import(val reference: Reference, val context: ParserRuleContext) : Node /** * Attributes can be put on various declarations */ class Attribute(val name: String, val values: List<String>, val context: ParserRuleContext) : Node { override fun toString(): String = "@$name" override fun hashCode(): Int = Objects.hash(name, values) override fun equals(other: Any?): Boolean = other is Attribute && other.name == name && other.values == values && other.hashCode() == hashCode() } /** * Declaration that can be accessed outside the Module */ interface Global : Node /** * Functions have a return type, which is the type of the value that is returned; * a list of Formals (aka Arguments), which are used inside the Function; * a list of Statements, which are executed in order and can use any formals or global objects; * and an optional last expression. The last expression is used as the return value for the function. * If there is no last expression, the function returns "void" (aka nothing). */ class Function(val prototype: Prototype, val statements: List<Statement>, var expression: Expression? = null, val context: ParserRuleContext) : Global, Type { constructor(attributes: List<Attribute>, returnType: Type, name: String, formals: List<Formal>, statements: List<Statement>, expression: Expression? = null, context: ParserRuleContext) : this(Prototype(attributes, returnType, name, formals), statements, expression, context) override fun toString(): String { val formals = formals.joinToString(separator = " -> ") { it.type.toString() } return "($formals -> $returnType)" } override fun hashCode(): Int = Objects.hash(attributes, returnType, name, formals, statements, expression) override fun equals(other: Any?): Boolean = other is Function && other.hashCode() == hashCode() && other.attributes == attributes && other.returnType == returnType && other.name == name && other.formals == formals fun copy() = Function(attributes, returnType, name, formals, statements, expression, context) override fun isCopyable(): Boolean = false class Prototype(val attributes: List<Attribute>, var returnType: Type, var name: String, var formals: List<Formal>) { override fun hashCode(): Int = Objects.hash(attributes, returnType, name, formals) override fun equals(other: Any?): Boolean = other is Prototype && other.attributes == attributes && other.returnType == returnType && other.name == name && other.formals == formals } // Prototype Boilerplate val attributes: List<Attribute> get() = prototype.attributes var returnType: Type get() = prototype.returnType set(value) { prototype.returnType = value } var name: String get() = prototype.name set(value) { prototype.name = value } var formals: List<Formal> get() = prototype.formals set(value) { prototype.formals = value } } /** * Formals are the arguments for Functions. */ class Formal(type: Type, name: String, context: ParserRuleContext) : Variable(type, name, null, true, context) /** * Variables have a type, name, and can have an initial expression. * * ``` * let a = 7 * ``` * * The type will be inferred to 'int' and the initial expression will be an IntegerLiteral(7). * * If 'constant' is true, the value of this variable can't be changed. */ open class Variable(val reference: Reference, var initialExpression: Expression? = null, val constant: Boolean = false, val context: ParserRuleContext) : Global { constructor(type: Type, name: String, initialExpression: Expression? = null, constant: Boolean = false, context: ParserRuleContext) : this(Reference(name, type), initialExpression, constant, context) val name: String get() = reference.name var type: Type get() = reference.type set(value) { reference.type = value } override fun toString(): String = "${if (constant) "let" else "var"} $name : $type${if (initialExpression != null) " = $initialExpression" else ""}" override fun hashCode(): Int = type.hashCode() + name.hashCode() + constant.hashCode() override fun equals(other: Any?): Boolean = other is Variable && other.name == name && other.type == type && other.constant == constant && other.hashCode() == hashCode() } /** * Classes (Clazz because Java contains a class named Class) are normal OOP classes, and can contain fields and methods. */ class Clazz(val name: String, val fields: List<Variable>, val methods: List<Function>, val constructor: Function?, val traits: List<Trait>, val context: ParserRuleContext) : Global, Type { override fun toString(): String = "$name(${fields.map { it.type }.joinToString()})" override fun hashCode(): Int = Objects.hash(name, fields, methods, constructor) override fun equals(other: Any?): Boolean = other is Clazz && other.hashCode() == hashCode() && other.name == name && other.fields == fields && other.methods == methods && other.constructor == constructor override fun isCopyable(): Boolean = traits.filter { it.name == "Copy" }.isNotEmpty() } open class Trait(val name: String, val functions: List<Function.Prototype> = listOf()) : Node, Type { override fun toString(): String = name override fun isCopyable(): Boolean = name == "Copy" // This seems ghetto } object CopyTrait : Trait("Copy", listOf()) val defaultTraits: List<Trait> = listOf(CopyTrait) /** * A Reference to a declaration. */ class Reference(val name: String, var type: Type = T_UNDEF) { override fun toString(): String = name override fun hashCode(): Int = Objects.hash(name, type) override fun equals(other: Any?): Boolean = name == other } /** * Stores the references and arguments for calling a Function. */ class FunctionCall(val functionReference: Reference, val arguments: List<Expression> = listOf()) : Node { override fun toString(): String = functionReference.name + "(" + arguments.map { it.toString() }.joinToString() + ")" override fun hashCode(): Int = Objects.hash(functionReference, arguments) override fun equals(other: Any?): Boolean = other is FunctionCall && other.functionReference == functionReference && other.arguments == arguments } /** * Stores the references and arguments for a calling a Method. */ class MethodCall(val variableReference: Reference, val methodReference: Reference, val arguments: List<Expression> = listOf()) : Node { override fun toString(): String = variableReference.name + "." + methodReference.name + "(" + arguments.map { it.toString() }.joinToString() + ")" override fun hashCode(): Int = Objects.hash(variableReference, methodReference, arguments) override fun equals(other: Any?): Boolean = other is MethodCall && other.variableReference == variableReference && other.methodReference == methodReference && other.arguments == arguments } // --------------------------------------------------------------------------------------------------------------------- // STATEMENTS // --------------------------------------------------------------------------------------------------------------------- /** * Statements are commands that Functions can run to do certain actions. These actions consist of function calls, * variable declarations, control flow, etc. */ abstract class Statement : Node { override fun equals(other: Any?): Boolean = other is Statement && other.hashCode() == hashCode() } /** * Blocks are Statements that contain Statements than can be run. */ open class Block(val statements: List<Statement>) : Statement() { override fun hashCode(): Int = Objects.hash(statements) override fun equals(other: Any?): Boolean = other is Block && other.statements == statements && other.hashCode() == hashCode() } /** * CheckedBlocks are Blocks with an expression to be evaluated before the Statements run. * * <pre> * (expr) { * statements; * } * </pre> * * @param expression Expression to test * @param statements Statements to be run */ open class CheckedBlock(var expression: Expression, statements: List<Statement>) : Block(statements) /** * If Statement * The statement list runs if the expression evaluates to true. * If the expression is false, control goes to elseStatement. This statement is an If Statement that has its own * expression to evaluate. There is no notion of an "Else Statement", they are If Statements with the expression set to * true. * * <pre> * if (eA) { * sA * } * else if (eB) { * sB * } * else if (eC) { * sC * } * else { * sD * } * </pre> * * This is represented in the tree as: * * <pre> * IfStatement * - eA * - sA * - IfStatement * - eB * - sB * - IfStatement * - eC * - sC * - IfStatement * - true * - sD * </pre> */ class IfStatement(expression: Expression, statements: List<Statement>, var elseStatement: IfStatement?, val context: ParserRuleContext) : CheckedBlock(expression, statements) /** * elseStatement returns an IfStatement with the expression set to a TrueExpression * @param statements Statements to run */ fun elseStatement(statements: List<Statement>, context: ParserRuleContext): IfStatement { return IfStatement(TrueExpression(context), statements, null, context) } /** * WhileStatements are Blocks that will run over and over as long as their expression is true. */ class WhileStatement(expression: Expression, statements: List<Statement>, val context: ParserRuleContext) : CheckedBlock(expression, statements) /** * VariableDeclarationStatements add a Variable to the local variable pool that other Statements can access. */ class VariableDeclarationStatement(val variable: Variable, val context: ParserRuleContext) : Statement() /** * */ class VariableReassignmentStatement(val reference: Reference, var expression: Expression, val context: ParserRuleContext) : Statement() { override fun toString(): String = "$reference = $expression (${reference.hashCode()}, ${expression.hashCode()})" override fun hashCode(): Int = Objects.hash(reference, expression) override fun equals(other: Any?): Boolean = other is VariableReassignmentStatement && other.reference == reference && other.expression == expression } /** * Statement wrapper for FunctionCalls */ class FunctionCallStatement(val functionCall: FunctionCall, val context: ParserRuleContext) : Statement() /** * Statement wrapper for MethodCalls */ class MethodCallStatement(val methodCall: MethodCall, val context: ParserRuleContext) : Statement() { override fun toString(): String = methodCall.toString() } /** * Set field of a Class */ class FieldSetterStatement(val variable: Expression, val fieldReference: Reference, val expression: Expression, val context: ParserRuleContext) : Statement() { override fun toString(): String = "$variable.$fieldReference = $expression" } // --------------------------------------------------------------------------------------------------------------------- // EXPRESSIONS // --------------------------------------------------------------------------------------------------------------------- /** * Expressions evaluate to a value. */ abstract class Expression(val child: List<Expression> = listOf()) : Node abstract class BooleanExpression(val value: Boolean, val context: ParserRuleContext) : Expression() /** * TrueExpressions are booleans that are only "true". */ class TrueExpression(context: ParserRuleContext) : BooleanExpression(true, context) { override fun toString(): String = "true" } /** * FalseExpressions are booleans that are only "false". */ class FalseExpression(context: ParserRuleContext) : BooleanExpression(false, context) { override fun toString(): String = "false" } /** * IntegerLiterals are an Expression wrapper for Ints. */ class IntegerLiteral(val value: Int, val context: ParserRuleContext) : Expression() { override fun toString(): String = value.toString() } class FloatLiteral(val value: Double, val type: FloatType, val context: ParserRuleContext) : Expression() { override fun toString(): String = value.toString() } /** * StringLiterals are an Expression wrapper for Strings. */ class StringLiteral(val value: String, val context: ParserRuleContext) : Expression() { override fun toString(): String = value } /** * Expression wrapper for References */ class ReferenceExpression(val reference: Reference, val context: ParserRuleContext) : Expression() { override fun toString(): String = reference.name override fun hashCode(): Int = reference.hashCode() override fun equals(other: Any?): Boolean = reference == other } /** * Expression wrapper for FunctionCalls */ class FunctionCallExpression(val functionCall: FunctionCall, val context: ParserRuleContext) : Expression(functionCall.arguments) { override fun toString(): String = functionCall.toString() } /** * Expression wrapper for MethodCalls */ class MethodCallExpression(val methodCall: MethodCall, val context: ParserRuleContext) : Expression(methodCall.arguments) { override fun toString(): String = methodCall.toString() } /** * Get field of a Class */ class FieldGetterExpression(val variable: Expression, val fieldReference: Reference, val context: ParserRuleContext) : Expression() { override fun toString(): String = "$variable.$fieldReference" } class ClazzInitializerExpression(val classReference: Reference, val arguments: List<Expression>, val context: ParserRuleContext) : Expression(arguments) { override fun toString(): String = "new ${classReference.name}(" + arguments.map { it.toString() }.joinToString() + ")" } /** * Operators are constructs that behave like Functions, but differ syntactically. */ enum class Operator(val string: String, val aType: Type = T_UNDEF, val bType: Type = T_UNDEF, val returnType: Type = T_UNDEF) { // Maths PLUS_INT("+", aType = T_INT32, bType = T_INT32, returnType = T_INT32), MINUS_INT("-", aType = T_INT32, bType = T_INT32, returnType = T_INT32), MULTIPLY_INT("*", aType = T_INT32, bType = T_INT32, returnType = T_INT32), DIVIDE_INT("/", aType = T_INT32, bType = T_INT32, returnType = T_INT32), PLUS_FLOAT("+.", aType = T_FLOAT32, bType = T_FLOAT32, returnType = T_FLOAT32), MINUS_FLOAT("-.", aType = T_FLOAT32, bType = T_FLOAT32, returnType = T_FLOAT32), MULTIPLY_FLOAT("*.", aType = T_FLOAT32, bType = T_FLOAT32, returnType = T_FLOAT32), DIVIDE_FLOAT("/.", aType = T_FLOAT32, bType = T_FLOAT32, returnType = T_FLOAT32), // Comparisons GREATER_THAN(">", returnType = T_BOOL), LESS_THAN("<", returnType = T_BOOL), EQUALS("==", returnType = T_BOOL), GREATER_THAN_EQUAL(">=", returnType = T_BOOL), LESS_THAN_EQUAL("<=", returnType = T_BOOL), NOT_EQUAL("!=", returnType = T_BOOL), AND("&&", returnType = T_BOOL), OR("||", returnType = T_BOOL); override fun toString(): String = string } /** * Get an Operator through its String representation */ fun getOperator(s: String): Operator? { try { return Operator.values().filter { it.string == s }[0] } catch (e: IndexOutOfBoundsException) { return null } } /** * BinaryOperators are Expressions that contain two sub-Expressions and an Operator that operates on them. */ class BinaryOperator(var expressionA: Expression, val operator: Operator, var expressionB: Expression, val context: ParserRuleContext) : Expression(listOf(expressionA, expressionB)) { override fun toString(): String = "($expressionA $operator $expressionB)" override fun hashCode(): Int = Objects.hash(expressionA, operator, expressionB) override fun equals(other: Any?): Boolean { return other is BinaryOperator && other.expressionA == expressionA && other.operator == operator && other.expressionB == expressionB } }
mpl-2.0
b331c4455420162b89fa606ef4e06b5b
36.966102
183
0.651736
4.373102
false
false
false
false
GunoH/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinNonSourceRootIndexFilter.kt
2
1652
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.stubindex import com.intellij.find.ngrams.TrigramIndex import com.intellij.openapi.application.runReadAction import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.FilenameIndex import com.intellij.util.indexing.GlobalIndexFilter import com.intellij.util.indexing.IndexId import org.jetbrains.kotlin.idea.util.isKotlinFileType class KotlinNonSourceRootIndexFilter: GlobalIndexFilter { private val enabled = !System.getProperty("kotlin.index.non.source.roots", "false").toBoolean() override fun isExcludedFromIndex(virtualFile: VirtualFile, indexId: IndexId<*, *>): Boolean = false override fun isExcludedFromIndex(virtualFile: VirtualFile, indexId: IndexId<*, *>, project: Project?): Boolean = project != null && !virtualFile.isDirectory && affectsIndex(indexId) && virtualFile.isKotlinFileType() && runReadAction { ProjectRootManager.getInstance(project).fileIndex.getOrderEntriesForFile(virtualFile).isEmpty() && !ProjectFileIndex.getInstance(project).isInLibrary(virtualFile) } override fun getVersion(): Int = 0 override fun affectsIndex(indexId: IndexId<*, *>): Boolean = enabled && (indexId !== TrigramIndex.INDEX_ID && indexId !== FilenameIndex.NAME) }
apache-2.0
50f105324c95f24990b68e13bcc3a327
47.617647
120
0.728814
4.902077
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/wizard/AbstractNewProjectWizardMultiStepBase.kt
2
2893
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.wizard import com.intellij.openapi.observable.properties.AtomicProperty import com.intellij.openapi.observable.util.bindStorage import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.NlsContexts import com.intellij.ui.dsl.builder.* import com.intellij.util.ui.JBUI abstract class AbstractNewProjectWizardMultiStepBase( parent: NewProjectWizardStep ) : AbstractNewProjectWizardStep(parent) { protected abstract val label: @NlsContexts.Label String private val stepsProperty = AtomicProperty<Map<String, NewProjectWizardStep>>(emptyMap()) var steps: Map<String, NewProjectWizardStep> by stepsProperty val stepProperty = propertyGraph.property("") .bindStorage("${javaClass.name}.selectedStep") var step by stepProperty private val stepsPanels = HashMap<String, DialogPanel>() protected open fun initSteps() = emptyMap<String, NewProjectWizardStep>() protected open fun setupSwitcherUi(builder: Panel) { builder.row(label) { createAndSetupSwitcher(this@row) }.bottomGap(BottomGap.SMALL) } protected open fun createAndSetupSwitcher(builder: Row): SegmentedButton<String> { return builder.segmentedButton(steps.keys) { it } .bind(stepProperty) .gap(RightGap.SMALL) .apply { stepsProperty.afterChange { items(steps.keys) } } } override fun setupUI(builder: Panel) { steps = initSteps() setupSwitcherUi(builder) with(builder) { row { val placeholder = placeholder() .align(AlignX.FILL) placeholder.component = getOrCreateStepPanel() stepProperty.afterChange { placeholder.component = getOrCreateStepPanel() } } } } private fun getOrCreateStepPanel(): DialogPanel? { if (step !in stepsPanels) { val stepUi = steps[step] ?: return null val panel = panel { stepUi.setupUI(this) } panel.setMinimumWidthForAllRowLabels(JBUI.scale(90)) stepsPanels[step] = panel } return stepsPanels[step] } override fun setupProject(project: Project) { steps[step]?.setupProject(project) } init { stepsProperty.afterChange { keywords.add(this, steps.keys) } stepsProperty.afterChange { stepsPanels.clear() } var oldSteps: Set<String> = emptySet() stepsProperty.afterChange { val addedSteps = steps.keys - oldSteps step = when { oldSteps.isNotEmpty() && addedSteps.isNotEmpty() -> addedSteps.first() step.isEmpty() -> steps.keys.first() step !in steps -> steps.keys.first() else -> step // Update all dependent things } oldSteps = steps.keys } } }
apache-2.0
765336b935bb24226fef372f9b30ed52
29.145833
158
0.700657
4.30506
false
false
false
false
jwren/intellij-community
python/python-features-trainer/src/com/jetbrains/python/ift/lesson/completion/PythonTabCompletionLesson.kt
5
3096
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.ift.lesson.completion import com.jetbrains.python.ift.PythonLessonsBundle import training.dsl.* import training.dsl.LessonUtil.checkExpectedStateOfEditor import training.learn.course.KLesson import training.util.isToStringContains import javax.swing.JList class PythonTabCompletionLesson : KLesson("Tab completion", PythonLessonsBundle.message("python.tab.completion.lesson.name")) { private val template = parseLessonSample(""" class Calculator: def __init__(self): self.current = 0 self.total = 0 def add(self, amount): self.current += amount def get_current(self): return self.<caret> """.trimIndent()) private val sample = createFromTemplate(template, "current") private val isTotalItem = { item: Any -> item.isToStringContains("total") } override val lessonContent: LessonContext.() -> Unit get() { return { prepareSample(sample) task("CodeCompletion") { text(PythonLessonsBundle.message("python.tab.completion.start.completion", code("current"), code("total"), action(it))) triggerAndBorderHighlight().listItem { ui -> isTotalItem(ui) } proposeRestoreMe() test { actions(it) } } task { text(PythonLessonsBundle.message("python.tab.completion.select.item", code("total"))) restoreState(delayMillis = defaultRestoreDelay) { (previous.ui as? JList<*>)?.let { ui -> !ui.isShowing || LessonUtil.findItem(ui, isTotalItem) == null } ?: true } stateCheck { selectNeededItem() ?: false } test { ideFrame { jListContains("total").item("total").click() } } } task { val result = LessonUtil.insertIntoSample(template, "total") text(PythonLessonsBundle.message("python.tab.completion.use.tab.completion", action("EditorEnter"), code("total"), code("current"), action("EditorTab"))) trigger("EditorChooseLookupItemReplace") { editor.document.text == result } restoreAfterStateBecomeFalse { selectNeededItem()?.not() ?: true } test { invokeActionViaShortcut("TAB") } } } } private fun TaskRuntimeContext.selectNeededItem(): Boolean? { return (previous.ui as? JList<*>)?.let { ui -> if (!ui.isShowing) return false val selectedIndex = ui.selectedIndex selectedIndex != -1 && isTotalItem(ui.model.getElementAt(selectedIndex)) } } private fun TaskContext.proposeRestoreMe() { proposeRestore { checkExpectedStateOfEditor(sample) } } override val suitableTips = listOf("TabInLookups") }
apache-2.0
c5aa147cf084a38ce3765a2a74afb59e
33.797753
140
0.602713
5.058824
false
false
false
false
JetBrains/kotlin-native
tools/benchmarksAnalyzer/src/main/kotlin-js/org/jetbrains/analyzer/Utils.kt
2
1295
/* * Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.analyzer import org.w3c.xhr.* import kotlin.browser.* import kotlin.js.* actual fun readFile(fileName: String): String { error("Reading from local file for JS isn't supported") } actual fun Double.format(decimalNumber: Int): String = this.asDynamic().toFixed(decimalNumber) actual fun writeToFile(fileName: String, text: String) { if (fileName != "html") error("Writing to local file for JS isn't supported") val bodyPart = text.substringAfter("<body>").substringBefore("</body>") document.body?.innerHTML = bodyPart } actual fun assert(value: Boolean, lazyMessage: () -> Any) { if (!value) error(lazyMessage) } actual fun sendGetRequest(url: String, user: String?, password: String?, followLocation: Boolean) : String { val proxyServerAddress = "https://perf-proxy.labs.jb.gg/" val newUrl = proxyServerAddress + url val request = XMLHttpRequest() request.open("GET", newUrl, false, user, password) request.send() if (request.status == 200.toShort()) { return request.responseText } error("Request to $url has status ${request.status}") }
apache-2.0
b46adc4adcbc48a0eae37a8237815c35
30.609756
108
0.694981
3.912387
false
false
false
false
GunoH/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/inference/driver/closure/ClosureInferenceUtil.kt
7
15756
// 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.groovy.intentions.style.inference.driver.closure import com.intellij.codeInsight.AnnotationUtil import com.intellij.lang.jvm.JvmParameter import com.intellij.lang.jvm.annotation.JvmAnnotationConstantValue import com.intellij.psi.* import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula import com.intellij.psi.util.parentOfType import org.jetbrains.plugins.groovy.intentions.closure.isClosureCall import org.jetbrains.plugins.groovy.intentions.style.inference.CollectingGroovyInferenceSession import org.jetbrains.plugins.groovy.intentions.style.inference.driver.BoundConstraint.ContainMarker.LOWER import org.jetbrains.plugins.groovy.intentions.style.inference.driver.RecursiveMethodAnalyzer import org.jetbrains.plugins.groovy.intentions.style.inference.driver.TypeUsageInformationBuilder import org.jetbrains.plugins.groovy.intentions.style.inference.driver.closure.ClosureParametersStorageBuilder.Companion.isReferenceTo import org.jetbrains.plugins.groovy.intentions.style.inference.properResolve import org.jetbrains.plugins.groovy.intentions.style.inference.resolve import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArrayInitializer import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction import org.jetbrains.plugins.groovy.lang.psi.impl.GrAnnotationUtil.inferClassAttribute import org.jetbrains.plugins.groovy.lang.psi.impl.stringValue import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.ClosureSyntheticParameter import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter.Position.ASSIGNMENT import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.SignatureHintProcessor import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.* import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.ExpectedType import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.ExpressionConstraint import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.TypeConstraint import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.type fun extractConstraintsFromClosureInvocations(closureParameter: ParameterizedClosure, instructions: List<ReadWriteVariableInstruction>): List<ConstraintFormula> { val collector = mutableListOf<ConstraintFormula>() for (call in instructions) { val nearestCall = call.element?.parentOfType<GrCall>()?.takeIf { it.isClosureCall(closureParameter.parameter) } ?: continue for (index in nearestCall.expressionArguments.indices) { val argumentExpression = nearestCall.expressionArguments.getOrNull(index) ?: continue val innerParameterType = closureParameter.typeParameters.getOrNull(index)?.type() val expectedType = if (innerParameterType == null) null else ExpectedType(innerParameterType, ASSIGNMENT) collector.add(ExpressionConstraint(expectedType, argumentExpression)) } } return collector } inline fun GrMethod.forEachParameterUsage(action: (GrParameter, List<ReadWriteVariableInstruction>) -> Unit) { val usages = block ?.controlFlow ?.filterIsInstance<ReadWriteVariableInstruction>() ?.groupBy { it.element?.reference?.resolve() as? GrParameter } ?: return parameters .filter { usages.containsKey(it) } .forEach { val instructions = usages.getValue(it) action(it, instructions) } } fun analyzeClosureUsages(closureParameter: ParameterizedClosure, usages: List<ReadWriteVariableInstruction>, builder: TypeUsageInformationBuilder) { val parameter = closureParameter.parameter val delegatesToCombiner = closureParameter.delegatesToCombiner for (usage in usages) { val element = usage.element ?: continue val directMethodResult = element.parentOfType<GrAssignmentExpression>()?.properResolve() as? GroovyMethodResult if (directMethodResult != null) { delegatesToCombiner.acceptResolveResult(directMethodResult) } val nearestCall = element.parentOfType<GrCall>() ?: continue val resolveResult = nearestCall.properResolve() as? GroovyMethodResult ?: return if (nearestCall.resolveMethod()?.containingClass?.qualifiedName == GROOVY_LANG_CLOSURE) { delegatesToCombiner.acceptResolveResult(resolveResult) collectClosureMethodInvocationDependencies(closureParameter, builder, resolveResult, nearestCall) } else { val mapping = resolveResult.candidate?.argumentMapping ?: continue val requiredArgument = mapping.arguments.find { it.isReferenceTo(parameter) } ?: continue val innerParameter = mapping.targetParameter(requiredArgument)?.psi ?: continue val signature = extractSignature(innerParameter, resolveResult, nearestCall) collectClosureParamsDependencies(innerParameter, closureParameter, builder, signature) processDelegatesToAnnotation(innerParameter, resolveResult, closureParameter.delegatesToCombiner) } } } fun collectClosureMethodInvocationDependencies(parameterizedClosure: ParameterizedClosure, builder: TypeUsageInformationBuilder, resolveResult: GroovyMethodResult, nearestCall: GrCall) { if (nearestCall.isClosureCall(parameterizedClosure.parameter)) { val arguments = resolveResult.candidate?.argumentMapping?.arguments ?: return val expectedTypes = parameterizedClosure.types.zip(arguments) val method = parameterizedClosure.parameter.parentOfType<GrMethod>() ?: return for ((expectedType, argument) in expectedTypes) { val argumentType = argument.type ?: continue builder.addConstraint(TypeConstraint(expectedType, argumentType, method)) RecursiveMethodAnalyzer.induceDeepConstraints(expectedType, argumentType, builder, method, LOWER) } } } fun extractSignature(innerParameter: PsiParameter, resolveResult: GroovyMethodResult, nearestCall: GrCall): Array<PsiType>? { val closureParamsAnnotation = innerParameter.annotations.find { it.qualifiedName == GROOVY_TRANSFORM_STC_CLOSURE_PARAMS } ?: return null val valueAttribute = inferClassAttribute(closureParamsAnnotation, "value")?.qualifiedName ?: return null val hintProcessor = SignatureHintProcessor.getHintProcessor(valueAttribute) ?: return null val optionsAttribute = closureParamsAnnotation.findAttributeValue("options") val arrayOptionsAttribute = AnnotationUtil.arrayAttributeValues(optionsAttribute) val options = arrayOptionsAttribute.mapNotNull { (it as? PsiLiteral)?.stringValue() }.toTypedArray() val invokedMethod = resolveResult.candidate?.method ?: return null val collectingSubstitutor = CollectingGroovyInferenceSession.getContextSubstitutor(resolveResult, nearestCall) return hintProcessor.inferExpectedSignatures(invokedMethod, collectingSubstitutor, options).singleOrNull() } fun collectClosureParamsDependencies(innerParameter: PsiParameter, closureParameter: ParameterizedClosure, builder: TypeUsageInformationBuilder, signature: Array<PsiType>?) { signature ?: return for ((inferredType, typeParameter) in signature.zip(closureParameter.typeParameters)) { builder.addConstraint(TypeConstraint(typeParameter.type(), inferredType, innerParameter)) builder.generateRequiredTypes(typeParameter, inferredType, LOWER) } } fun processDelegatesToAnnotation(innerParameter: PsiParameter, resolveResult: GroovyMethodResult, combiner: DelegatesToCombiner) { val annotation = innerParameter.annotations.find { it.qualifiedName == GROOVY_LANG_DELEGATES_TO } ?: return trySetStrategyAttribute(annotation, combiner) if (!trySetValueAttribute(annotation, combiner)) { if (!trySetTypeAttribute(annotation, combiner, resolveResult)) { trySetParameterDelegate(annotation, combiner, resolveResult) } } } private fun trySetValueAttribute(annotation: PsiAnnotation, combiner: DelegatesToCombiner): Boolean { val valueAttribute = annotation.findDeclaredAttributeValue("value")?.reference?.resolve() as? PsiClass if (valueAttribute != null && valueAttribute.qualifiedName != GROOVY_LANG_DELEGATES_TO_TARGET) { combiner.setDelegate(valueAttribute) return true } else { return false } } private fun trySetTypeAttribute(annotation: PsiAnnotation, combiner: DelegatesToCombiner, resolveResult: GroovyMethodResult): Boolean { val typeAttribute = annotation.findDeclaredAttributeValue("type")?.stringValue() if (typeAttribute != null) { val createdType = createTypeSignature(typeAttribute, resolveResult.substitutor, annotation) if (createdType != null) { combiner.setTypeDelegate(createdType) } return true } return false } private fun trySetStrategyAttribute(annotation: PsiAnnotation, combiner: DelegatesToCombiner) { val strategyAttribute = annotation.findDeclaredAttributeValue("strategy")?.run(::extractIntRepresentation) if (strategyAttribute != null) { combiner.setStrategy(strategyAttribute) } } private fun trySetParameterDelegate(annotation: PsiAnnotation, combiner: DelegatesToCombiner, resolveResult: GroovyMethodResult) { val mapping = resolveResult.candidate?.argumentMapping ?: return val methodParameters = resolveResult.candidate?.method?.parameters?.takeIf { it.size > 1 }?.asList() ?: return val targetParameter = findTargetParameter(annotation, methodParameters) val argument = mapping.arguments.find { mapping.targetParameter(it)?.psi == targetParameter } ?: return val argumentExpression = (argument as? ExpressionArgument)?.expression if (argumentExpression != null) { combiner.setDelegate(argumentExpression) } else { val argumentType = argument.type.resolve() ?: return combiner.setDelegate(argumentType) } } private fun findTargetParameter(annotation: PsiAnnotation, methodParameters: Iterable<JvmParameter>): JvmParameter? { val delegatingParameters = methodParameters.mapNotNull { param -> val delegatesToAnnotation = param.annotations.find { it.qualifiedName == GROOVY_LANG_DELEGATES_TO_TARGET } delegatesToAnnotation?.let { param to it } } val targetLiteral = annotation.findDeclaredAttributeValue("target") if (targetLiteral != null) { return delegatingParameters.find { (_, anno) -> if (anno is GrAnnotation) { anno.findAttributeValue("value")?.stringValue() == targetLiteral.stringValue() } else { val value = (anno.findAttribute("value")?.attributeValue as? JvmAnnotationConstantValue) value?.constantValue as? String == targetLiteral.stringValue() } }?.first } else { return delegatingParameters.firstOrNull()?.first } } internal fun createMethodFromClosureBlock(body: GrClosableBlock, param: ParameterizedClosure, typeParameterList: PsiTypeParameterList): GrMethod { val enrichedBodyParameters = if (param.types.size == 1 && body.parameters.isEmpty()) listOf("it") else body.parameters.map { it.name } val parameters = param.types .zip(enrichedBodyParameters) .joinToString { (type, name) -> type.canonicalText + " " + name } val statements = body.statements.joinToString("\n") { it.text } return GroovyPsiElementFactory .getInstance(typeParameterList.project) .createMethodFromText(""" def ${typeParameterList.text} void unique_named_method($parameters) { $statements } """.trimIndent(), typeParameterList) } private fun extractIntRepresentation(attribute: PsiAnnotationMemberValue): String? { return when (attribute) { is PsiLiteralValue -> (attribute.value as? Int).toString() is GrExpression -> attribute.text else -> null } } fun createTypeSignature(signatureRepresentation: String, substitutor: PsiSubstitutor, context: PsiElement): PsiType? { val newType = JavaPsiFacade.getElementFactory(context.project).createTypeFromText("UnknownType<$signatureRepresentation>", context) return (newType as PsiClassType).parameters.map { substitutor.substitute(it) }.singleOrNull() } fun availableParameterNumber(annotation: PsiAnnotation): Int { val value = (annotation.parameterList.attributes.find { it.name == "value" }?.value?.reference?.resolve() as? PsiClass) ?: return 0 val options = lazy { annotation.parameterList.attributes.find { it.name == "options" }?.value as? GrAnnotationArrayInitializer } return when (value.qualifiedName) { GROOVY_TRANSFORM_STC_SIMPLE_TYPE -> parseSimpleType(options.value ?: return 0) GROOVY_TRANSFORM_STC_FROM_STRING -> parseFromString(options.value ?: return 0) in ClosureParamsCombiner.availableHints -> 1 GROOVY_TRANSFORM_STC_FROM_ABSTRACT_TYPE_METHODS -> /*todo*/ 0 GROOVY_TRANSFORM_STC_MAP_ENTRY_OR_KEY_VALUE -> /*todo*/ 2 else -> 0 } } private fun parseFromString(signatures: GrAnnotationArrayInitializer): Int { val signature = signatures.initializers.firstOrNull()?.text ?: return 0 return signature.count { it == ',' } + 1 } private fun parseSimpleType(parameterTypes: GrAnnotationArrayInitializer): Int { return parameterTypes.initializers.size } data class AnnotatingResult(val parameter: GrParameter, val annotationText: String) fun getBlock(parameter: GrParameter): GrClosableBlock? = when (parameter) { is ClosureSyntheticParameter -> parameter.closure else -> parameter.parentOfType<GrClosableBlock>()?.takeIf { it.parameterList.getParameterNumber(parameter) != -1 } } internal infix fun PsiSubstitutor.compose(right: PsiSubstitutor): PsiSubstitutor { val typeParameters = substitutionMap.keys var newSubstitutor = PsiSubstitutor.EMPTY typeParameters.forEach { typeParameter -> newSubstitutor = newSubstitutor.put(typeParameter, right.substitute(this.substitute(typeParameter))) } return newSubstitutor } inline fun PsiType.anyComponent(crossinline predicate: (PsiType) -> Boolean): Boolean { var mark = false accept(object : PsiTypeVisitor<Unit>() { override fun visitClassType(classType: PsiClassType) { if (predicate(classType)) { mark = true } classType.parameters.forEach { it.accept(this) } } override fun visitWildcardType(wildcardType: PsiWildcardType) { wildcardType.bound?.accept(this) } override fun visitIntersectionType(intersectionType: PsiIntersectionType) { intersectionType.conjuncts?.forEach { it.accept(this) } } override fun visitArrayType(arrayType: PsiArrayType) { arrayType.componentType.accept(this) } }) return mark }
apache-2.0
2eb19f2849bec20bc3ab7c3ae5ef739c
49.341853
138
0.764026
4.943834
false
false
false
false
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/actions/ChangePreviewLayoutAction.kt
3
1429
package org.intellij.plugins.markdown.ui.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.fileEditor.TextEditorWithPreview import com.intellij.openapi.project.DumbAware internal abstract class ChangePreviewLayoutAction( private val layout: TextEditorWithPreview.Layout ): ToggleAction(layout.getName(), layout.getName(), layout.getIcon(null)), DumbAware { override fun isSelected(event: AnActionEvent): Boolean { val editor = MarkdownActionUtil.findSplitEditor(event) return editor?.layout == layout } override fun setSelected(event: AnActionEvent, state: Boolean) { val editor = MarkdownActionUtil.findSplitEditor(event) ?: return if (state) { editor.layout = layout } else if (layout == TextEditorWithPreview.Layout.SHOW_EDITOR_AND_PREVIEW) { editor.isVerticalSplit = !editor.isVerticalSplit } } override fun update(event: AnActionEvent) { super.update(event) val editor = MarkdownActionUtil.findSplitEditor(event) ?: return event.presentation.icon = layout.getIcon(editor) } class EditorOnly: ChangePreviewLayoutAction(TextEditorWithPreview.Layout.SHOW_EDITOR) class EditorAndPreview: ChangePreviewLayoutAction(TextEditorWithPreview.Layout.SHOW_EDITOR_AND_PREVIEW) class PreviewOnly: ChangePreviewLayoutAction(TextEditorWithPreview.Layout.SHOW_PREVIEW) }
apache-2.0
b67dd8af2e1e4935ef34b8748cfe7cdd
38.694444
105
0.789363
4.522152
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinULiteralExpression.kt
2
1830
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.psi.KtConstantExpression import org.jetbrains.kotlin.psi.KtEscapeStringTemplateEntry import org.jetbrains.uast.UElement import org.jetbrains.uast.ULiteralExpression import org.jetbrains.uast.kotlin.internal.KotlinFakeUElement import org.jetbrains.uast.wrapULiteral class KotlinULiteralExpression( override val sourcePsi: KtConstantExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), ULiteralExpression, KotlinUElementWithType, KotlinEvaluatableUElement, KotlinFakeUElement { override val isNull: Boolean get() = sourcePsi.unwrapBlockOrParenthesis().node?.elementType == KtNodeTypes.NULL override val value by lz { evaluate() } override fun unwrapToSourcePsi(): List<PsiElement> = listOfNotNull(wrapULiteral(this).sourcePsi) } class KotlinStringULiteralExpression( override val sourcePsi: PsiElement, givenParent: UElement?, val text: String ) : KotlinAbstractUExpression(givenParent), ULiteralExpression, KotlinUElementWithType, KotlinFakeUElement { constructor(psi: PsiElement, uastParent: UElement?) : this(psi, uastParent, if (psi is KtEscapeStringTemplateEntry) psi.unescapedValue else psi.text) override val value: String get() = text override fun evaluate() = value override fun getExpressionType(): PsiType? = PsiType.getJavaLangString(sourcePsi.manager, sourcePsi.resolveScope) override fun unwrapToSourcePsi(): List<PsiElement> = listOfNotNull(wrapULiteral(this).sourcePsi) }
apache-2.0
07822bc4484c382527aca5524dfb0192
41.55814
158
0.791803
4.88
false
false
false
false
Jire/Charlatano
src/main/kotlin/com/charlatano/game/Aim.kt
1
1823
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.game import com.charlatano.game.CSGO.csgoEXE import com.charlatano.game.entity.Player import com.charlatano.game.entity.position import com.charlatano.game.entity.punch import com.charlatano.game.netvars.NetVarOffsets.vecViewOffset import com.charlatano.utils.Angle import com.charlatano.utils.Vector import com.charlatano.utils.normalize import org.jire.kna.float import java.lang.Math.toDegrees import kotlin.math.atan import kotlin.math.sqrt private val angles: ThreadLocal<Angle> = ThreadLocal.withInitial { Vector() } fun calculateAngle(player: Player, dst: Vector): Angle = angles.get().apply { val myPunch = player.punch() val myPosition = player.position() val dX = myPosition.x - dst.x val dY = myPosition.y - dst.y val dZ = myPosition.z + csgoEXE.float(player + vecViewOffset) - dst.z val hyp = sqrt((dX * dX) + (dY * dY)) x = toDegrees(atan(dZ / hyp)) - myPunch.x * 2.0 y = toDegrees(atan(dY / dX)) - myPunch.y * 2.0 z = 0.0 if (dX >= 0.0) y += 180 normalize() }
agpl-3.0
18919b6467915a13f7a1e61e7c1ae7a3
34.076923
78
0.738892
3.472381
false
false
false
false
hellocreep/refactoring
kotlinjs/src/main/ReplaceTempWithChain/Person.kt
1
572
class Person { private var name: String private var sex: String private var age: Int init { this.name = "" this.sex = "" this.age = 0 } fun setName(name: String): Person { this.name = name return this } fun setSex(sex: String): Person { this.sex = sex return this } fun setAge(age: Int): Person { this.age = age return this } override fun toString(): String { return "name: " + this.name + " sex: " + this.sex + " age: " + this.age } }
mit
4f4ff34287f77a38a0aa7c1302fa12e1
18.1
79
0.505245
3.891156
false
false
false
false
intrigus/jtransc
jtransc-core/src/com/jtransc/backend/asm2/TirToStm.kt
1
5047
package com.jtransc.backend.asm2 import com.jtransc.ast.* import com.jtransc.ds.cast import com.jtransc.org.objectweb.asm.Label class TirToStm(val methodType: AstType.METHOD, val blockContext: BlockContext, val types: AstTypes) { val locals = hashMapOf<Local, AstLocal>() val stms = arrayListOf<AstStm>() var id = 0 fun AstType.convertType(): AstType { val type = this return when (type) { is AstType.COMMON -> { if (type.single != null) { type.single!!.convertType() } else { if (type.elements.any { it is AstType.Primitive }) { getCommonTypePrim(type.elements.cast<AstType.Primitive>()) } else { AstType.OBJECT } } } else -> type } } val Local.ast: AstLocal get() { val canonicalLocal = Local(this.type.convertType(), this.index) if (canonicalLocal.type is AstType.UNKNOWN) { println("ASSERT UNKNOWN!: $canonicalLocal") } return locals.getOrPut(canonicalLocal) { AstLocal(id++, canonicalLocal.type) } } val Label.ast: AstLabel get() = blockContext.label(this) val Local.expr: AstExpr.LOCAL get() = AstExpr.LOCAL(this.ast) val Operand.expr: AstExpr get() = when (this) { is Constant -> this.v.lit is Param -> AstExpr.PARAM(AstArgument(this.index, this.type.convertType())) is Local -> AstExpr.LOCAL(this.ast) is This -> AstExpr.THIS(this.clazz.name) //is CatchException -> AstExpr.CAUGHT_EXCEPTION(this.type) is CatchException -> AstExpr.CAUGHT_EXCEPTION(AstType.OBJECT) else -> TODO("$this") } fun convert(tirs: List<TIR>) { for (tir in tirs) { when (tir) { is TIR.NOP -> Unit is TIR.MOV -> stms += tir.dst.expr.setTo(tir.src.expr.castTo(tir.dst.type)) is TIR.INSTANCEOF -> stms += tir.dst.expr.setTo(AstExpr.INSTANCE_OF(tir.src.expr, tir.type as AstType.Reference)) is TIR.CONV -> stms += tir.dst.expr.setTo(tir.src.expr.castTo(tir.dst.type)) is TIR.ARRAYLENGTH -> stms += tir.dst.expr.setTo(AstExpr.ARRAY_LENGTH(tir.obj.expr)) is TIR.NEW -> stms += tir.dst.expr.setTo(AstExpr.NEW(tir.type)) is TIR.NEWARRAY -> stms += tir.dst.expr.setTo(AstExpr.NEW_ARRAY(tir.arrayType, tir.lens.map { it.expr })) is TIR.UNOP -> stms += tir.dst.expr.setTo(AstExpr.UNOP(tir.op, tir.r.expr)) is TIR.BINOP -> { val leftType = when (tir.op) { AstBinop.LCMP, AstBinop.EQ, AstBinop.NE, AstBinop.GE, AstBinop.LE, AstBinop.GT, AstBinop.LT -> tir.l.type AstBinop.CMPG, AstBinop.CMPL -> AstType.DOUBLE else -> tir.dst.type } val rightType = when (tir.op) { AstBinop.SHL, AstBinop.SHR, AstBinop.USHR -> AstType.INT else -> leftType } stms += tir.dst.expr.setTo(AstExpr.BINOP(tir.dst.type, tir.l.expr.castTo(leftType), tir.op, tir.r.expr.castTo(rightType))) } is TIR.ARRAY_STORE -> { stms += AstStm.SET_ARRAY(tir.array.expr, tir.index.expr, tir.value.expr.castTo(tir.elementType.convertType())) } is TIR.ARRAY_LOAD -> { stms += tir.dst.expr.setTo(AstExpr.ARRAY_ACCESS(tir.array.expr, tir.index.expr)) } is TIR.GETSTATIC -> stms += tir.dst.expr.setTo(AstExpr.FIELD_STATIC_ACCESS(tir.field)) is TIR.GETFIELD -> stms += tir.dst.expr.setTo(AstExpr.FIELD_INSTANCE_ACCESS(tir.field, tir.obj.expr.castTo(tir.field.containingTypeRef))) is TIR.PUTSTATIC -> stms += AstStm.SET_FIELD_STATIC(tir.field, tir.src.expr.castTo(tir.field.type)) is TIR.PUTFIELD -> stms += AstStm.SET_FIELD_INSTANCE(tir.field, tir.obj.expr.castTo(tir.field.containingTypeRef), tir.src.expr.castTo(tir.field.type)) is TIR.INVOKE_COMMON -> { val method = tir.method val args = tir.args.zip(method.type.args).map { it.first.expr.castTo(it.second.type) } val expr = if (tir.obj != null) { AstExpr.CALL_INSTANCE(tir.obj!!.expr.castTo(tir.method.containingClassType), tir.method, args, isSpecial = tir.isSpecial) } else { AstExpr.CALL_STATIC(tir.method, args, isSpecial = tir.isSpecial) } if (tir is TIR.INVOKE) { stms += tir.dst.expr.setTo(expr) } else { stms += AstStm.STM_EXPR(expr) } } is TIR.MONITOR -> stms += if (tir.enter) AstStm.MONITOR_ENTER(tir.obj.expr) else AstStm.MONITOR_EXIT(tir.obj.expr) // control flow: is TIR.LABEL -> stms += AstStm.STM_LABEL(tir.label.ast) is TIR.JUMP -> stms += AstStm.GOTO(tir.label.ast) is TIR.JUMP_IF -> { val t1 = tir.l.expr.type stms += AstStm.IF_GOTO(tir.label.ast, AstExpr.BINOP(AstType.BOOL, tir.l.expr, tir.op, tir.r.expr.castTo(t1))) } is TIR.SWITCH_GOTO -> stms += AstStm.SWITCH_GOTO( tir.subject.expr, tir.deflt.ast, tir.cases.entries.groupBy { it.value }.map { it.value.map { it.key } to it.key.ast } ) is TIR.RET -> { //if (methodType.ret == AstType.REF("j.ClassInfo")) { // println("go!") //} stms += if (tir.v != null) AstStm.RETURN(tir.v.expr.castTo(methodType.ret)) else AstStm.RETURN_VOID() } is TIR.THROW -> stms += AstStm.THROW(tir.ex.expr) //is TIR.PHI_PLACEHOLDER -> stms += AstStm.NOP("PHI_PLACEHOLDER") else -> TODO("$tir") } } } }
apache-2.0
0c7664a6817af8ae2531a54c425e1173
40.03252
154
0.658015
2.783784
false
false
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/data/entity/Property.kt
1
493
package com.ivanovsky.passnotes.data.entity data class Property( val type: PropertyType? = null, val name: String? = null, val value: String? = null, val isProtected: Boolean = false ) { val isDefault = (type != null && PropertyType.DEFAULT_TYPES.contains(type)) companion object { const val PROPERTY_NAME_TEMPLATE = "_etm_template" const val PROPERTY_NAME_TEMPLATE_UID = "_etm_template_uuid" const val PROPERTY_VALUE_TEMPLATE = "1" } }
gpl-2.0
8a7e05798047dd91deb611a703bcb35f
25
79
0.659229
3.975806
false
false
false
false
yiyocx/YitLab
app/src/main/kotlin/yiyo/gitlabandroid/ui/adapters/ViewPagerAdapter.kt
2
793
package yiyo.gitlabandroid.ui.adapters import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import java.util.* /** * Created by yiyo on 25/08/15. */ public class ViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager) { val mFragmentList = ArrayList<Fragment>() val mFragmentTitleList = ArrayList<String>() override fun getItem(position: Int): Fragment = mFragmentList.get(position) override fun getCount(): Int = mFragmentList.size fun addFragment(fragment: Fragment, title: String) { mFragmentList.add(fragment) mFragmentTitleList.add(title) } override fun getPageTitle(position: Int): CharSequence = mFragmentTitleList.get(position) }
gpl-2.0
8c17e756ba8d6e6946a64aaaa1337a43
29.5
93
0.754098
4.263441
false
false
false
false
seventhroot/elysium
bukkit/rpk-payments-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/command/payment/PaymentCreateCommand.kt
1
4486
/* * Copyright 2016 Ross Binden * * 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.rpkit.payments.bukkit.command.payment import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.economy.bukkit.currency.RPKCurrencyProvider import com.rpkit.payments.bukkit.RPKPaymentsBukkit import com.rpkit.payments.bukkit.group.RPKPaymentGroupImpl import com.rpkit.payments.bukkit.group.RPKPaymentGroupProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player /** * Payment create command. * Creates a payment group. */ class PaymentCreateCommand(private val plugin: RPKPaymentsBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (sender.hasPermission("rpkit.payments.command.payment.create")) { if (args.isNotEmpty()) { val paymentGroupProvider = plugin.core.serviceManager.getServiceProvider(RPKPaymentGroupProvider::class) val currencyProvider = plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class) val currencyName = plugin.config.getString("payment-groups.defaults.currency") val currency = if (currencyName == null) currencyProvider.defaultCurrency else currencyProvider.getCurrency(currencyName) val name = args.joinToString(" ") if (paymentGroupProvider.getPaymentGroup(name) == null) { if (sender is Player) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (minecraftProfile != null) { val character = characterProvider.getActiveCharacter(minecraftProfile) if (character != null) { val paymentGroup = RPKPaymentGroupImpl( plugin, name = name, amount = plugin.config.getInt("payment-groups.defaults.amount"), currency = currency, interval = plugin.config.getLong("payment-groups.defaults.interval"), lastPaymentTime = System.currentTimeMillis(), balance = 0 ) paymentGroupProvider.addPaymentGroup(paymentGroup) paymentGroup.addOwner(character) sender.sendMessage(plugin.messages["payment-create-valid"]) } else { sender.sendMessage(plugin.messages["no-character"]) } } else { sender.sendMessage(plugin.messages["no-minecraft-profile"]) } } else { sender.sendMessage(plugin.messages["not-from-console"]) } } else{ sender.sendMessage(plugin.messages["payment-create-invalid-name-already-exists"]) } } else { sender.sendMessage(plugin.messages["payment-create-usage"]) } } else { sender.sendMessage(plugin.messages["no-permission-payment-create"]) } return true } }
apache-2.0
23708a7f2e797c6edc54a19f59695e5b
49.977273
136
0.597414
5.751282
false
false
false
false
eurofurence/ef-app_android
app/src/main/kotlin/org/eurofurence/connavigator/util/v2/AbstractDelta.kt
1
3391
@file:Suppress("unused") package org.eurofurence.connavigator.util.v2 import io.swagger.client.model.* import java.util.* /** * An abstract form of the delta case classes. */ class AbstractDelta<T>( val id: (T) -> UUID, val last: Date, val deltaStart: Date, val clearBeforeInsert: Boolean, val changed: List<T>, val deleted: List<UUID>) fun DeltaResponseAnnouncementRecord.convert() = AbstractDelta(AnnouncementRecord::getId, storageLastChangeDateTimeUtc, storageDeltaStartChangeDateTimeUtc, removeAllBeforeInsert, changedEntities, deletedEntities) fun DeltaResponseDealerRecord.convert() = AbstractDelta(DealerRecord::getId, storageLastChangeDateTimeUtc, storageDeltaStartChangeDateTimeUtc, removeAllBeforeInsert, changedEntities, deletedEntities) fun DeltaResponseEventConferenceDayRecord.convert() = AbstractDelta(EventConferenceDayRecord::getId, storageLastChangeDateTimeUtc, storageDeltaStartChangeDateTimeUtc, removeAllBeforeInsert, changedEntities, deletedEntities) fun DeltaResponseEventConferenceRoomRecord.convert() = AbstractDelta(EventConferenceRoomRecord::getId, storageLastChangeDateTimeUtc, storageDeltaStartChangeDateTimeUtc, removeAllBeforeInsert, changedEntities, deletedEntities) fun DeltaResponseEventConferenceTrackRecord.convert() = AbstractDelta(EventConferenceTrackRecord::getId, storageLastChangeDateTimeUtc, storageDeltaStartChangeDateTimeUtc, removeAllBeforeInsert, changedEntities, deletedEntities) fun DeltaResponseEventRecord.convert() = AbstractDelta(EventRecord::getId, storageLastChangeDateTimeUtc, storageDeltaStartChangeDateTimeUtc, removeAllBeforeInsert, changedEntities, deletedEntities) fun DeltaResponseImageRecord.convert() = AbstractDelta(ImageRecord::getId, storageLastChangeDateTimeUtc, storageDeltaStartChangeDateTimeUtc, removeAllBeforeInsert, changedEntities, deletedEntities) fun DeltaResponseKnowledgeEntryRecord.convert() = AbstractDelta(KnowledgeEntryRecord::getId, storageLastChangeDateTimeUtc, storageDeltaStartChangeDateTimeUtc, removeAllBeforeInsert, changedEntities, deletedEntities) fun DeltaResponseKnowledgeGroupRecord.convert() = AbstractDelta(KnowledgeGroupRecord::getId, storageLastChangeDateTimeUtc, storageDeltaStartChangeDateTimeUtc, removeAllBeforeInsert, changedEntities, deletedEntities) fun DeltaResponseMapRecord.convert() = AbstractDelta(MapRecord::getId, storageLastChangeDateTimeUtc, storageDeltaStartChangeDateTimeUtc, removeAllBeforeInsert, changedEntities, deletedEntities)
mit
3c3b797fdc04a1eb21736967ec13232e
33.969072
56
0.631377
5.63289
false
false
false
false
nsnikhil/Notes
app/src/main/java/com/nrs/nsnik/notes/util/ReminderUtil.kt
1
3869
/* * Notes Copyright (C) 2018 Nikhil Soni * This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. * This is free software, and you are welcome to redistribute it * under certain conditions; type `show c' for details. * * The hypothetical commands `show w' and `show c' should show the appropriate * parts of the General Public License. Of course, your program's commands * might be different; for a GUI interface, you would use an "about box". * * You should also get your employer (if you work as a programmer) or school, * if any, to sign a "copyright disclaimer" for the program, if necessary. * For more information on this, and how to apply and follow the GNU GPL, see * <http://www.gnu.org/licenses/>. * * The GNU General Public License does not permit incorporating your program * into proprietary programs. If your program is a subroutine library, you * may consider it more useful to permit linking proprietary applications with * the library. If this is what you want to do, use the GNU Lesser General * Public License instead of this License. But first, please read * <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ package com.nrs.nsnik.notes.util import android.app.Activity import android.app.AlarmManager import android.app.PendingIntent import android.app.TimePickerDialog import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.PackageManager import androidx.lifecycle.MutableLiveData import com.nrs.nsnik.notes.R import com.nrs.nsnik.notes.util.receiver.NotificationReceiver import java.util.* class ReminderUtil { companion object { fun setReminder(activity: Activity, title: String, body: String): MutableLiveData<Int> { val hasReminders = MutableLiveData<Int>() val calendar = Calendar.getInstance() val time = TimePickerDialog(activity, { timePicker, hour, minutes -> hasReminders.value = 1 setNotification(activity, calendar, hour, minutes, title, body) }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), false) time.show() return hasReminders } private fun setNotification(activity: Activity, calendar: Calendar, hour: Int, minutes: Int, title: String, body: String) { val myIntent = Intent(activity, NotificationReceiver::class.java) myIntent.putExtra(activity.resources.getString(R.string.notificationTitle), title) myIntent.putExtra(activity.resources.getString(R.string.notificationContent), body) val alarmManager = activity.getSystemService(Context.ALARM_SERVICE) as AlarmManager val pendingIntent = PendingIntent.getBroadcast(activity, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT) calendar.set(Calendar.HOUR_OF_DAY, hour) calendar.set(Calendar.MINUTE, minutes) alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY, pendingIntent) } fun cancelReminder(activity: Activity) { val receiver = ComponentName(activity, NotificationReceiver::class.java) val packageManager: PackageManager = activity.packageManager packageManager.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP) val intent = Intent(activity, NotificationReceiver::class.java) val pendingIntent = PendingIntent.getBroadcast(activity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) val alarmManager = activity.getSystemService(Context.ALARM_SERVICE) as AlarmManager alarmManager.cancel(pendingIntent) pendingIntent.cancel() } } }
gpl-3.0
e1a681c74af25cc74e0bc42dd98c309c
44.529412
142
0.718273
4.644658
false
false
false
false
VerifAPS/verifaps-lib
geteta/src/main/kotlin/edu/kit/iti/formal/automation/testtables/apps/common.kt
1
2425
package edu.kit.iti.formal.automation.testtables.apps import com.github.ajalt.clikt.parameters.groups.OptionGroup import com.github.ajalt.clikt.parameters.options.* import com.github.ajalt.clikt.parameters.types.file import edu.kit.iti.formal.automation.testtables.GetetaFacade import edu.kit.iti.formal.automation.testtables.model.GeneralizedTestTable import edu.kit.iti.formal.util.info class CexAnalysationArguments() : OptionGroup() { val cexJson by option("--cexjson", help = "exports an analysis of the counter example in json").flag() val runAnalyzer by option("--row-map", help = "print out a mapping between table rows and states") .flag("--no-row-map", default = false) val odsExport by option("--ods", help = "generate ods counter-example file").file() val odsOpen by option("--ods-open").flag() val cexPrinter by option("--cexout", help = "prints an analyis of the counter example and the program") .flag() } class AutomataOptions : OptionGroup() { val drawAutomaton by option("--debug-automaton", help="generate a dot file, showing the generated automaton").flag(default = false) val showAutomaton by option("--show-automaton", help="run dot and show the image of the automaton").flag(default = false) } class TableArguments() : OptionGroup() { fun readTables(): List<GeneralizedTestTable> { return table.flatMap { info("Use table file ${it.absolutePath}") info("Time constants: $timeConstants") GetetaFacade.readTables(it, timeConstants) }.map { it.ensureProgramRuns() it.generateSmvExpression() it.simplify() }.filterByName(tableWhitelist) } val timeConstants: Map<String, Int> by option("-T", help = "setting a time constant") .splitPair("=") .convert{ it.first to it.second.toInt()} .multiple() .toMap() val table by option("-t", "--table", help = "test table file", metavar = "FILE") .file(exists = true, readable = true) .multiple(required = true) val tableWhitelist by option("--select-table", metavar = "TABLE_NAME", help = "specify table by name, which should be used from the given file") .multiple() val enableMesh by option("--meshed", help="enable experimental meshed tables") .flag("-M", default = false) }
gpl-3.0
f214850a374bce167b0bf0ab5c511d66
40.827586
135
0.661031
4.055184
false
true
false
false
AlmasB/FXGL
fxgl-gameplay/src/main/kotlin/com/almasb/fxgl/cutscene/dialogue/DialogueGraph.kt
1
7612
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.cutscene.dialogue import com.almasb.fxgl.core.collection.PropertyMap import com.almasb.fxgl.cutscene.dialogue.DialogueNodeType.* import javafx.beans.property.SimpleStringProperty import javafx.beans.property.StringProperty import javafx.collections.FXCollections /** * @author Almas Baimagambetov ([email protected]) */ enum class DialogueNodeType { START, END, TEXT, SUBDIALOGUE, CHOICE, FUNCTION, BRANCH } /** * The context in which a dialogue is running. * For example, a single NPC could be a context. */ fun interface DialogueContext { /** * @return property map that is local to the dialogue context */ fun properties(): PropertyMap } /* NODES */ sealed class DialogueNode( val type: DialogueNodeType, text: String ) { val textProperty: StringProperty = SimpleStringProperty(text) val text: String get() = textProperty.value val audioFileNameProperty: StringProperty = SimpleStringProperty("") val audioFileName: String get() = audioFileNameProperty.value override fun toString(): String { return javaClass.simpleName } } class StartNode(text: String) : DialogueNode(START, text) class EndNode(text: String) : DialogueNode(END, text) class TextNode(text: String) : DialogueNode(TEXT, text) class SubDialogueNode(text: String) : DialogueNode(SUBDIALOGUE, text) class FunctionNode(text: String) : DialogueNode(FUNCTION, text) class BranchNode(text: String) : DialogueNode(BRANCH, text) class ChoiceNode(text: String) : DialogueNode(CHOICE, text) { /** * Maps option id to option text. * Options start at id 0. * These are ids that are local to this choice node. */ val options = hashMapOf<Int, StringProperty>() /** * Maps option id to option condition. * Options start at id 0. * These are ids that are local to this choice node. */ val conditions = hashMapOf<Int, StringProperty>() /** * Returns last option id present in the options map, or -1 if there are no options. */ val lastOptionID: Int get() = options.keys.maxOrNull() ?: -1 } /* EDGES */ open class DialogueEdge(val source: DialogueNode, val target: DialogueNode) { override fun toString(): String { return "$source -> $target" } } class DialogueChoiceEdge(source: DialogueNode, val optionID: Int, target: DialogueNode) : DialogueEdge(source, target) { override fun toString(): String { return "$source, $optionID -> $target" } } /* GRAPH */ /** * A simplified graph implementation with minimal integrity checks. */ class DialogueGraph( /** * Counter for node ids in this graph. */ internal var uniqueID: Int = 0 ) { val nodes = FXCollections.observableMap(hashMapOf<Int, DialogueNode>()) val edges = FXCollections.observableArrayList<DialogueEdge>() val startNode: StartNode get() = nodes.values.find { it.type == START } as? StartNode ?: throw IllegalStateException("No start node in this graph.") /** * Adds node to this graph. */ fun addNode(node: DialogueNode) { nodes[uniqueID++] = node } /** * Removes the node from this graph, including incident edges. */ fun removeNode(node: DialogueNode) { val id = findNodeID(node) nodes.remove(id) edges.removeIf { it.source === node || it.target === node } } fun addEdge(edge: DialogueEdge) { edges += edge } fun removeEdge(edge: DialogueEdge) { edges -= edge } /** * Adds a dialogue edge between [source] and [target]. */ fun addEdge(source: DialogueNode, target: DialogueNode) { edges += DialogueEdge(source, target) } /** * Adds a choice dialog edge between [source] and [target]. */ fun addChoiceEdge(source: DialogueNode, optionID: Int, target: DialogueNode) { edges += DialogueChoiceEdge(source, optionID, target) } /** * Removes a dialogue edge between [source] and [target]. */ fun removeEdge(source: DialogueNode, target: DialogueNode) { edges.removeIf { it.source === source && it.target === target } } /** * Remove a choice dialogue edge between [source] and [target]. */ fun removeChoiceEdge(source: DialogueNode, optionID: Int, target: DialogueNode) { edges.removeIf { it is DialogueChoiceEdge && it.source === source && it.optionID == optionID && it.target === target } } fun containsNode(node: DialogueNode): Boolean = node in nodes.values /** * @return node id in this graph or -1 if node is not in this graph */ fun findNodeID(node: DialogueNode): Int { for ((id, n) in nodes) { if (n === node) return id } return -1 } fun getNodeByID(id: Int): DialogueNode { return nodes[id] ?: throw IllegalArgumentException("Graph does not contain a node with id $id") } fun nextNode(node: DialogueNode): DialogueNode? { return edges.find { it.source === node }?.target } fun nextNode(node: DialogueNode, optionID: Int): DialogueNode? { return edges.find { it is DialogueChoiceEdge && it.source === node && it.optionID == optionID }?.target } fun appendGraph(source: DialogueNode, target: DialogueNode, graph: DialogueGraph) { val start = graph.startNode val endNodes = graph.nodes.values.filter { it.type == END } // convert start and end nodes into text nodes and add them to this graph val newStart = TextNode(start.text) val newEndNodes = endNodes.map { TextNode(it.text) } addNode(newStart) newEndNodes.forEach { addNode(it) } // add the rest of the nodes "as is" to this graph graph.nodes.values .minus(start) .minus(endNodes) .forEach { addNode(it) } // add the "internal" graph edges to this graph graph.edges .filter { containsNode(it.source) && containsNode(it.target) } .forEach { if (it is DialogueChoiceEdge) { addChoiceEdge(it.source, it.optionID, it.target) } else { addEdge(it.source, it.target) } } // add the "external" graph edges // form new chain source -> start -> ... -> endNodes -> target addEdge(source, newStart) newEndNodes.forEach { addEdge(it, target) } addEdge(newStart, graph.nextNode(start)!!) newEndNodes.forEach { endNode -> graph.edges .filter { it.target.type == END } .forEach { if (it is DialogueChoiceEdge) { addChoiceEdge(it.source, it.optionID, endNode) } else { addEdge(it.source, endNode) } } } } /** * @return a shallow copy of the graph (i.e. nodes and edges are the same references as in this graph) */ fun copy(): DialogueGraph { val copy = DialogueGraph(uniqueID) copy.nodes.putAll(nodes) copy.edges.addAll(edges) return copy } }
mit
f22d388e22eea209e155ebf0799b585f
27.192593
120
0.603915
4.281215
false
false
false
false
MaibornWolff/codecharta
analysis/import/CSVImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/csv/ParserDialog.kt
1
2447
package de.maibornwolff.codecharta.importer.csv import com.github.kinquirer.KInquirer import com.github.kinquirer.components.promptConfirm import com.github.kinquirer.components.promptInput import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface class ParserDialog { companion object : ParserDialogInterface { override fun collectParserArgs(): List<String> { val inputFileNames = mutableListOf(KInquirer.promptInput( message = "Please specify the name of the first sourcemonitor CSV file to be parsed:", hint = "input.csv" )) while (true) { val additionalFile = KInquirer.promptInput( message = "If you want to parse additional sourcemonitor CSV files, specify the name of the next file. Otherwise, leave this field empty to skip.", ) if (additionalFile.isNotBlank()) { inputFileNames.add(additionalFile) } else { break } } val outputFileName: String = KInquirer.promptInput( message = "What is the name of the output file?", hint = "output.cc.json" ) val pathColumnName: String = KInquirer.promptInput( message = "What is the name of the path column name?", default = "path" ) val delimiter = KInquirer.promptInput( message = "Which column delimiter is used in the CSV file?", hint = ",", default = "," ) val pathSeparator = KInquirer.promptInput( message = "Which path separator is used in the path names?", hint = "/", default = "/" ) val isCompressed = (outputFileName.isEmpty()) || KInquirer.promptConfirm( message = "Do you want to compress the output file?", default = true ) return inputFileNames + listOfNotNull( "--output-file=$outputFileName", "--path-column-name=$pathColumnName", "--delimiter=$delimiter", "--path-separator=$pathSeparator", if (isCompressed) null else "--not-compressed", ) } } }
bsd-3-clause
0ac47b33adadb22903bfb597aa4f0436
37.84127
171
0.541888
5.771226
false
false
false
false
chrsep/Kingfish
app/src/main/java/com/directdev/portal/models/CourseModel.kt
1
667
package com.directdev.portal.models import com.squareup.moshi.Json import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class CourseModel( @PrimaryKey @Json(name = "CLASS_NBR") open var classNumber: Int = 0, @Json(name = "COURSEID") open var courseId: String = "N/A", //3.370 @Json(name = "COURSENAME") open var courseName: String = "N/A", //0.00 @Json(name = "CRSE_ID") open var crseId: String = "N/A", //60 @Json(name = "SSR_COMPONENT") open var ssrComponent: String = "N/A", //146 open var term: Int = 0 ) : RealmObject()
gpl-3.0
e80420290eeafac3fbb6bbf8d41f1baf
24.653846
71
0.577211
3.529101
false
false
false
false
ericberman/MyFlightbookAndroid
app/src/main/java/model/Totals.kt
1
3536
/* MyFlightbook for Android - provides native access to MyFlightbook pilot's logbook Copyright (C) 2017-2022 MyFlightbook, LLC This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package model import org.ksoap2.serialization.SoapObject import java.io.Serializable import java.util.* class Totals : SoapableObject, Serializable { enum class NumType { Integer, Decimal, Time, Currency } enum class TotalsGroup { None, CategoryClass, ICAO, Model, Capabilities, CoreFields, Properties, Total } @JvmField var description = "" @JvmField var value = 0.0 @JvmField var subDescription = "" @JvmField var numericType = NumType.Integer @JvmField var query: FlightQuery? = null private var group = TotalsGroup.None @JvmField var groupName = "" constructor(so: SoapObject) : super() { fromProperties(so) } constructor() : super() override fun toString(): String { return String.format(Locale.getDefault(), "%s %s %.2f", description, subDescription, value) } override fun toProperties(so: SoapObject) { so.addProperty("Value", value) so.addProperty("Description", description) so.addProperty("SubDescription", subDescription) so.addProperty("NumericType", numericType) so.addProperty("Query", query) so.addProperty("Group", group) so.addProperty("GroupName", groupName) } override fun fromProperties(so: SoapObject) { description = so.getProperty("Description").toString() value = so.getProperty("Value").toString().toDouble() // Optional strings come through as "anyType" if they're not actually present, so check for that. val o = so.getProperty("SubDescription") if (o != null && !o.toString().contains("anyType")) subDescription = o.toString() numericType = NumType.valueOf(so.getProperty("NumericType").toString()) if (so.hasProperty("Query")) { val q = so.getProperty("Query") as SoapObject query = FlightQuery() query!!.fromProperties(q) } group = TotalsGroup.valueOf(so.getProperty("Group").toString()) groupName = so.getPropertySafelyAsString("GroupName") } companion object { @JvmStatic fun groupTotals(rgIn: Array<Totals>?): ArrayList<ArrayList<Totals>> { val result = ArrayList<ArrayList<Totals>>() if (rgIn == null) return result val d = Hashtable<Int, ArrayList<Totals>>() for (ti in rgIn) { if (!d.containsKey(ti.group.ordinal)) d[ti.group.ordinal] = ArrayList() d[ti.group.ordinal]?.add(ti) } for (tg in TotalsGroup.values()) { if (d.containsKey(tg.ordinal)) result.add(d[tg.ordinal]!!) } return result } } }
gpl-3.0
4f680387f9dce881bb98433cee8a5739
33.676471
105
0.639989
4.464646
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/client/view/detail/tab_5e.kt
1
4099
package at.cpickl.gadsu.client.view.detail import at.cpickl.gadsu.client.Client import at.cpickl.gadsu.client.ElementMaybe import at.cpickl.gadsu.client.YinYangMaybe import at.cpickl.gadsu.client.xprops.view.GridBagFill import at.cpickl.gadsu.view.Fields import at.cpickl.gadsu.view.ViewNames import at.cpickl.gadsu.view.components.panels.FormPanel import at.cpickl.gadsu.view.language.Labels import at.cpickl.gadsu.view.logic.ModificationChecker import at.cpickl.gadsu.view.swing.titledBorder import com.google.common.eventbus.EventBus import org.slf4j.LoggerFactory import java.awt.GridBagConstraints class ClientTab5e( initialClient: Client, modificationChecker: ModificationChecker, bus: EventBus ) : DefaultClientTab( tabTitle = Labels.Tabs.Client5e, type = ClientTabType.FIVEE ) { private val log = LoggerFactory.getLogger(javaClass) private val fields = Fields<Client>(modificationChecker) val inpYyTendency = fields.newComboBox(YinYangMaybe.Enum.orderedValues, initialClient.yyTendency, "Tendenz", { it.yyTendency }, ViewNames.Client.InputYyTendency) val inpTextYinYang = fields.newTextArea("Beschreibung", { it.textYinYang }, ViewNames.Client.InputTextYinYang, bus) val inpElementTendency = fields.newComboBox(ElementMaybe.Enum.orderedValues, initialClient.elementTendency, "Tendenz", { it.elementTendency }, ViewNames.Client.InputElementTendency) val inpFiveElements = fields.newTextArea("Beschreibung", { it.textFiveElements }, ViewNames.Client.InputTextFiveElements, bus) val inpTextWood = fields.newTextArea("Holz", { it.textWood }, ViewNames.Client.InputTextFiveElements + "Wood", bus) val inpTextFire = fields.newTextArea("Feuer", { it.textFire }, ViewNames.Client.InputTextFiveElements + "Fire", bus) val inpTextEarth = fields.newTextArea("Erde", { it.textEarth }, ViewNames.Client.InputTextFiveElements + "Earth", bus) val inpTextMetal = fields.newTextArea("Metall", { it.textMetal }, ViewNames.Client.InputTextFiveElements + "Metal", bus) val inpTextWater = fields.newTextArea("Wasser", { it.textWater }, ViewNames.Client.InputTextFiveElements + "Water", bus) init { val formYy = FormPanel(fillCellsGridy = false).apply { titledBorder("Yin Yang") addFormInput(label = inpYyTendency.formLabel, input = inpYyTendency.toComponent(), fillType = GridBagFill.None, inputWeighty = 0.0) addFormInput(label = inpTextYinYang.formLabel, input = inpTextYinYang.toComponent(), fillType = GridBagFill.Both, inputWeighty = 1.0) } val form5e = FormPanel(fillCellsGridy = false).apply { titledBorder("5 Elemente") addFormInput(label = inpElementTendency.formLabel, input = inpElementTendency.toComponent(), fillType = GridBagFill.None, inputWeighty = 0.0) addFormInput(label = inpFiveElements.formLabel, input = inpFiveElements.toComponent(), fillType = GridBagFill.Both, inputWeighty = 0.2) addFormInput(label = inpTextWood.formLabel, input = inpTextWood.toComponent(), fillType = GridBagFill.Both, inputWeighty = 0.2) addFormInput(label = inpTextFire.formLabel, input = inpTextFire.toComponent(), fillType = GridBagFill.Both, inputWeighty = 0.2) addFormInput(label = inpTextEarth.formLabel, input = inpTextEarth.toComponent(), fillType = GridBagFill.Both, inputWeighty = 0.2) addFormInput(label = inpTextMetal.formLabel, input = inpTextMetal.toComponent(), fillType = GridBagFill.Both, inputWeighty = 0.2) addFormInput(label = inpTextWater.formLabel, input = inpTextWater.toComponent(), fillType = GridBagFill.Both, inputWeighty = 0.2) } c.fill = GridBagConstraints.BOTH c.weightx = 1.0 c.weighty = 0.3 add(formYy) c.gridy++ c.weighty = 0.7 add(form5e) } override fun isModified(client: Client) = fields.isAnyModified(client) override fun updateFields(client: Client) { log.trace("updateFields(client={})", client) fields.updateAll(client) } }
apache-2.0
b733858518a5fd8c92fe482163413b8e
53.653333
185
0.730666
3.605101
false
false
false
false
gatheringhallstudios/MHGenDatabase
app/src/main/java/com/ghstudios/android/data/cursors/QuestCursor.kt
1
2474
package com.ghstudios.android.data.cursors import android.database.Cursor import android.database.CursorWrapper import com.ghstudios.android.data.classes.Location import com.ghstudios.android.data.classes.Quest import com.ghstudios.android.data.classes.QuestHub import com.ghstudios.android.data.database.S import com.ghstudios.android.data.util.getInt import com.ghstudios.android.data.util.getLong import com.ghstudios.android.data.util.getString /** * A convenience class to wrap a cursor that returns rows from the "quests" * table. The [] method will give you a Quest instance * representing the current row. */ class QuestCursor(c: Cursor) : CursorWrapper(c) { /** * Returns a Quest object configured for the current row, or null if the * current row is invalid. */ //0=Normal,1=Key,2=Urgent val quest: Quest get() { val quest = Quest().apply { id = getLong(S.COLUMN_QUESTS_ID) name = getString("q" + S.COLUMN_QUESTS_NAME) ?: "" jpnName = getString("q" + S.COLUMN_QUESTS_JPN_NAME) ?: "" goal = getString(S.COLUMN_QUESTS_GOAL) hub = QuestHub.from(getString(S.COLUMN_QUESTS_HUB)!!) type = getInt(S.COLUMN_QUESTS_TYPE) stars = getString(S.COLUMN_QUESTS_STARS) timeLimit = getInt(S.COLUMN_QUESTS_TIME_LIMIT) fee = getInt(S.COLUMN_QUESTS_FEE) reward = getInt(S.COLUMN_QUESTS_REWARD) hrp = getInt(S.COLUMN_QUESTS_HRP) subGoal = getString(S.COLUMN_QUESTS_SUB_GOAL) subReward = getInt(S.COLUMN_QUESTS_SUB_REWARD) subHrp = getInt(S.COLUMN_QUESTS_SUB_HRP) goalType = getInt(S.COLUMN_QUESTS_GOAL_TYPE) hunterType = getInt(S.COLUMN_QUESTS_HUNTER_TYPE) flavor = getString(S.COLUMN_QUESTS_FLAVOR) metadata = getInt(S.COLUMN_QUESTS_METADATA) rank = getString(S.COLUMN_QUESTS_RANK) permitMonsterId = getInt(S.COLUMN_QUESTS_PERMIT_MONSTER_ID) } if(quest.name.isEmpty()) quest.name = quest.jpnName quest.location = Location().apply { id = getLong(S.COLUMN_QUESTS_LOCATION_ID) name = getString("l" + S.COLUMN_LOCATIONS_NAME) fileLocation = getString(S.COLUMN_LOCATIONS_MAP) } return quest } }
mit
8931df2cc0ae859d39ff2721a327f907
38.919355
76
0.613985
3.945774
false
false
false
false
VladRassokhin/intellij-hcl
src/kotlin/org/intellij/plugins/hil/psi/HILLexer.kt
1
2211
/* * 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 org.intellij.plugins.hil.psi import com.intellij.lexer.FlexAdapter import org.intellij.plugins.hil.psi._HILLexer.INTERPOLATION import org.intellij.plugins.hil.psi._HILLexer.STRING class HILLexer : FlexAdapter(_HILLexer()) { companion object { private val STRING_START_MASK: Int = 0xFFFF shl 0x10 // 0xFFFF0000 private val IN_STRING = 1 shl 14 private val HIL_MASK = 0x00003F00 // 8-13 private val JFLEX_STATE_MASK: Int = 0xFF } override fun getFlex(): _HILLexer { return super.getFlex() as _HILLexer } override fun start(buffer: CharSequence, startOffset: Int, endOffset: Int, state: Int) { val lexer = flex if (!isLexerInStringOrHILState(state) || state and IN_STRING == 0) { lexer.stringStart = -1 lexer.hil = 0 } else { lexer.stringStart = (state and STRING_START_MASK) ushr 0x10 lexer.hil = (state and HIL_MASK) ushr 8 } super.start(buffer, startOffset, endOffset, state and JFLEX_STATE_MASK) } private fun isLexerInStringOrHILState(state: Int): Boolean { return when (state and JFLEX_STATE_MASK) { STRING -> true INTERPOLATION -> true else -> false } } override fun getState(): Int { val lexer = flex var state = super.getState() assert(state and (JFLEX_STATE_MASK.inv()) == 0) { "State outside JFLEX_STATE_MASK ($JFLEX_STATE_MASK) should not be used by JFLex lexer" } state = state and JFLEX_STATE_MASK if (lexer.stringStart != -1) { state = state or IN_STRING } state = state or (((lexer.hil and 0x3f) shl 8) and HIL_MASK) return state } }
apache-2.0
3dad5b9b292fb2dd08fddf46d24768e3
32.5
142
0.688829
3.595122
false
false
false
false
jitsi/jitsi-videobridge
jvb/src/main/kotlin/org/jitsi/videobridge/cc/allocation/BandwidthAllocator.kt
1
16380
/* * Copyright @ 2015 - Present, 8x8 Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge.cc.allocation import edu.umd.cs.findbugs.annotations.SuppressFBWarnings import org.jitsi.nlj.MediaSourceDesc import org.jitsi.utils.event.EventEmitter import org.jitsi.utils.event.SyncEventEmitter import org.jitsi.utils.logging.DiagnosticContext import org.jitsi.utils.logging2.Logger import org.jitsi.utils.logging2.createChildLogger import org.jitsi.videobridge.cc.config.BitrateControllerConfig import org.jitsi.videobridge.util.TaskPools import org.json.simple.JSONObject import java.time.Clock import java.time.Duration import java.time.Instant import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit import java.util.function.Supplier import kotlin.math.abs internal class BandwidthAllocator<T : MediaSourceContainer>( eventHandler: EventHandler, /** * Provide the current list of endpoints (in no particular order). * TODO: Simplify to avoid the weird (and slow) flow involving `endpointsSupplier` and `sortedEndpointIds`. */ private val endpointsSupplier: Supplier<List<T>>, /** * Whether bandwidth allocation should be constrained to the available bandwidth (when `true`), or assume * infinite bandwidth (when `false`). */ private val trustBwe: Supplier<Boolean>, parentLogger: Logger, private val diagnosticContext: DiagnosticContext, private val clock: Clock ) { private val logger = createChildLogger(parentLogger) /** * The estimated available bandwidth in bits per second. */ private var bweBps: Long = -1 /** * Whether this bandwidth estimator has been expired. Once expired we stop periodic re-allocation. */ private var expired = false /** * The "effective" constraints for an endpoint indicate the maximum resolution/fps that this * [BandwidthAllocator] would allocate for this endpoint given enough bandwidth. * * They are the constraints signaled by the receiver, further reduced to 0 when the endpoint is "outside lastN". * * Effective constraints are used to signal to video senders to reduce their resolution to the minimum that * satisfies all receivers. * * With the multi-stream support added, the mapping is stored on a per source name basis instead of an endpoint id. * * When an endpoint falls out of the last N, the constraints of all the sources of this endpoint are reduced to 0. * * TODO Update this description when the endpoint ID signaling is removed from the JVB. */ private var effectiveConstraints: EffectiveConstraintsMap = emptyMap() private val eventEmitter: EventEmitter<EventHandler> = SyncEventEmitter<EventHandler>().apply { addHandler(eventHandler) } /** * The allocations settings signalled by the receiver. */ private var allocationSettings = AllocationSettings(defaultConstraints = VideoConstraints(BitrateControllerConfig.config.thumbnailMaxHeightPx())) /** * The last time [BandwidthAllocator.update] was called. * Initialized as initialization time to prevent triggering an update immediately, because the settings might not * have been configured yet. */ private var lastUpdateTime: Instant = clock.instant() /** * The result of the bitrate control algorithm, the last time it ran. */ var allocation = BandwidthAllocation(emptySet()) private set /** * The task scheduled to call [.update]. */ private var updateTask: ScheduledFuture<*>? = null init { rescheduleUpdate() } /** * Gets a JSON representation of the parts of this object's state that are deemed useful for debugging. */ @get:SuppressFBWarnings( value = ["IS2_INCONSISTENT_SYNC"], justification = "We intentionally avoid synchronizing while reading fields only used in debug output." ) val debugState: JSONObject get() { val debugState = JSONObject() debugState["trustBwe"] = trustBwe.get() debugState["bweBps"] = bweBps debugState["allocation"] = allocation.debugState debugState["allocationSettings"] = allocationSettings.toJson() debugState["effectiveConstraints"] = effectiveConstraints return debugState } /** * Get the available bandwidth, taking into account the `trustBwe` option. */ private val availableBandwidth: Long get() = if (trustBwe.get()) bweBps else Long.MAX_VALUE /** * Notify the [BandwidthAllocator] that the estimated available bandwidth has changed. * @param newBandwidthBps the newly estimated bandwidth in bps */ fun bandwidthChanged(newBandwidthBps: Long) { if (!bweChangeIsLargerThanThreshold(bweBps, newBandwidthBps)) { logger.debug { "New bwe ($newBandwidthBps) is not significantly changed from previous bwe ($bweBps), ignoring." } // If this is a "negligible" change in the bandwidth estimation // wrt the last bandwidth estimation that we reacted to, then // do not update the bandwidth allocation. The goal is to limit // the resolution changes due to bandwidth estimation changes, // as often resolution changes can negatively impact user // experience, at the risk of clogging the receiver pipe. } else { logger.debug { "new bandwidth is $newBandwidthBps, updating" } bweBps = newBandwidthBps update() } } /** * Updates the allocation settings and calculates a new bitrate [BandwidthAllocation]. * @param allocationSettings the new allocation settings. */ fun update(allocationSettings: AllocationSettings) { this.allocationSettings = allocationSettings update() } /** * Runs the bandwidth allocation algorithm, and fires events if the result is different from the previous result. */ @Synchronized fun update() { if (expired) { return } lastUpdateTime = clock.instant() // Order the sources by selection, followed by Endpoint's speech activity. val sources = endpointsSupplier.get().flatMap { it.mediaSources.toList() }.toMutableList() val sortedSources = prioritize(sources, selectedSources) // Extract and update the effective constraints. val oldEffectiveConstraints = effectiveConstraints val newEffectiveConstraints = getEffectiveConstraints(sortedSources, allocationSettings) effectiveConstraints = newEffectiveConstraints logger.trace { "Allocating: sortedSources=${sortedSources.map { it.sourceName }}, " + " effectiveConstraints=$newEffectiveConstraints" } // Compute the bandwidth allocation. val newAllocation = allocate(sortedSources) val allocationChanged = !allocation.isTheSameAs(newAllocation) val effectiveConstraintsChanged = effectiveConstraints != oldEffectiveConstraints if (allocationChanged) { eventEmitter.fireEvent { allocationChanged(newAllocation) } } allocation = newAllocation logger.trace { "Finished allocation: allocationChanged=$allocationChanged, " + "effectiveConstraintsChanged=$effectiveConstraintsChanged" } if (effectiveConstraintsChanged) { eventEmitter.fireEvent { effectiveVideoConstraintsChanged(oldEffectiveConstraints, effectiveConstraints) } } } // On-stage sources are considered selected (with higher priority). private val selectedSources: List<String> get() { // On-stage sources are considered selected (with higher priority). val selectedSources = allocationSettings.onStageSources.toMutableList() allocationSettings.selectedSources.forEach { if (!selectedSources.contains(it)) { selectedSources.add(it) } } return selectedSources } /** * Implements the bandwidth allocation algorithm for the given ordered list of media sources. * * The new version which works with multiple streams per endpoint. * * @param conferenceMediaSources the list of endpoint media sources in order of priority to allocate for. * @return the new [BandwidthAllocation]. */ @Synchronized private fun allocate(conferenceMediaSources: List<MediaSourceDesc>): BandwidthAllocation { val sourceBitrateAllocations = createAllocations(conferenceMediaSources) if (sourceBitrateAllocations.isEmpty()) { return BandwidthAllocation(emptySet()) } var remainingBandwidth = availableBandwidth var oldRemainingBandwidth: Long = -1 var oversending = false while (oldRemainingBandwidth != remainingBandwidth) { oldRemainingBandwidth = remainingBandwidth for (i in sourceBitrateAllocations.indices) { val sourceBitrateAllocation = sourceBitrateAllocations[i] if (sourceBitrateAllocation.constraints.isDisabled()) { continue } // In stage view improve greedily until preferred, in tile view go step-by-step. remainingBandwidth -= sourceBitrateAllocation.improve(remainingBandwidth, i == 0) if (remainingBandwidth < 0) { oversending = true } // In stage view, do not allocate bandwidth for thumbnails until the on-stage reaches "preferred". // This prevents enabling thumbnail only to disable them when bwe slightly increases allowing on-stage // to take more. if (sourceBitrateAllocation.isOnStage() && !sourceBitrateAllocation.hasReachedPreferred()) { break } } } // The sources which are in lastN, and are sending video, but were suspended due to bwe. val suspendedIds = sourceBitrateAllocations .filter { it.isSuspended } .map { it.mediaSource.sourceName }.toList() if (suspendedIds.isNotEmpty()) { logger.info("Sources suspended due to insufficient bandwidth (bwe=$availableBandwidth bps): $suspendedIds") } val allocations = mutableSetOf<SingleAllocation>() var targetBps: Long = 0 var idealBps: Long = 0 for (sourceBitrateAllocation: SingleSourceAllocation in sourceBitrateAllocations) { allocations.add(sourceBitrateAllocation.result) targetBps += sourceBitrateAllocation.targetBitrate idealBps += sourceBitrateAllocation.idealBitrate } return BandwidthAllocation(allocations, oversending, idealBps, targetBps, suspendedIds) } /** * Query whether the allocator has non-zero effective constraints for the given endpoint or source. */ internal fun hasNonZeroEffectiveConstraints(source: MediaSourceDesc): Boolean { val constraints = effectiveConstraints[source] ?: return false return !constraints.isDisabled() } @Synchronized private fun createAllocations( conferenceMediaSources: List<MediaSourceDesc> ): List<SingleSourceAllocation> = conferenceMediaSources.map { source -> SingleSourceAllocation( source.owner, source, // Note that we use the effective constraints and not the receiver's constraints // directly. This means we never even try to allocate bitrate to sources "outside // lastN". For example, if LastN=1 and the first endpoint sends a non-scalable // stream with bitrate higher that the available bandwidth, we will forward no // video at all instead of going to the second endpoint in the list. // I think this is not desired behavior. However, it is required for the "effective // constraints" to work as designed. effectiveConstraints[source]!!, allocationSettings.onStageSources.contains(source.sourceName), diagnosticContext, clock, logger ) }.toList() /** * Expire this bandwidth allocator. */ fun expire() { expired = true updateTask?.cancel(false) } /** * Submits a call to `update` in a CPU thread if bandwidth allocation has not been performed recently. * * Also, re-schedule the next update in at most `maxTimeBetweenCalculations`. This should only be run * in the constructor or in the scheduler thread, otherwise it will schedule multiple tasks. */ private fun rescheduleUpdate() { if (expired) { return } val timeSinceLastUpdate = Duration.between(lastUpdateTime, clock.instant()) val period = BitrateControllerConfig.config.maxTimeBetweenCalculations() val delayMs = if (timeSinceLastUpdate > period) { logger.debug("Running periodic re-allocation.") TaskPools.CPU_POOL.execute { this.update() } period.toMillis() } else { period.minus(timeSinceLastUpdate).toMillis() } // Add 5ms to avoid having to re-schedule right away. This increases the average period at which we // re-allocate by an insignificant amount. updateTask = TaskPools.SCHEDULED_POOL.schedule( { rescheduleUpdate() }, delayMs + 5, TimeUnit.MILLISECONDS ) } interface EventHandler { fun allocationChanged(allocation: BandwidthAllocation) fun effectiveVideoConstraintsChanged( oldEffectiveConstraints: EffectiveConstraintsMap, newEffectiveConstraints: EffectiveConstraintsMap ) } } /** * Returns a boolean that indicates whether the current bandwidth estimation (in bps) has changed above the * configured threshold with respect to the previous bandwidth estimation. * * @param previousBwe the previous bandwidth estimation (in bps). * @param currentBwe the current bandwidth estimation (in bps). * @return true if the bandwidth has changed above the configured threshold, * false otherwise. */ private fun bweChangeIsLargerThanThreshold(previousBwe: Long, currentBwe: Long): Boolean { if (previousBwe == -1L || currentBwe == -1L) { return true } // We supress re-allocation when BWE has changed less than 15% (by default) of its previous value in order to // prevent excessive changes during ramp-up. // When BWE increases it should eventually increase past the threshold because of probing. // When BWE decreases it is probably above the threshold because of AIMD. It's not clear to me whether we need // the threshold in this case. // In any case, there are other triggers for re-allocation, so any suppression we do here will only last up to // a few seconds. val deltaBwe = abs(currentBwe - previousBwe) return deltaBwe > previousBwe * BitrateControllerConfig.config.bweChangeThreshold() // If, on the other hand, the bwe has decreased, we require at least a 15% drop in order to update the bitrate // allocation. This is an ugly hack to prevent too many resolution/UI changes in case the bridge produces too // low bandwidth estimate, at the risk of clogging the receiver's pipe. // TODO: do we still need this? Do we ever ever see BWE drop by <%15? } typealias EffectiveConstraintsMap = Map<MediaSourceDesc, VideoConstraints>
apache-2.0
46c4b2853492f0496abd2cf7ca868531
41.107969
120
0.675885
5.074349
false
false
false
false
wireapp/wire-android
app/src/main/java/com/waz/zclient/pages/extendedcursor/voicefilter2/WaveGraphView.kt
1
3969
package com.waz.zclient.pages.extendedcursor.voicefilter2 import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Path import android.util.AttributeSet import android.view.View import com.waz.zclient.R class WaveGraphView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) { companion object { private const val kDefaultFrequency = 1.5f private const val kDefaultAmplitude = 1.0f private const val kDefaultIdleAmplitude = 0.01f private const val kDefaultNumberOfWaves = 5 private const val kDefaultPhaseShift = -0.25f private const val kDefaultDensity = 5.0f } private val path: Path private var waveColor: Int = 0 private val frequency: Float private var amplitude: Float = 0.toFloat() private val idleAmplitude: Float private val phaseShift: Float private val density: Double private var currentMaxAmplitude: Float? = null private val paint: Paint private val numberOfWaves: Int private var phase: Float = 0.toFloat() fun setAccentColor(accentColor: Int) { waveColor = accentColor } init { this.waveColor = Color.WHITE this.frequency = kDefaultFrequency this.amplitude = kDefaultAmplitude this.idleAmplitude = kDefaultIdleAmplitude this.numberOfWaves = kDefaultNumberOfWaves this.phaseShift = -kDefaultPhaseShift this.density = kDefaultDensity.toDouble() paint = Paint(Paint.ANTI_ALIAS_FLAG) paint.color = Color.WHITE paint.strokeWidth = resources.getDimensionPixelSize(R.dimen.wire__divider__height).toFloat() paint.style = Paint.Style.STROKE path = Path() } fun setMaxAmplitude(normalizedAmplitude: Float) { this.currentMaxAmplitude = normalizedAmplitude invalidate() phase += phaseShift val newAmplitude = Math.max(normalizedAmplitude, idleAmplitude) amplitude = (amplitude * 2 + newAmplitude) / 3 } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (currentMaxAmplitude == null) { return } // We draw multiple sinus waves, with equal phases but altered amplitudes, multiplied by a parable function. for (i in 0 until numberOfWaves) { path.reset() val halfHeight = canvas.height / 2.0f val width = canvas.width val mid = width / 2.0f val maxAmplitude = halfHeight - 4.0f // 4 corresponds to twice the stroke width // Progress is a value between 1.0 and -0.5, determined by the current wave idx, which is used to alter the wave's amplitude. val progress = 1.0f - i.toFloat() / numberOfWaves val normedAmplitude = (1.5f * progress - 0.5f) * amplitude path.moveTo(0f, halfHeight) var x = density while (x < width + this.density) { // We use a parable to scale the sinus wave, that has its peak in the middle of the view. val scaling = (-Math.pow(1.0f / mid * (x - mid), 2.0) + 1).toFloat() val y = (scaling.toDouble() * maxAmplitude.toDouble() * normedAmplitude.toDouble() * Math.sin(2.0 * Math.PI * (x / width) * this.frequency.toDouble() + this.phase) + halfHeight).toFloat() path.lineTo(x.toFloat(), y) x += this.density } val multiplier = Math.min(1.0f, progress / 3.0f * 2.0f + 1.0f / 3.0f) val alpha = Color.alpha(waveColor) val newAlpha = (multiplier * alpha).toInt() val color = Color.argb(newAlpha, Color.red(waveColor), Color.green(waveColor), Color.blue(waveColor)) paint.color = color canvas.drawPath(path, paint) } } }
gpl-3.0
c16ab3f8d04f5ea4434d424d630dcf55
36.8
203
0.642227
4.19113
false
false
false
false
teddywest32/realm-java
examples/kotlinExample/src/main/kotlin/io/realm/examples/kotlin/model/Person.kt
5
2074
/* * Copyright 2015 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.realm.examples.kotlin.model import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.Ignore import io.realm.annotations.PrimaryKey // Your model has to extend RealmObject. Furthermore, the class and all of the // properties must be annotated with open (Kotlin classes and methods are final // by default). open class Person( // You can put properties in the constructor as long as all of them are initialized with // default values. This ensures that an empty constructor is generated. // All properties are by default persisted. // Properties can be annotated with PrimaryKey or Index. // If you use non-nullable types, properties must be initialized with non-null values. @PrimaryKey open var name: String = "", open var age: Int = 0, // Other objects in a one-to-one relation must also subclass RealmObject open var dog: Dog? = null, // One-to-many relations is simply a RealmList of the objects which also subclass RealmObject open var cats: RealmList<Cat> = RealmList(), // You can instruct Realm to ignore a field and not persist it. @Ignore open var tempReference: Int = 0, open var id: Long = 0 ) : RealmObject() { // The Kotlin compiler generates standard getters and setters. // Realm will overload them and code inside them is ignored. // So if you prefer you can also just have empty abstract methods. }
apache-2.0
fe2c46446d9e70174c3097400edee9b4
39.666667
101
0.713115
4.508696
false
false
false
false
Deletescape-Media/Lawnchair
SystemUIShared/src/com/android/systemui/shared/animation/UnfoldMoveFromCenterAnimator.kt
1
6187
/* * Copyright (C) 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 com.android.systemui.shared.animation import android.graphics.Point import android.view.Surface import android.view.View import android.view.WindowManager import com.android.systemui.unfold.UnfoldTransitionProgressProvider import java.lang.ref.WeakReference /** * Creates an animation where all registered views are moved into their final location * by moving from the center of the screen to the sides */ class UnfoldMoveFromCenterAnimator @JvmOverloads constructor( private val windowManager: WindowManager, /** * Allows to set custom translation applier * Could be useful when a view could be translated from * several sources and we want to set the translation * using custom methods instead of [View.setTranslationX] or * [View.setTranslationY] */ private val translationApplier: TranslationApplier = object : TranslationApplier {}, /** * Allows to set custom implementation for getting * view location. Could be useful if logical view bounds * are different than actual bounds (e.g. view container may * have larger width than width of the items in the container) */ private val viewCenterProvider: ViewCenterProvider = object : ViewCenterProvider {} ) : UnfoldTransitionProgressProvider.TransitionProgressListener { private val screenSize = Point() private var isVerticalFold = false private val animatedViews: MutableList<AnimatedView> = arrayListOf() private var lastAnimationProgress: Float = 0f /** * Updates display properties in order to calculate the initial position for the views * Must be called before [registerViewForAnimation] */ fun updateDisplayProperties() { windowManager.defaultDisplay.getSize(screenSize) // Simple implementation to get current fold orientation, // this might not be correct on all devices // TODO: use JetPack WindowManager library to get the fold orientation isVerticalFold = windowManager.defaultDisplay.rotation == Surface.ROTATION_0 || windowManager.defaultDisplay.rotation == Surface.ROTATION_180 } /** * If target view positions have changed (e.g. because of layout changes) call this method * to re-query view positions and update the translations */ fun updateViewPositions() { animatedViews.forEach { animatedView -> animatedView.view.get()?.let { animatedView.updateAnimatedView(it) } } onTransitionProgress(lastAnimationProgress) } /** * Registers a view to be animated, the view should be measured and layouted * After finishing the animation it is necessary to clear * the views using [clearRegisteredViews] */ fun registerViewForAnimation(view: View) { val animatedView = createAnimatedView(view) animatedViews.add(animatedView) } /** * Unregisters all registered views and resets their translation */ fun clearRegisteredViews() { onTransitionProgress(1f) animatedViews.clear() } override fun onTransitionProgress(progress: Float) { animatedViews.forEach { it.view.get()?.let { view -> translationApplier.apply( view = view, x = it.startTranslationX * (1 - progress), y = it.startTranslationY * (1 - progress) ) } } lastAnimationProgress = progress } private fun createAnimatedView(view: View): AnimatedView = AnimatedView(view = WeakReference(view)).updateAnimatedView(view) private fun AnimatedView.updateAnimatedView(view: View): AnimatedView { val viewCenter = Point() viewCenterProvider.getViewCenter(view, viewCenter) val viewCenterX = viewCenter.x val viewCenterY = viewCenter.y if (isVerticalFold) { val distanceFromScreenCenterToViewCenter = screenSize.x / 2 - viewCenterX startTranslationX = distanceFromScreenCenterToViewCenter * TRANSLATION_PERCENTAGE startTranslationY = 0f } else { val distanceFromScreenCenterToViewCenter = screenSize.y / 2 - viewCenterY startTranslationX = 0f startTranslationY = distanceFromScreenCenterToViewCenter * TRANSLATION_PERCENTAGE } return this } /** * Interface that allows to use custom logic to apply translation to view */ interface TranslationApplier { /** * Called when we need to apply [x] and [y] translation to [view] */ fun apply(view: View, x: Float, y: Float) { view.translationX = x view.translationY = y } } /** * Interface that allows to use custom logic to get the center of the view */ interface ViewCenterProvider { /** * Called when we need to get the center of the view */ fun getViewCenter(view: View, outPoint: Point) { val viewLocation = IntArray(2) view.getLocationOnScreen(viewLocation) val viewX = viewLocation[0] val viewY = viewLocation[1] outPoint.x = viewX + view.width / 2 outPoint.y = viewY + view.height / 2 } } private class AnimatedView( val view: WeakReference<View>, var startTranslationX: Float = 0f, var startTranslationY: Float = 0f ) } private const val TRANSLATION_PERCENTAGE = 0.3f
gpl-3.0
efc3b3e3c491ec34bbc09409143738b4
34.354286
94
0.666882
4.867821
false
false
false
false
consp1racy/android-commons
commons/src/main/java/net/xpece/android/net/ConnectivityInfo.kt
1
2676
package net.xpece.android.net class ConnectivityInfo(@ConnectivityReceiver.State val state: Int, val isAirplaneModeEnabled: Boolean) { companion object { @JvmStatic private val CONNECTED = ConnectivityInfo(ConnectivityReceiver.Companion.STATE_CONNECTED, false) @JvmStatic private val CONNECTING = ConnectivityInfo(ConnectivityReceiver.Companion.STATE_CONNECTING, false) @JvmStatic private val DISCONNECTED = ConnectivityInfo(ConnectivityReceiver.Companion.STATE_DISCONNECTED, false) @JvmStatic private val CONNECTED_AIRPLANE = ConnectivityInfo(ConnectivityReceiver.Companion.STATE_CONNECTED, true) @JvmStatic private val CONNECTING_AIRPLANE = ConnectivityInfo(ConnectivityReceiver.Companion.STATE_CONNECTING, true) @JvmStatic private val DISCONNECTED_AIRPLANE = ConnectivityInfo(ConnectivityReceiver.Companion.STATE_DISCONNECTED, true) @JvmField val DEFAULT = CONNECTED } val isConnected: Boolean get() = state == ConnectivityReceiver.STATE_CONNECTED val isConnecting: Boolean get() = state == ConnectivityReceiver.STATE_CONNECTING val isDisconnected: Boolean get() = state == ConnectivityReceiver.STATE_DISCONNECTED fun copy(@ConnectivityReceiver.State state: Int = this.state, isAirplaneModeEnabled: Boolean = this.isAirplaneModeEnabled): ConnectivityInfo { if (!isAirplaneModeEnabled) { when (state) { ConnectivityReceiver.STATE_CONNECTED -> return CONNECTED ConnectivityReceiver.STATE_CONNECTING -> return CONNECTING ConnectivityReceiver.STATE_DISCONNECTED -> return DISCONNECTED } } else { when (state) { ConnectivityReceiver.STATE_CONNECTED -> return CONNECTED_AIRPLANE ConnectivityReceiver.STATE_CONNECTING -> return CONNECTING_AIRPLANE ConnectivityReceiver.STATE_DISCONNECTED -> return DISCONNECTED_AIRPLANE } } throw IllegalArgumentException("Unrecognized state $state.") } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ConnectivityInfo) return false if (state != other.state) return false if (isAirplaneModeEnabled != other.isAirplaneModeEnabled) return false return true } override fun hashCode(): Int { var result = state.hashCode() result = 31 * result + isAirplaneModeEnabled.hashCode() return result } override fun toString(): String { return "ConnectivityInfo(state=$state, isAirplaneModeEnabled=$isAirplaneModeEnabled)" } }
apache-2.0
64911df3af79152b10ff80d08e233df1
43.6
146
0.700299
5.236791
false
false
false
false
ice1000/algo4j
src/test/kotlin/org/algo4j/util/SeqUtilsTest.kt
1
5420
package org.algo4j.util import org.algo4j.test.* import org.jetbrains.annotations.Contract import org.jetbrains.annotations.TestOnly import org.junit.Assert.* import org.junit.BeforeClass import org.junit.Test import java.util.* import java.util.Arrays as StdArrays /** * Created by ice1000 on 2016/11/17. * * @author ice1000 */ class SeqUtilsTest { @TestOnly @Test(timeout = 500) fun discretizationTest() { val ints = intArrayOf(33, 1, 100, 20, 43, 43) val result = intArrayOf(2, 0, 4, 1, 3, 3) SeqUtils .discretization(ints) SeqUtils .toString(ints) .println() assertArrayEquals(result, ints) val doubles = ints .map(Int::toDouble) .toDoubleArray() SeqUtils .discretization(doubles) SeqUtils .toString(doubles) .println() assertArrayEquals( result .map(Int::toDouble) .toDoubleArray(), doubles, 1e-10 ) } @TestOnly @Test(timeout = 100) fun inversionTest() { assertEquals(SeqUtils.inversion(intArrayOf(3, 1, 5, 2, 4)), 4) } @TestOnly // @JvmOverloads fun sortTest( sortInt: (IntArray) -> Unit, sortDouble: (DoubleArray) -> Unit, times: Int = 10000) { test(times) { val data1 = shuffledIntList val res11 = data1.toIntArray() StdArrays.sort(res11) val res12 = data1.toIntArray() sortInt(res12) assertArrayEquals(res11, res12) val data2 = shuffledDoubleList val res21 = data2.toDoubleArray() StdArrays.sort(res21) val res22 = data2.toDoubleArray() sortDouble(res22) assertArrayEquals(res21, res22, 1e-10) } } @TestOnly @Test(timeout = 1000) fun sortBubbleTest() = sortTest( SeqUtils::sortBubble, SeqUtils::sortBubble, 2000 ) @TestOnly @Test(timeout = 1000) fun sortInsertionTest() = sortTest( SeqUtils::sortInsertion, SeqUtils::sortInsertion, 2000 ) @TestOnly @Test(timeout = 1000) fun sortQuickTest() = sortTest( SeqUtils::sortQuick, SeqUtils::sortQuick ) @TestOnly @Test(timeout = 1000) fun sortMergeTest() = sortTest( SeqUtils::sortMerge, SeqUtils::sortMerge ) @TestOnly @Test(timeout = 1000) fun sortSelectionTest() = sortTest( SeqUtils::sortSelection, SeqUtils::sortSelection, 2000 ) @TestOnly @Test(timeout = 1000) fun sortCombTest() = sortTest( SeqUtils::sortComb, SeqUtils::sortComb, 2000 ) @TestOnly @Test(timeout = 1000) fun sortCocktailTest() = sortTest( SeqUtils::sortCocktail, SeqUtils::sortCocktail, 2000 ) @TestOnly @Test(timeout = 10000) fun sortForkJoinTest() = sortTest( SeqUtils::sortForkJoin, SeqUtils::sortForkJoin, 2000 ) /** * 大数据归并测试(归并吊打快排现场) */ @TestOnly @Test(timeout = 10000) fun veryStrongTestMergeSort() { SeqUtils.sortMerge(strongIntArray.toIntArray()) } /** * 大数据快排测试(快排被归并吊打现场) */ @TestOnly @Test(timeout = 10000) fun veryStrongTestQuickSort() { SeqUtils.sortQuick(strongIntArray.toIntArray()) } /** * 大数据多线程快排测试(无脑开的多线程吊打单线程现场) * Java实现 */ @TestOnly @Test(timeout = 10000) fun veryStrongTestForkJoinSort() { SeqUtils.sortForkJoin(strongIntArray.toIntArray()) } /** * 大数据单线程快排测试 * Java实现 */ @TestOnly @Test(timeout = 10000) fun veryStrongTestJavaQuickSort() { ParallelQuickSorter .MultiThreadingQuickSorterInt(strongIntArray.toIntArray(), Integer.MAX_VALUE) .forkJoinSort() } /** * 复制测试 */ @TestOnly @Test(timeout = 1000) fun copyTest() { assertNull(SeqUtils.copy(null as IntArray?)) assertNull(SeqUtils.copy(null as DoubleArray?)) assertNull(SeqUtils.copy(null as FloatArray?)) assertNull(SeqUtils.copy(null as BooleanArray?)) assertNull(SeqUtils.copy(null as ShortArray?)) assertNull(SeqUtils.copy(null as ByteArray?)) assertNull(SeqUtils.copy(null as IntArray? as DoubleArray? as FloatArray? as BooleanArray? as ShortArray? as ByteArray?)) test(1000) { val arr = shuffledIntList.toIntArray() val arr2 = shuffledDoubleList.toDoubleArray() assertArrayEquals( StdArrays.copyOf(arr, arr.size), SeqUtils.copy(arr) ) assertArrayEquals( StdArrays.copyOf(arr2, arr2.size), SeqUtils.copy(arr2), 1e-15 ) } } /** * 看毛片测试 */ @TestOnly @Test(timeout = 1000) fun testKmp() { assertEquals(2, SeqUtils.kmp( intArrayOf(3, 2, 3, 5, 3, 2, 3), intArrayOf(3, 2, 3))) val rand = Random(System.currentTimeMillis()) test(1000) { val str = rand.nextInt(RAND_BOUND).toString() val times = rand.nextInt(200) val van = "${str}van".repeat(times) assertEquals(times, SeqUtils.kmp(van, "van")) assertEquals(times, SeqUtils.kmp(van, "va")) assertEquals(times, SeqUtils.kmp(van, "an")) assertEquals(times, SeqUtils.kmp(van, "v")) assertEquals(times, SeqUtils.kmp(van, str)) } } companion object Initializer { @BeforeClass @JvmStatic fun loadJniLibrary() { Loader.loadJni() randomArray = strongIntArray } lateinit var randomArray: List<Int> @TestOnly @Contract(pure = true) get val RAND_BOUND = 666666 @TestOnly @Contract(pure = true) get @TestOnly @JvmStatic fun main(args: Array<String>) { Loader.loadJni() SeqUtilsTest().discretizationTest() } } }
lgpl-3.0
67195f83715252321c358244748aecd0
18.744361
81
0.668888
2.948905
false
true
false
false
vase4kin/TeamCityApp
features/about/feature/src/main/java/teamcityapp/features/about/AboutActivity.kt
1
3068
/* * Copyright 2020 Andrey Tolpeev * * 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 teamcityapp.features.about import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.View import dagger.android.support.DaggerAppCompatActivity import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.addTo import io.reactivex.rxkotlin.subscribeBy import io.reactivex.schedulers.Schedulers import teamcityapp.features.about.repository.AboutRepository import teamcityapp.features.about.repository.models.ServerInfo import teamcityapp.libraries.utils.initToolbar import javax.inject.Inject /** * About activity */ class AboutActivity : DaggerAppCompatActivity() { @Inject lateinit var repository: AboutRepository private val subscriptions: CompositeDisposable = CompositeDisposable() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_about) initToolbar() loadServerInfo() } private fun loadServerInfo() { repository.serverInfo() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { showLoader() } .doFinally { hideLoader() } .subscribeBy( onError = { showAboutFragment() }, onSuccess = { showAboutFragment(it) } ) .addTo(subscriptions) } private fun showAboutFragment(serverInfo: ServerInfo? = null) { // Commit fragment to container supportFragmentManager .beginTransaction() .replace(R.id.about_library_container, AboutFragment.create(serverInfo)) .commit() } private fun showLoader() { findViewById<View>(R.id.progress_wheel).visibility = View.VISIBLE } private fun hideLoader() { findViewById<View>(R.id.progress_wheel).visibility = View.GONE } companion object { /** * Start About activity with Flag [Intent.FLAG_ACTIVITY_SINGLE_TOP] */ fun start(activity: Activity) { val launchIntent = Intent(activity, AboutActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) activity.startActivity(launchIntent) } } }
apache-2.0
114744ae6471596fba86c81112652fe7
29.989899
84
0.665254
4.964401
false
false
false
false
bnsantos/android-offline-example
app/app/src/main/java/com/bnsantos/offline/ui/activities/UserActivity.kt
1
2819
package com.bnsantos.offline.ui.activities import android.arch.lifecycle.Observer import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View.GONE import android.view.View.VISIBLE import android.widget.Toast import com.bnsantos.offline.R import com.bnsantos.offline.models.User import com.bnsantos.offline.viewmodel.UserViewModel import com.bnsantos.offline.vo.Resource import kotlinx.android.synthetic.main.activity_user.* class UserActivity : BaseActivity<UserViewModel>(UserViewModel::class.java){ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_user) showLoading(true) save.setOnClickListener { saveUser() } mViewModel.read().observe(this, observer(false)) } private fun observer(saving: Boolean): Observer<Resource<User>> { return Observer { showLoading(false) when (it) { is Resource.Error -> showError(it.message) is Resource.Loading -> showUser(it.data) is Resource.Success -> showUser(it.data) } if (saving){ finish() } } } private fun showUser(user: User){ id.setText(user.id) name.setText(user.name) email.setText(user.email) } private fun newUser(){ id.setText("") name.setText("") email.setText("") id.isEnabled = true } private fun saveUser(){ id.isEnabled = false showLoading(true) mViewModel.save(id.text.toString(), name.text.toString(), email.text.toString()).observe(this, observer(true)) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { val inflater = menuInflater inflater.inflate(R.menu.user, menu) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if(item?.itemId == R.id.newUser){ newUser() return true }else { return super.onOptionsItemSelected(item) } } private fun showLoading(show: Boolean){ if (show) { progressBar.visibility = VISIBLE idInputLayout.visibility = GONE nameInputLayout.visibility = GONE emailInputLayout.visibility = GONE save.visibility = GONE }else { progressBar.visibility = GONE idInputLayout.visibility = VISIBLE nameInputLayout.visibility = VISIBLE emailInputLayout.visibility = VISIBLE save.visibility = VISIBLE } } private fun showError(error: String){ Toast.makeText(this, error, Toast.LENGTH_LONG).show() } }
apache-2.0
9dda88b9b220155cf8289f394822373d
27.484848
118
0.620433
4.682724
false
false
false
false
Softwee/codeview-android
codeview/src/main/java/io/github/kbiakov/codeview/CodeView.kt
2
7370
package io.github.kbiakov.codeview import android.content.Context import android.graphics.drawable.Drawable import android.graphics.drawable.GradientDrawable import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.AttributeSet import android.view.View import android.widget.RelativeLayout import io.github.kbiakov.codeview.Thread.delayed import io.github.kbiakov.codeview.adapters.AbstractCodeAdapter import io.github.kbiakov.codeview.adapters.CodeWithNotesAdapter import io.github.kbiakov.codeview.adapters.Options import io.github.kbiakov.codeview.highlight.ColorThemeData import io.github.kbiakov.codeview.highlight.color /** * @class CodeView * * View for showing code content with syntax highlighting. * * @author Kirill Biakov */ class CodeView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RelativeLayout(context, attrs, defStyleAttr) { private val vCodeList: RecyclerView private val vShadows: Map<ShadowPosition, View> /** * Primary constructor. */ init { inflate(context, R.layout.layout_code_view, this) attrs?.let(::checkStartAnimation) vCodeList = findViewById<RecyclerView>(R.id.rv_code_content).apply { layoutManager = LinearLayoutManager(context) isNestedScrollingEnabled = true } vShadows = mapOf( ShadowPosition.RightBorder to R.id.shadow_right_border, ShadowPosition.NumBottom to R.id.shadow_num_bottom, ShadowPosition.ContentBottom to R.id.shadow_content_bottom ).mapValues { findViewById<View>(it.value) } } private fun checkStartAnimation(attrs: AttributeSet) { if (visibility == VISIBLE && attrs.isAnimateOnStart(context)) { alpha = Const.Alpha.Invisible animate() .setDuration(Const.DefaultDelay * 5) .alpha(Const.Alpha.Initial) } else { alpha = Const.Alpha.Initial } } private fun AbstractCodeAdapter<*>.checkHighlightAnimation(action: () -> Unit) { if (options.animateOnHighlight) { animate() .setDuration(Const.DefaultDelay * 2) .alpha(Const.Alpha.AlmostInvisible) delayed { animate().alpha(Const.Alpha.Visible) action() } } else { action() } } /** * Highlight code with defined programming language. * It holds the placeholder on view until code is not highlighted. */ private fun highlight() { getAdapter()?.apply { highlight { checkHighlightAnimation(::notifyDataSetChanged) } } } /** * Border shadows will shown if full listing presented. * It helps to see what part of code is scrolled & hidden. * * @param isVisible Is shadows visible */ fun setupShadows(isVisible: Boolean) { val visibility = if (isVisible) VISIBLE else GONE val theme = getOptionsOrDefault().theme vShadows.forEach { (pos, view) -> view.visibility = visibility view.setSafeBackground(pos.createShadow(theme)) } } // - Initialization /** * Prepare view with default adapter & options. */ private fun prepare() = setAdapter(CodeWithNotesAdapter(context)) /** * Initialize with options. * * @param options Options */ fun setOptions(options: Options) = setAdapter(CodeWithNotesAdapter(context, options)) /** * Initialize with adapter. * * @param adapter Adapter */ fun setAdapter(adapter: AbstractCodeAdapter<*>) { vCodeList.adapter = adapter highlight() } // - Options /** * View options accessor. */ fun getOptions() = getAdapter()?.options fun getOptionsOrDefault() = getOptions() ?: Options(context) /** * Update options or initialize if needed. * * @param options Options */ fun updateOptions(options: Options) { getAdapter() ?: setOptions(options) getAdapter()?.options = options setupShadows(options.shadows) } fun updateOptions(body: Options.() -> Unit) { val options = getOptions() ?: getOptionsOrDefault() updateOptions(options.apply(body)) } // - Adapter /** * Code adapter accessor. */ fun getAdapter() = vCodeList.adapter as? AbstractCodeAdapter<*> /** * Update adapter or initialize if needed. * * @param adapter Adapter */ fun updateAdapter(adapter: AbstractCodeAdapter<*>) { adapter.options = getOptionsOrDefault() setAdapter(adapter) } // - Set code /** * Set code content. * * There are two ways before code will be highlighted: * 1) view is not initialized (adapter or options are not set), * prepare with default params & try to classify language * 2) view initialized with some params, language: * a) is set: used defined programming language * b) not set: try to classify * * @param code Code content */ fun setCode(code: String) { getAdapter() ?: prepare() getAdapter()?.updateCode(code) } /** * Set code content. * * There are two ways before code will be highlighted: * 1) view is not initialized, prepare with default params * 2) view initialized with some params, set new language * * @param code Code content * @param language Programming language */ fun setCode(code: String, language: String) { val options = getOptionsOrDefault() updateOptions(options.withLanguage(language)) getAdapter()?.updateCode(code) } companion object { private fun AttributeSet.isAnimateOnStart(context: Context): Boolean { context.theme.obtainStyledAttributes(this, R.styleable.CodeView, 0, 0).apply { val flag = getBoolean(R.styleable.CodeView_animateOnStart, false) recycle() return@isAnimateOnStart flag } return false } private fun View.setSafeBackground(newBackground: Drawable) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { background = newBackground } } } private enum class ShadowPosition { RightBorder, NumBottom, ContentBottom; fun createShadow(theme: ColorThemeData) = when (this) { RightBorder -> GradientDrawable.Orientation.LEFT_RIGHT to theme.bgContent NumBottom -> GradientDrawable.Orientation.TOP_BOTTOM to theme.bgNum ContentBottom -> GradientDrawable.Orientation.TOP_BOTTOM to theme.bgContent }.let { (orientation, color) -> val colors = arrayOf(android.R.color.transparent, color) GradientDrawable(orientation, colors.map(Int::color).toIntArray()) } } } /** * Provide listener to code line clicks. */ interface OnCodeLineClickListener { fun onCodeLineClicked(n: Int, line: String) }
mit
463d9d98b80d1a2169a49dface8bbebb
28.838057
96
0.624559
4.632307
false
false
false
false
lukecwik/incubator-beam
examples/kotlin/src/main/java/org/apache/beam/examples/kotlin/cookbook/TriggerExample.kt
5
27918
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.examples.kotlin.cookbook import com.google.api.services.bigquery.model.TableFieldSchema import com.google.api.services.bigquery.model.TableReference import com.google.api.services.bigquery.model.TableRow import com.google.api.services.bigquery.model.TableSchema import edu.umd.cs.findbugs.annotations.SuppressFBWarnings import org.apache.beam.examples.kotlin.common.ExampleBigQueryTableOptions import org.apache.beam.examples.kotlin.common.ExampleOptions import org.apache.beam.examples.kotlin.common.ExampleUtils import org.apache.beam.sdk.Pipeline import org.apache.beam.sdk.io.TextIO import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO import org.apache.beam.sdk.io.gcp.bigquery.WriteResult import org.apache.beam.sdk.options.Default import org.apache.beam.sdk.options.Description import org.apache.beam.sdk.options.PipelineOptionsFactory import org.apache.beam.sdk.options.StreamingOptions import org.apache.beam.sdk.transforms.DoFn import org.apache.beam.sdk.transforms.GroupByKey import org.apache.beam.sdk.transforms.PTransform import org.apache.beam.sdk.transforms.ParDo import org.apache.beam.sdk.transforms.windowing.* import org.apache.beam.sdk.values.KV import org.apache.beam.sdk.values.PCollection import org.apache.beam.sdk.values.PCollectionList import org.joda.time.Duration import org.joda.time.Instant import java.util.Random import java.util.concurrent.TimeUnit /** * This example illustrates the basic concepts behind triggering. It shows how to use different * trigger definitions to produce partial (speculative) results before all the data is processed and * to control when updated results are produced for late data. The example performs a streaming * analysis of the data coming in from a text file and writes the results to BigQuery. It divides * the data into [windows][Window] to be processed, and demonstrates using various kinds of * [triggers][org.apache.beam.sdk.transforms.windowing.Trigger] to control when the results for * each window are emitted. * * * This example uses a portion of real traffic data from San Diego freeways. It contains readings * from sensor stations set up along each freeway. Each sensor reading includes a calculation of the * 'total flow' across all lanes in that freeway direction. * * * Concepts: * * <pre> * 1. The default triggering behavior * 2. Late data with the default trigger * 3. How to get speculative estimates * 4. Combining late data and speculative estimates </pre> * * * * Before running this example, it will be useful to familiarize yourself with Beam triggers and * understand the concept of 'late data', See: [ * https://beam.apache.org/documentation/programming-guide/#triggers](https://beam.apache.org/documentation/programming-guide/#triggers) * * * The example is configured to use the default BigQuery table from the example common package * (there are no defaults for a general Beam pipeline). You can override them by using the `--bigQueryDataset`, and `--bigQueryTable` options. If the BigQuery table do not exist, the * example will try to create them. * * * The pipeline outputs its results to a BigQuery table. Here are some queries you can use to see * interesting results: Replace `<enter_table_name>` in the query below with the name of the * BigQuery table. Replace `<enter_window_interval>` in the query below with the window * interval. * * * To see the results of the default trigger, Note: When you start up your pipeline, you'll * initially see results from 'late' data. Wait after the window duration, until the first pane of * non-late data has been emitted, to see more interesting results. `SELECT * FROM * enter_table_name WHERE trigger_type = "default" ORDER BY window DESC` * * * To see the late data i.e. dropped by the default trigger, `SELECT * FROM * <enter_table_name> WHERE trigger_type = "withAllowedLateness" and (timing = "LATE" or timing = * "ON_TIME") and freeway = "5" ORDER BY window DESC, processing_time` * * * To see the difference between accumulation mode and discarding mode, `SELECT * FROM * <enter_table_name> WHERE (timing = "LATE" or timing = "ON_TIME") AND (trigger_type = * "withAllowedLateness" or trigger_type = "sequential") and freeway = "5" ORDER BY window DESC, * processing_time` * * * To see speculative results every minute, `SELECT * FROM <enter_table_name> WHERE * trigger_type = "speculative" and freeway = "5" ORDER BY window DESC, processing_time` * * * To see speculative results every five minutes after the end of the window `SELECT * FROM * <enter_table_name> WHERE trigger_type = "sequential" and timing != "EARLY" and freeway = "5" * ORDER BY window DESC, processing_time` * * * To see the first and the last pane for a freeway in a window for all the trigger types, `SELECT * FROM <enter_table_name> WHERE (isFirst = true or isLast = true) ORDER BY window` * * * To reduce the number of results for each query we can add additional where clauses. For * examples, To see the results of the default trigger, `SELECT * FROM <enter_table_name> * WHERE trigger_type = "default" AND freeway = "5" AND window = "<enter_window_interval>"` * * * The example will try to cancel the pipelines on the signal to terminate the process (CTRL-C) * and then exits. */ object TriggerExample { // Numeric value of fixed window duration, in minutes const val WINDOW_DURATION = 30 // Constants used in triggers. // Speeding up ONE_MINUTE or FIVE_MINUTES helps you get an early approximation of results. // ONE_MINUTE is used only with processing time before the end of the window val ONE_MINUTE: Duration = Duration.standardMinutes(1) // FIVE_MINUTES is used only with processing time after the end of the window val FIVE_MINUTES: Duration = Duration.standardMinutes(5) // ONE_DAY is used to specify the amount of lateness allowed for the data elements. val ONE_DAY: Duration = Duration.standardDays(1) /** Defines the BigQuery schema used for the output. */ private val schema: TableSchema get() { val fields = arrayListOf<TableFieldSchema>( TableFieldSchema().setName("trigger_type").setType("STRING"), TableFieldSchema().setName("freeway").setType("STRING"), TableFieldSchema().setName("total_flow").setType("INTEGER"), TableFieldSchema().setName("number_of_records").setType("INTEGER"), TableFieldSchema().setName("window").setType("STRING"), TableFieldSchema().setName("isFirst").setType("BOOLEAN"), TableFieldSchema().setName("isLast").setType("BOOLEAN"), TableFieldSchema().setName("timing").setType("STRING"), TableFieldSchema().setName("event_time").setType("TIMESTAMP"), TableFieldSchema().setName("processing_time").setType("TIMESTAMP") ) return TableSchema().setFields(fields) } /** * This transform demonstrates using triggers to control when data is produced for each window * Consider an example to understand the results generated by each type of trigger. The example * uses "freeway" as the key. Event time is the timestamp associated with the data element and * processing time is the time when the data element gets processed in the pipeline. For freeway * 5, suppose there are 10 elements in the [10:00:00, 10:30:00) window. Key (freeway) | Value * (total_flow) | event time | processing time 5 | 50 | 10:00:03 | 10:00:47 5 | 30 | 10:01:00 | * 10:01:03 5 | 30 | 10:02:00 | 11:07:00 5 | 20 | 10:04:10 | 10:05:15 5 | 60 | 10:05:00 | 11:03:00 * 5 | 20 | 10:05:01 | 11.07:30 5 | 60 | 10:15:00 | 10:27:15 5 | 40 | 10:26:40 | 10:26:43 5 | 60 | * 10:27:20 | 10:27:25 5 | 60 | 10:29:00 | 11:11:00 * * * Beam tracks a watermark which records up to what point in event time the data is complete. * For the purposes of the example, we'll assume the watermark is approximately 15m behind the * current processing time. In practice, the actual value would vary over time based on the * systems knowledge of the current delay and contents of the backlog (data that has not yet been * processed). * * * If the watermark is 15m behind, then the window [10:00:00, 10:30:00) (in event time) would * close at 10:44:59, when the watermark passes 10:30:00. */ internal class CalculateTotalFlow(private val windowDuration: Int) : PTransform<PCollection<KV<String, Int>>, PCollectionList<TableRow>>() { override fun expand(flowInfo: PCollection<KV<String, Int>>): PCollectionList<TableRow> { // Concept #1: The default triggering behavior // By default Beam uses a trigger which fires when the watermark has passed the end of the // window. This would be written {@code Repeatedly.forever(AfterWatermark.pastEndOfWindow())}. // The system also defaults to dropping late data -- data which arrives after the watermark // has passed the event timestamp of the arriving element. This means that the default trigger // will only fire once. // Each pane produced by the default trigger with no allowed lateness will be the first and // last pane in the window, and will be ON_TIME. // The results for the example above with the default trigger and zero allowed lateness // would be: // Key (freeway) | Value (total_flow) | number_of_records | isFirst | isLast | timing // 5 | 260 | 6 | true | true | ON_TIME // At 11:03:00 (processing time) the system watermark may have advanced to 10:54:00. As a // result, when the data record with event time 10:05:00 arrives at 11:03:00, it is considered // late, and dropped. val defaultTriggerResults = flowInfo .apply( "Default", Window // The default window duration values work well if you're running the default // input // file. You may want to adjust the window duration otherwise. .into<KV<String, Int>>( FixedWindows.of(Duration.standardMinutes(windowDuration.toLong()))) // The default trigger first emits output when the system's watermark passes // the end // of the window. .triggering(Repeatedly.forever(AfterWatermark.pastEndOfWindow())) // Late data is dropped .withAllowedLateness(Duration.ZERO) // Discard elements after emitting each pane. // With no allowed lateness and the specified trigger there will only be a // single // pane, so this doesn't have a noticeable effect. See concept 2 for more // details. .discardingFiredPanes()) .apply(TotalFlow("default")) // Concept #2: Late data with the default trigger // This uses the same trigger as concept #1, but allows data that is up to ONE_DAY late. This // leads to each window staying open for ONE_DAY after the watermark has passed the end of the // window. Any late data will result in an additional pane being fired for that same window. // The first pane produced will be ON_TIME and the remaining panes will be LATE. // To definitely get the last pane when the window closes, use // .withAllowedLateness(ONE_DAY, ClosingBehavior.FIRE_ALWAYS). // The results for the example above with the default trigger and ONE_DAY allowed lateness // would be: // Key (freeway) | Value (total_flow) | number_of_records | isFirst | isLast | timing // 5 | 260 | 6 | true | false | ON_TIME // 5 | 60 | 1 | false | false | LATE // 5 | 30 | 1 | false | false | LATE // 5 | 20 | 1 | false | false | LATE // 5 | 60 | 1 | false | false | LATE val withAllowedLatenessResults = flowInfo .apply( "WithLateData", Window.into<KV<String, Int>>( FixedWindows.of(Duration.standardMinutes(windowDuration.toLong()))) // Late data is emitted as it arrives .triggering(Repeatedly.forever(AfterWatermark.pastEndOfWindow())) // Once the output is produced, the pane is dropped and we start preparing the // next // pane for the window .discardingFiredPanes() // Late data is handled up to one day .withAllowedLateness(ONE_DAY)) .apply(TotalFlow("withAllowedLateness")) // Concept #3: How to get speculative estimates // We can specify a trigger that fires independent of the watermark, for instance after // ONE_MINUTE of processing time. This allows us to produce speculative estimates before // all the data is available. Since we don't have any triggers that depend on the watermark // we don't get an ON_TIME firing. Instead, all panes are either EARLY or LATE. // We also use accumulatingFiredPanes to build up the results across each pane firing. // The results for the example above for this trigger would be: // Key (freeway) | Value (total_flow) | number_of_records | isFirst | isLast | timing // 5 | 80 | 2 | true | false | EARLY // 5 | 100 | 3 | false | false | EARLY // 5 | 260 | 6 | false | false | EARLY // 5 | 320 | 7 | false | false | LATE // 5 | 370 | 9 | false | false | LATE // 5 | 430 | 10 | false | false | LATE val speculativeResults = flowInfo .apply( "Speculative", Window.into<KV<String, Int>>( FixedWindows.of(Duration.standardMinutes(windowDuration.toLong()))) // Trigger fires every minute. .triggering( Repeatedly.forever( AfterProcessingTime.pastFirstElementInPane() // Speculative every ONE_MINUTE .plusDelayOf(ONE_MINUTE))) // After emitting each pane, it will continue accumulating the elements so // that each // approximation includes all of the previous data in addition to the newly // arrived // data. .accumulatingFiredPanes() .withAllowedLateness(ONE_DAY)) .apply(TotalFlow("speculative")) // Concept #4: Combining late data and speculative estimates // We can put the previous concepts together to get EARLY estimates, an ON_TIME result, // and LATE updates based on late data. // Each time a triggering condition is satisfied it advances to the next trigger. // If there are new elements this trigger emits a window under following condition: // > Early approximations every minute till the end of the window. // > An on-time firing when the watermark has passed the end of the window // > Every five minutes of late data. // Every pane produced will either be EARLY, ON_TIME or LATE. // The results for the example above for this trigger would be: // Key (freeway) | Value (total_flow) | number_of_records | isFirst | isLast | timing // 5 | 80 | 2 | true | false | EARLY // 5 | 100 | 3 | false | false | EARLY // 5 | 260 | 6 | false | false | EARLY // [First pane fired after the end of the window] // 5 | 320 | 7 | false | false | ON_TIME // 5 | 430 | 10 | false | false | LATE // For more possibilities of how to build advanced triggers, see {@link Trigger}. val sequentialResults = flowInfo .apply( "Sequential", Window.into<KV<String, Int>>( FixedWindows.of(Duration.standardMinutes(windowDuration.toLong()))) .triggering( AfterEach.inOrder( Repeatedly.forever( AfterProcessingTime.pastFirstElementInPane() // Speculative every ONE_MINUTE .plusDelayOf(ONE_MINUTE)) .orFinally(AfterWatermark.pastEndOfWindow()), Repeatedly.forever( AfterProcessingTime.pastFirstElementInPane() // Late data every FIVE_MINUTES .plusDelayOf(FIVE_MINUTES)))) .accumulatingFiredPanes() // For up to ONE_DAY .withAllowedLateness(ONE_DAY)) .apply(TotalFlow("sequential")) // Adds the results generated by each trigger type to a PCollectionList. return PCollectionList.of<TableRow>(defaultTriggerResults) .and(withAllowedLatenessResults) .and(speculativeResults) .and(sequentialResults) } } ////////////////////////////////////////////////////////////////////////////////////////////////// // The remaining parts of the pipeline are needed to produce the output for each // concept above. Not directly relevant to understanding the trigger examples. /** * Calculate total flow and number of records for each freeway and format the results to TableRow * objects, to save to BigQuery. */ @SuppressFBWarnings("NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION") // kotlin-specific spotbugs false positive internal class TotalFlow(private val triggerType: String) : PTransform<PCollection<KV<String, Int>>, PCollection<TableRow>>() { override fun expand(flowInfo: PCollection<KV<String, Int>>): PCollection<TableRow> { val flowPerFreeway = flowInfo.apply(GroupByKey.create()) val results = flowPerFreeway.apply( ParDo.of( object : DoFn<KV<String, Iterable<Int>>, KV<String, String>>() { @ProcessElement @Throws(Exception::class) fun processElement(c: ProcessContext) { val flows = c.element().value var sum = 0 var numberOfRecords = 0L for (value in flows) { sum += value numberOfRecords++ } c.output(KV.of<String, String>(c.element().key, "$sum,$numberOfRecords")) } })) return results.apply(ParDo.of(FormatTotalFlow(triggerType))) } } /** * Format the results of the Total flow calculation to a TableRow, to save to BigQuery. Adds the * triggerType, pane information, processing time and the window timestamp. */ internal class FormatTotalFlow(private val triggerType: String) : DoFn<KV<String, String>, TableRow>() { @ProcessElement @Throws(Exception::class) fun processElement(c: ProcessContext, window: BoundedWindow) { val values = c.element().value.split(",".toRegex()).toTypedArray() val row = TableRow() .set("trigger_type", triggerType) .set("freeway", c.element().key) .set("total_flow", Integer.parseInt(values[0])) .set("number_of_records", java.lang.Long.parseLong(values[1])) .set("window", window.toString()) .set("isFirst", c.pane().isFirst) .set("isLast", c.pane().isLast) .set("timing", c.pane().timing.toString()) .set("event_time", c.timestamp().toString()) .set("processing_time", Instant.now().toString()) c.output(row) } } /** * Extract the freeway and total flow in a reading. Freeway is used as key since we are * calculating the total flow for each freeway. */ internal class ExtractFlowInfo : DoFn<String, KV<String, Int>>() { @ProcessElement @Throws(Exception::class) fun processElement(c: ProcessContext) { val laneInfo = c.element().split(",".toRegex()).toTypedArray() if ("timestamp" == laneInfo[0]) { // Header row return } if (laneInfo.size < VALID_NUM_FIELDS) { // Skip the invalid input. return } val freeway = laneInfo[2] val totalFlow = tryIntegerParse(laneInfo[7]) // Ignore the records with total flow 0 to easily understand the working of triggers. // Skip the records with total flow -1 since they are invalid input. if (totalFlow == null || totalFlow <= 0) { return } c.output(KV.of<String, Int>(freeway, totalFlow)) } companion object { private const val VALID_NUM_FIELDS = 50 } } /** Inherits standard configuration options. */ interface TrafficFlowOptions : ExampleOptions, ExampleBigQueryTableOptions, StreamingOptions { @get:Description("Input file to read from") @get:Default.String("gs://apache-beam-samples/traffic_sensor/Freeways-5Minaa2010-01-01_to_2010-02-15.csv") var input: String @get:Description("Numeric value of window duration for fixed windows, in minutes") @get:Default.Integer(WINDOW_DURATION) var windowDuration: Int? } @Throws(Exception::class) @JvmStatic fun main(args: Array<String>) { val options = PipelineOptionsFactory.fromArgs(*args).withValidation() as TrafficFlowOptions options.isStreaming = true options.bigQuerySchema = schema val exampleUtils = ExampleUtils(options) exampleUtils.setup() val pipeline = Pipeline.create(options) val tableRef = getTableReference( options.project, options.bigQueryDataset, options.bigQueryTable) val resultList = pipeline .apply("ReadMyFile", TextIO.read().from(options.input)) .apply("InsertRandomDelays", ParDo.of(InsertDelays())) .apply(ParDo.of(ExtractFlowInfo())) .apply(CalculateTotalFlow(options.windowDuration!!)) for (i in 0 until resultList.size()) { resultList.get(i).apply<WriteResult>(BigQueryIO.writeTableRows().to(tableRef).withSchema(schema)) } val result = pipeline.run() // ExampleUtils will try to cancel the pipeline and the injector before the program exits. exampleUtils.waitToFinish(result) } /** Add current time to each record. Also insert a delay at random to demo the triggers. */ class InsertDelays : DoFn<String, String>() { @ProcessElement @Throws(Exception::class) fun processElement(c: ProcessContext) { var timestamp = Instant.now() val random = Random() if (random.nextDouble() < THRESHOLD) { val range = MAX_DELAY - MIN_DELAY val delayInMinutes = random.nextInt(range) + MIN_DELAY val delayInMillis = TimeUnit.MINUTES.toMillis(delayInMinutes.toLong()) timestamp = Instant(timestamp.millis - delayInMillis) } c.outputWithTimestamp(c.element(), timestamp) } companion object { private const val THRESHOLD = 0.001 // MIN_DELAY and MAX_DELAY in minutes. private const val MIN_DELAY = 1 private const val MAX_DELAY = 100 } } /** Sets the table reference. */ private fun getTableReference(project: String, dataset: String, table: String): TableReference { return TableReference().apply { projectId = project datasetId = dataset tableId = table } } private fun tryIntegerParse(number: String): Int? { return try { Integer.parseInt(number) } catch (e: NumberFormatException) { null } } }
apache-2.0
c2cdd554de042fe7e74f4ca644400e3a
52.076046
182
0.570492
4.818433
false
false
false
false
http4k/http4k
http4k-serverless/lambda/integration-test/src/test/kotlin/org/http4k/serverless/lambda/testing/setup/aws/apigateway/AwsApiGateway.kt
1
3217
package org.http4k.serverless.lambda.testing.setup.aws.apigateway import dev.forkhandles.result4k.Result import dev.forkhandles.result4k.map import org.http4k.core.HttpHandler import org.http4k.core.Uri import org.http4k.core.then import org.http4k.filter.ClientFilters import org.http4k.filter.SetAwsServiceUrl import org.http4k.serverless.lambda.testing.setup.aws.RemoteFailure import org.http4k.serverless.lambda.testing.setup.aws.apigatewayv2.ApiDetails import org.http4k.serverless.lambda.testing.setup.aws.apigatewayv2.ApiId import org.http4k.serverless.lambda.testing.setup.aws.apigatewayv2.ApiName import org.http4k.serverless.lambda.testing.setup.aws.apigatewayv2.Stage import org.http4k.serverless.lambda.testing.setup.aws.getOrThrow import org.http4k.serverless.lambda.testing.setup.aws.lambda.Region interface AwsApiGateway { operator fun <R : Any> invoke(action: AwsApiGatewayAction<R>): Result<R, RemoteFailure> companion object } fun AwsApiGateway.Companion.Http(rawHttp: HttpHandler, region: Region) = object : AwsApiGateway { private val http = ClientFilters.SetAwsServiceUrl("apigateway", region.name).then(rawHttp) override fun <R : Any> invoke(action: AwsApiGatewayAction<R>) = action.toResult( http(action.toRequest()) ) } fun AwsApiGateway.createApi(name: ApiName, region: Region) = this(CreateApi(name)).map { toApiDetails(it, region) }.getOrThrow() fun AwsApiGateway.listApis(region: Region): List<ApiDetails> = this(ListApis()).map { it._embedded.item.map { item -> toApiDetails(item, region) } }.getOrThrow() fun AwsApiGateway.delete(apiId: ApiId) = this(DeleteApi(apiId)) fun AwsApiGateway.listResources(apiId: ApiId) = this(ListRootResource(apiId)).getOrThrow() fun AwsApiGateway.createResource(apiId: ApiId, parentResource: RestResourceDetails) = this(CreateResource(apiId, parentResource)).getOrThrow() fun AwsApiGateway.createMethod(apiId: ApiId, resource: RestResourceDetails) = this(CreateMethod(apiId, resource)).getOrThrow() fun AwsApiGateway.createIntegration(apiId: ApiId, resource: RestResourceDetails, functionArn: String, region: Region) = this(CreateIntegration(apiId, resource, functionArn, region)).getOrThrow() fun AwsApiGateway.createIntegrationResponse(apiId: ApiId, resource: RestResourceDetails) = this(CreateIntegrationResponse(apiId, resource)).getOrThrow() fun AwsApiGateway.createStage(apiId: ApiId, stage: Stage, deploymentId: DeploymentId) = this(CreateStage(apiId, stage, deploymentId)).getOrThrow() data class RestApiDetails(val name: String, val id: String) data class ListApiResponse(val _embedded: EmbeddedDetails) data class EmbeddedDetails(val item: List<RestApiDetails>) data class RestResourceDetails(val id: String, val path: String) data class ListResourcesResponse(val _embedded: EmbeddedResourceDetails) data class EmbeddedResourceDetails(val item: RestResourceDetails) data class DeploymentName(val value: String) data class DeploymentId(val id: String) private fun toApiDetails(it: RestApiDetails, region: Region) = ApiDetails( ApiName(it.name), ApiId(it.id), apiEndpoint = Uri.of("https://${it.id}.execute-api.${region.name}.amazonaws.com/default") )
apache-2.0
39bd2007d0059a746e3e4e2b6a62ef49
50.063492
119
0.790488
3.766979
false
true
false
false